@runappsai/agent 0.1.5 → 0.1.7
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 +109 -101
- package/dist/agent.d.ts +1 -0
- package/dist/agent.js +27 -13
- package/dist/agent.umd.js +147 -138
- package/dist/chat.js +65 -23
- package/dist/context.js +14 -3
- package/dist/dialogs.js +2 -0
- package/dist/file-guard.js +1 -1
- package/dist/file-tools.d.ts +1 -1
- package/dist/file-tools.js +9 -5
- package/dist/index.cjs +138 -84
- package/dist/index.d.ts +1 -1
- package/dist/sandbox.d.ts +15 -9
- package/dist/sandbox.js +105 -75
- package/dist/types.d.ts +32 -1
- package/dist/ui.cjs +53 -21
- package/dist/workspace.js +1 -1
- package/docs/agent.md +2 -2
- package/docs/chat-ui.md +2 -2
- package/docs/node.md +1 -1
- package/docs/reference.md +2 -2
- package/docs/skills.md +1 -1
- package/docs/tools.md +27 -6
- package/docs/workspace.md +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -291,11 +291,20 @@ ${input.agentsMd.trim()}
|
|
|
291
291
|
}
|
|
292
292
|
if (input.hasSandbox) {
|
|
293
293
|
rules.push("For arithmetic, dates, counting, parsing or any other computation, run run_js instead of working it out in your head, and report the computed result.");
|
|
294
|
+
if (input.tools.some((t) => t.name === "read_file")) rules.push("Inside run_js, tools.read_file({ path }) returns the whole file and tools.list_files the whole list; the output limits apply only when you call them yourself.");
|
|
294
295
|
}
|
|
295
296
|
out.push("# How to work\n" + rules.map((r) => `- ${r}`).join("\n"));
|
|
297
|
+
const has = (name) => input.tools.some((t) => t.name === name);
|
|
296
298
|
if (input.workspaceDescription) {
|
|
299
|
+
const look = ["list_files", "read_file"].filter(has);
|
|
300
|
+
const uses = [
|
|
301
|
+
look.length ? `${look.join(" and ")} to look around` : "",
|
|
302
|
+
has("edit_file") ? "edit_file for small changes (each oldText must match exactly once)" : "",
|
|
303
|
+
has("write_file") ? "write_file for new files or rewrites" : ""
|
|
304
|
+
].filter(Boolean);
|
|
297
305
|
out.push(
|
|
298
|
-
"# Workspace\nYou have a file tree (absolute POSIX paths).\n" + input.workspaceDescription +
|
|
306
|
+
"# Workspace\nYou have a file tree (absolute POSIX paths).\n" + input.workspaceDescription + (uses.length ? `
|
|
307
|
+
Use ${uses.join(", ")}.` : "") + (has("write_file") && has("edit_file") ? " A reply has an output limit: a file longer than you can emit in one call is written in parts \u2014 write_file the first part, then edit_file to append the rest (oldText = the last lines written) \u2014 never one huge write_file." : "") + (input.canWrite && input.memoryPath ? `
|
|
299
308
|
To remember something for later conversations (a preference, a decision, a fact about the user's project), append a short line to ${input.memoryPath}; it is shown to you at the start of every conversation.` : "")
|
|
300
309
|
);
|
|
301
310
|
}
|
|
@@ -305,10 +314,10 @@ Your notes from earlier conversations (${input.memoryPath ?? "/memory/notes.md"}
|
|
|
305
314
|
` + input.memory.trim());
|
|
306
315
|
}
|
|
307
316
|
const visible = input.skills.filter((s) => !s.disableModelInvocation);
|
|
308
|
-
if (visible.length) {
|
|
317
|
+
if (visible.length && has("read_file")) {
|
|
309
318
|
const esc = (t) => t.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
310
319
|
out.push(
|
|
311
|
-
"# Skills\nThe following skills provide specialized instructions for specific tasks.\nUse read_file to load a skill's file when the task matches its description.\nWhen a skill file references a relative path, resolve it against the skill directory (the folder of SKILL.md) and use that absolute path in tool calls." + (input.hasSandbox ? "\nThe only runtime here is run_js (JavaScript in a sandbox: no shell, no Python, no network). A skill's scripts written for another language (Python, shell, Ruby\u2026) cannot be run as they are: read the script, port its logic to JavaScript and run that with run_js, keeping the same inputs, outputs and behaviour (
|
|
320
|
+
"# Skills\nThe following skills provide specialized instructions for specific tasks.\nUse read_file to load a skill's file when the task matches its description.\nWhen a skill file references a relative path, resolve it against the skill directory (the folder of SKILL.md) and use that absolute path in tool calls." + (input.hasSandbox ? "\nThe only runtime here is run_js (JavaScript in a sandbox: no shell, no Python, no network). A skill's scripts written for another language (Python, shell, Ruby\u2026) cannot be run as they are: read the script, port its logic to JavaScript and run that with run_js, keeping the same inputs, outputs and behaviour (tools.read_file for files the script reads; browser-safe APIs only \u2014 no npm imports, no subprocesses, no network); tell the user it was ported. If a script truly needs what the sandbox lacks (a binary, a network service), say so and do the part that can be done." : "\nThere is no runtime for scripts here: a skill's scripts (Python, shell, JavaScript\u2026) cannot be executed; follow their logic by hand where feasible and say so, or tell the user what cannot be done.") + "\n\n<available_skills>\n" + visible.map((s) => ` <skill>
|
|
312
321
|
<name>${esc(s.name)}</name>
|
|
313
322
|
<description>${esc(s.description)}</description>
|
|
314
323
|
<location>${esc(s.path)}</location>
|
|
@@ -2629,11 +2638,12 @@ function fileTools(ws, opts = {}) {
|
|
|
2629
2638
|
properties: { path: { type: "string", description: "Folder to list. Default /" } },
|
|
2630
2639
|
additionalProperties: false
|
|
2631
2640
|
},
|
|
2632
|
-
async execute({ path }) {
|
|
2641
|
+
async execute({ path }, ctx) {
|
|
2633
2642
|
const files2 = await ws.list(path || "/");
|
|
2634
2643
|
if (!files2.length) return `No files under ${normalizePath(path || "/")}.`;
|
|
2635
|
-
const
|
|
2636
|
-
|
|
2644
|
+
const max = ctx?.parentId ? Infinity : MAX_LIST;
|
|
2645
|
+
const lines = files2.slice(0, max).map((f) => `${f.path} (${f.size} B)`);
|
|
2646
|
+
if (files2.length > max) lines.push(`
|
|
2637
2647
|
[${MAX_LIST} entries limit reached (${files2.length} in all). List a sub-folder.]`);
|
|
2638
2648
|
return lines.join("\n");
|
|
2639
2649
|
}
|
|
@@ -2692,13 +2702,14 @@ function fileTools(ws, opts = {}) {
|
|
|
2692
2702
|
await files.saw(normalizePath(path), { start: total + 1, end: total, total });
|
|
2693
2703
|
return `Offset ${start} is beyond end of file (${total} lines total)`;
|
|
2694
2704
|
}
|
|
2695
|
-
const
|
|
2705
|
+
const whole = !!ctx?.parentId;
|
|
2706
|
+
const want = whole ? limit ?? Infinity : limit !== void 0 ? Math.min(limit, MAX_READ_LINES) : MAX_READ_LINES;
|
|
2696
2707
|
const out = [];
|
|
2697
2708
|
let bytes = 0;
|
|
2698
2709
|
let end = start - 1;
|
|
2699
2710
|
for (let i = start - 1; i < total && out.length < want; i++) {
|
|
2700
2711
|
const b = new TextEncoder().encode(lines[i]).byteLength + 1;
|
|
2701
|
-
if (bytes + b > MAX_READ_BYTES && out.length > 0) break;
|
|
2712
|
+
if (!whole && bytes + b > MAX_READ_BYTES && out.length > 0) break;
|
|
2702
2713
|
out.push(lines[i]);
|
|
2703
2714
|
bytes += b;
|
|
2704
2715
|
end = i + 1;
|
|
@@ -3028,20 +3039,14 @@ if (isNode) {
|
|
|
3028
3039
|
send = function (m) { self.postMessage(m); };
|
|
3029
3040
|
}
|
|
3030
3041
|
var pending = new Map(), seq = 0;
|
|
3031
|
-
function
|
|
3042
|
+
function callTool(name, args) {
|
|
3032
3043
|
return new Promise(function (resolve, reject) {
|
|
3033
3044
|
var id = ++seq;
|
|
3034
3045
|
pending.set(id, { resolve: resolve, reject: reject });
|
|
3035
|
-
send({ type: "
|
|
3046
|
+
send({ type: "tool", id: id, name: name, args: args });
|
|
3036
3047
|
});
|
|
3037
3048
|
}
|
|
3038
|
-
var
|
|
3039
|
-
read: function (p) { return rpc("read", [p]); },
|
|
3040
|
-
write: function (p, c) { return rpc("write", [p, c]); },
|
|
3041
|
-
list: function (p) { return rpc("list", [p || "/"]); },
|
|
3042
|
-
exists: function (p) { return rpc("exists", [p]); },
|
|
3043
|
-
remove: function (p) { return rpc("delete", [p]); },
|
|
3044
|
-
};
|
|
3049
|
+
var tools = {};
|
|
3045
3050
|
var logs = [], logChars = 0, maxLog = 20000;
|
|
3046
3051
|
function fmt(a) {
|
|
3047
3052
|
if (typeof a === "string") return a;
|
|
@@ -3075,8 +3080,18 @@ async function run(msg) {
|
|
|
3075
3080
|
var start = Date.now();
|
|
3076
3081
|
try {
|
|
3077
3082
|
var AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;
|
|
3078
|
-
|
|
3079
|
-
|
|
3083
|
+
(msg.tools || []).forEach(function (name) {
|
|
3084
|
+
tools[name] = function (args) { return callTool(name, args === undefined ? {} : args); };
|
|
3085
|
+
});
|
|
3086
|
+
var fn = new AsyncFunction("input", "console", "tools", msg.code);
|
|
3087
|
+
// A tool the code may not call says so, rather than "tools.x is not a function".
|
|
3088
|
+
var offered = new Proxy(Object.freeze(tools), {
|
|
3089
|
+
get: function (t, k) {
|
|
3090
|
+
if (k in t || typeof k !== "string" || k === "then" || k === "toJSON") return t[k];
|
|
3091
|
+
return function () { return Promise.reject(new Error("tools." + k + " cannot be called from run_js; call it directly if you have it")); };
|
|
3092
|
+
},
|
|
3093
|
+
});
|
|
3094
|
+
var value = await fn(msg.input, sandboxConsole, offered);
|
|
3080
3095
|
send({ type: "done", result: serialize(value), logs: logs.join("\\n"), durationMs: Date.now() - start });
|
|
3081
3096
|
} catch (e) {
|
|
3082
3097
|
send({ type: "error", error: (e && e.stack) || String(e), logs: logs.join("\\n"), durationMs: Date.now() - start });
|
|
@@ -3084,11 +3099,15 @@ async function run(msg) {
|
|
|
3084
3099
|
}
|
|
3085
3100
|
function onMessage(m) {
|
|
3086
3101
|
if (m.type === "run") run(m);
|
|
3087
|
-
else if (m.type === "
|
|
3102
|
+
else if (m.type === "toolResult") {
|
|
3088
3103
|
var p = pending.get(m.id);
|
|
3089
3104
|
if (!p) return;
|
|
3090
3105
|
pending.delete(m.id);
|
|
3091
|
-
if (m.ok) p.resolve(m.value);
|
|
3106
|
+
if (m.ok) { p.resolve(m.value); return; }
|
|
3107
|
+
// The host's words, without this program's frames in them.
|
|
3108
|
+
var err = new Error(m.error);
|
|
3109
|
+
err.stack = m.error;
|
|
3110
|
+
p.reject(err);
|
|
3092
3111
|
}
|
|
3093
3112
|
}
|
|
3094
3113
|
if (isNode) port.on("message", onMessage); else self.onmessage = function (ev) { onMessage(ev.data); };
|
|
@@ -3103,6 +3122,12 @@ async function spawn() {
|
|
|
3103
3122
|
onMessage: (fn) => {
|
|
3104
3123
|
w2.onmessage = (ev) => fn(ev.data);
|
|
3105
3124
|
},
|
|
3125
|
+
onFail: (fn) => {
|
|
3126
|
+
w2.onerror = (ev) => {
|
|
3127
|
+
ev.preventDefault();
|
|
3128
|
+
fn(ev.message || "The sandbox worker could not run; the page's Content-Security-Policy may block it.");
|
|
3129
|
+
};
|
|
3130
|
+
},
|
|
3106
3131
|
terminate: () => w2.terminate()
|
|
3107
3132
|
};
|
|
3108
3133
|
}
|
|
@@ -3112,85 +3137,90 @@ async function spawn() {
|
|
|
3112
3137
|
return {
|
|
3113
3138
|
post: (m) => w.postMessage(m),
|
|
3114
3139
|
onMessage: (fn) => w.on("message", (m) => fn(m)),
|
|
3140
|
+
onFail: (fn) => {
|
|
3141
|
+
w.on("error", (e) => fn(e instanceof Error ? e.message : String(e)));
|
|
3142
|
+
w.on("exit", () => fn("The sandbox worker exited before the code finished."));
|
|
3143
|
+
},
|
|
3115
3144
|
terminate: () => w.terminate()
|
|
3116
3145
|
};
|
|
3117
3146
|
}
|
|
3118
|
-
async function runInSandbox(
|
|
3147
|
+
async function runInSandbox(code, input, opts = {}) {
|
|
3119
3148
|
const timeoutMs = Math.min(6e4, Math.max(100, opts.timeoutMs ?? 1e4));
|
|
3120
3149
|
const worker = await spawn();
|
|
3121
3150
|
const started = Date.now();
|
|
3151
|
+
const bridge = opts.bridge;
|
|
3122
3152
|
return new Promise((resolve) => {
|
|
3123
3153
|
let settled = false;
|
|
3154
|
+
const running = new AbortController();
|
|
3124
3155
|
const finish = (r) => {
|
|
3125
3156
|
if (settled) return;
|
|
3126
3157
|
settled = true;
|
|
3127
3158
|
clearTimeout(timer);
|
|
3128
3159
|
opts.signal?.removeEventListener("abort", onAbort);
|
|
3129
3160
|
worker.terminate();
|
|
3161
|
+
running.abort();
|
|
3130
3162
|
resolve(r);
|
|
3131
3163
|
};
|
|
3132
|
-
|
|
3164
|
+
let left = timeoutMs, resumed = 0, waiting = 0;
|
|
3165
|
+
let timer;
|
|
3166
|
+
const startClock = () => {
|
|
3167
|
+
resumed = Date.now();
|
|
3168
|
+
timer = setTimeout(() => finish({ ok: false, logs: "", error: `Timed out after ${timeoutMs} ms`, durationMs: Date.now() - started }), Math.max(0, left));
|
|
3169
|
+
};
|
|
3170
|
+
const whileWaiting = async (work) => {
|
|
3171
|
+
if (waiting++ === 0) {
|
|
3172
|
+
clearTimeout(timer);
|
|
3173
|
+
left -= Date.now() - resumed;
|
|
3174
|
+
}
|
|
3175
|
+
try {
|
|
3176
|
+
return await work();
|
|
3177
|
+
} finally {
|
|
3178
|
+
if (--waiting === 0 && !settled) startClock();
|
|
3179
|
+
}
|
|
3180
|
+
};
|
|
3181
|
+
startClock();
|
|
3133
3182
|
const onAbort = () => finish({ ok: false, logs: "", error: "Aborted", durationMs: Date.now() - started });
|
|
3134
3183
|
opts.signal?.addEventListener("abort", onAbort, { once: true });
|
|
3184
|
+
if (opts.signal?.aborted) return onAbort();
|
|
3185
|
+
worker.onFail((why) => finish({ ok: false, logs: "", error: why, durationMs: Date.now() - started }));
|
|
3186
|
+
let toolCalls = 0;
|
|
3187
|
+
let queue = Promise.resolve();
|
|
3188
|
+
const callTool = (name, args) => {
|
|
3189
|
+
if (!bridge?.names.includes(name)) throw new Error(`there is no tool named "${name}"`);
|
|
3190
|
+
const max = bridge.max ?? 50;
|
|
3191
|
+
if (++toolCalls > max) throw new Error(`this run has used its ${max} tool calls; return what you have and continue in another run_js`);
|
|
3192
|
+
const turn = queue.then(() => {
|
|
3193
|
+
if (settled) throw new Error("the code has finished");
|
|
3194
|
+
return bridge.call(name, args, running.signal);
|
|
3195
|
+
});
|
|
3196
|
+
queue = turn.catch(() => {
|
|
3197
|
+
});
|
|
3198
|
+
return turn;
|
|
3199
|
+
};
|
|
3135
3200
|
worker.onMessage(async (m) => {
|
|
3136
3201
|
if (m.type === "done") {
|
|
3137
3202
|
finish({ ok: true, result: m.result, logs: m.logs ?? "", durationMs: m.durationMs ?? Date.now() - started });
|
|
3138
3203
|
} else if (m.type === "error") {
|
|
3139
3204
|
finish({ ok: false, error: String(m.error), logs: m.logs ?? "", durationMs: m.durationMs ?? Date.now() - started });
|
|
3140
|
-
} else if (m.type === "
|
|
3141
|
-
|
|
3142
|
-
|
|
3143
|
-
|
|
3144
|
-
|
|
3145
|
-
|
|
3146
|
-
switch (m.op) {
|
|
3147
|
-
case "read": {
|
|
3148
|
-
const p = normalizePath(String(args[0]));
|
|
3149
|
-
const doc = await ws.readAsText(p);
|
|
3150
|
-
if (!doc) throw new Error(`${p} is a binary file`);
|
|
3151
|
-
await opts.guard?.saw(p, { text: doc.kind === "text" ? doc.text : void 0 });
|
|
3152
|
-
value = doc.text;
|
|
3153
|
-
break;
|
|
3154
|
-
}
|
|
3155
|
-
case "write": {
|
|
3156
|
-
const p = normalizePath(String(args[0]));
|
|
3157
|
-
await opts.guard?.check(p, "overwrite");
|
|
3158
|
-
await ws.write(p, String(args[1] ?? ""));
|
|
3159
|
-
await opts.guard?.wrote(p);
|
|
3160
|
-
value = true;
|
|
3161
|
-
break;
|
|
3162
|
-
}
|
|
3163
|
-
case "list":
|
|
3164
|
-
value = (await ws.list(String(args[0] ?? "/"))).map((f) => ({ path: f.path, size: f.size }));
|
|
3165
|
-
break;
|
|
3166
|
-
case "exists":
|
|
3167
|
-
value = await ws.exists(String(args[0]));
|
|
3168
|
-
break;
|
|
3169
|
-
case "delete": {
|
|
3170
|
-
const path = normalizePath(String(args[0]));
|
|
3171
|
-
await opts.guard?.check(path, "delete");
|
|
3172
|
-
if (opts.confirmDelete && !await opts.confirmDelete(path)) throw new Error(`the user declined deleting ${path}`);
|
|
3173
|
-
await ws.delete(path);
|
|
3174
|
-
opts.guard?.forget(path);
|
|
3175
|
-
value = true;
|
|
3176
|
-
break;
|
|
3177
|
-
}
|
|
3178
|
-
default:
|
|
3179
|
-
throw new Error(`unknown fs op ${String(m.op)}`);
|
|
3205
|
+
} else if (m.type === "tool") {
|
|
3206
|
+
void whileWaiting(async () => {
|
|
3207
|
+
try {
|
|
3208
|
+
worker.post({ type: "toolResult", id: m.id, ok: true, value: await callTool(String(m.name), m.args) });
|
|
3209
|
+
} catch (e) {
|
|
3210
|
+
worker.post({ type: "toolResult", id: m.id, ok: false, error: e.message });
|
|
3180
3211
|
}
|
|
3181
|
-
|
|
3182
|
-
} catch (e) {
|
|
3183
|
-
worker.post({ type: "fsResult", id, ok: false, error: e.message });
|
|
3184
|
-
}
|
|
3212
|
+
});
|
|
3185
3213
|
}
|
|
3186
3214
|
});
|
|
3187
|
-
worker.post({ type: "run", code, input, network: !!opts.network, maxLogChars: opts.maxLogChars });
|
|
3215
|
+
worker.post({ type: "run", code, input, network: !!opts.network, maxLogChars: opts.maxLogChars, tools: bridge?.names });
|
|
3188
3216
|
});
|
|
3189
3217
|
}
|
|
3190
|
-
function sandboxTool(
|
|
3218
|
+
function sandboxTool(opts = {}) {
|
|
3219
|
+
const maxCode = opts.maxCodeChars ?? 2e4;
|
|
3191
3220
|
return defineTool({
|
|
3192
3221
|
name: "run_js",
|
|
3193
|
-
description:
|
|
3222
|
+
description: `Run JavaScript in a sandbox (no DOM, no network) and get back what it returns plus its console output. Use it for arithmetic, dates, parsing, data transformation and to run a skill's scripts instead of working them out by hand. The code is the body of an async function: use \`return\` for the result (JSON), \`console.log\` for notes. Available: \`input\` (the input argument), and \`tools\` \u2014 \`await tools.<name>(args)\` calls any of your other tools with the same arguments and rules, one at a time, and resolves with its full text result (it throws when the call fails or the user declines; do not work around a decline). A tool that cannot be called from code says so when called. Up to ${opts.maxToolCalls ?? 50} calls per run and ${maxCode} characters of code; time spent waiting for a tool does not count against the time limit.`,
|
|
3223
|
+
guidelines: "A large result you only need to compute over (logs, orders, a long list): fetch it inside run_js with `tools` and return the numbers, so the data never passes through this conversation. Parse a tool's text there rather than assuming a shape: try one call and look at it first.",
|
|
3194
3224
|
parameters: {
|
|
3195
3225
|
type: "object",
|
|
3196
3226
|
properties: {
|
|
@@ -3203,13 +3233,22 @@ function sandboxTool(ws, opts = {}) {
|
|
|
3203
3233
|
},
|
|
3204
3234
|
maxResultChars: 24e3,
|
|
3205
3235
|
async execute({ code, input, timeout_ms }, ctx) {
|
|
3206
|
-
|
|
3207
|
-
const
|
|
3236
|
+
if (code.length > maxCode) throw new Error(`the code is ${code.length} characters; the limit is ${maxCode}. Do less in one run.`);
|
|
3237
|
+
const bridge = {
|
|
3238
|
+
names: ctx.agent.tools.filter((t) => t.name !== "run_js" && !t.endsRun && !t.vision && !t.display?.hidden && t.callableFromCode !== false).map((t) => t.name),
|
|
3239
|
+
max: opts.maxToolCalls,
|
|
3240
|
+
call: async (name, args, signal) => {
|
|
3241
|
+
const r2 = await ctx.callTool(name, args, { signal });
|
|
3242
|
+
if (r2.status !== "ok") throw new Error(r2.text.replace(/^Error:\s*/, ""));
|
|
3243
|
+
return r2.text;
|
|
3244
|
+
}
|
|
3245
|
+
};
|
|
3246
|
+
const r = await runInSandbox(code, input, { ...opts, timeoutMs: timeout_ms ?? opts.timeoutMs, signal: ctx.signal, bridge });
|
|
3208
3247
|
const parts = [];
|
|
3209
3248
|
if (r.logs) parts.push(`console:
|
|
3210
3249
|
${r.logs}`);
|
|
3211
3250
|
if (r.ok) parts.push(r.result === void 0 ? "Returned: undefined" : `Returned: ${r.result}`);
|
|
3212
|
-
else parts.push(`Error: ${r.error}`);
|
|
3251
|
+
else parts.push(/^\w*Error\b/.test(r.error ?? "") ? String(r.error) : `Error: ${r.error}`);
|
|
3213
3252
|
parts.push(`(${r.durationMs} ms)`);
|
|
3214
3253
|
return { content: parts.join("\n\n"), details: r };
|
|
3215
3254
|
}
|
|
@@ -3398,6 +3437,8 @@ function nullUI() {
|
|
|
3398
3437
|
function askUserTool() {
|
|
3399
3438
|
return defineTool({
|
|
3400
3439
|
name: "ask_user",
|
|
3440
|
+
// The model asks, between its steps; code in the middle of a run does not.
|
|
3441
|
+
callableFromCode: false,
|
|
3401
3442
|
description: "Ask the user one to three questions when the request is genuinely ambiguous and the answer changes what you would do. 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.",
|
|
3402
3443
|
parameters: {
|
|
3403
3444
|
type: "object",
|
|
@@ -3464,6 +3505,7 @@ var MEMORY_PATH = "/memory/notes.md";
|
|
|
3464
3505
|
var AGENTS_PATH = "/AGENTS.md";
|
|
3465
3506
|
var MAX_NOTES_CHARS = 6e3;
|
|
3466
3507
|
var MAX_RETRIES = 3;
|
|
3508
|
+
var NESTED_RESULT_CHARS = 2e6;
|
|
3467
3509
|
var LOOP_WARN = 3;
|
|
3468
3510
|
var LOOP_STOP = 6;
|
|
3469
3511
|
function toWire(m, older) {
|
|
@@ -3539,6 +3581,7 @@ function withoutMedia(messages, media, model) {
|
|
|
3539
3581
|
var emptyUsage = () => ({ total_cost: 0, prompt_tokens: 0, completion_tokens: 0, calls: 0 });
|
|
3540
3582
|
var abortedResult = () => ({ runId: "", reason: "aborted", text: "", usage: emptyUsage() });
|
|
3541
3583
|
var SKIPPED_STOP = "Skipped: the user stopped the run.";
|
|
3584
|
+
var FILE_TOOL_NAMES = /* @__PURE__ */ new Set(["read_file", "list_files", "search_files", "write_file", "edit_file", "move_file", "copy_file", "delete_file"]);
|
|
3542
3585
|
var balanceError = () => new ProviderError(402, "The reply was cut short because the balance could not cover a full answer; top up to continue", { code: "insufficient_balance" });
|
|
3543
3586
|
function raceAbort(p, signal) {
|
|
3544
3587
|
if (signal.aborted) {
|
|
@@ -3606,7 +3649,7 @@ var Agent = class {
|
|
|
3606
3649
|
tools.push(...fileTools(this.workspace, { guard }).filter((t) => !want || want.has(t.name)));
|
|
3607
3650
|
}
|
|
3608
3651
|
if (opts.askUser !== false) tools.push(askUserTool());
|
|
3609
|
-
if (opts.sandbox !== false) tools.push(sandboxTool(
|
|
3652
|
+
if (opts.sandbox !== false) tools.push(sandboxTool(typeof opts.sandbox === "object" ? opts.sandbox : {}));
|
|
3610
3653
|
const seen = /* @__PURE__ */ new Set();
|
|
3611
3654
|
for (const t of tools) {
|
|
3612
3655
|
if (seen.has(t.name)) throw new Error(`two tools are named "${t.name}"`);
|
|
@@ -4139,7 +4182,8 @@ var Agent = class {
|
|
|
4139
4182
|
appName: this.opts.appName,
|
|
4140
4183
|
instructions: typeof this.opts.instructions === "function" ? this.opts.instructions() : this.opts.instructions,
|
|
4141
4184
|
tools,
|
|
4142
|
-
|
|
4185
|
+
// Without file tools the directory is only where the session is kept.
|
|
4186
|
+
workspaceDescription: ws && tools.some((t) => FILE_TOOL_NAMES.has(t.name)) ? ws.describe() : void 0,
|
|
4143
4187
|
skills: ws ? await ws.skills() : [],
|
|
4144
4188
|
hasSandbox: tools.some((t) => t.name === "run_js"),
|
|
4145
4189
|
hasAskUser: tools.some((t) => t.name === "ask_user"),
|
|
@@ -4385,18 +4429,22 @@ var Agent = class {
|
|
|
4385
4429
|
const id = call.id ?? "", name = call.function.name;
|
|
4386
4430
|
this.emit("tool_start", { runId, id, name, args: call.function.arguments });
|
|
4387
4431
|
this.emit("tool_end", { runId, id, name, status: "skipped", result: why, durationMs: 0 });
|
|
4388
|
-
return { message: { role: "tool", tool_call_id: id, content: why }, key: "", changed: false, progress: true };
|
|
4432
|
+
return { message: { role: "tool", tool_call_id: id, content: why }, key: "", changed: false, progress: true, status: "skipped" };
|
|
4389
4433
|
}
|
|
4390
|
-
|
|
4434
|
+
/** `parentId`: a call made from inside that tool call (ctx.callTool); its result goes back to the tool, not into the conversation. */
|
|
4435
|
+
async runTool(call, runId, signal, truncated, parentId) {
|
|
4391
4436
|
const id = call.id ?? "";
|
|
4437
|
+
const nested = parentId ? { parentId } : {};
|
|
4392
4438
|
const name = call.function.name;
|
|
4393
4439
|
const started = Date.now();
|
|
4394
4440
|
let progress;
|
|
4395
4441
|
let tool;
|
|
4396
4442
|
const finish = (status, content, details) => {
|
|
4397
4443
|
const result = textOf(content);
|
|
4398
|
-
this.emit("tool_end", { runId, id, name, status, result, details, durationMs: Date.now() - started, ...typeof content === "string" ? {} : { content } });
|
|
4444
|
+
this.emit("tool_end", { runId, id, name, status, result: parentId ? truncate(result, DEFAULT_MAX_RESULT_CHARS).text : result, details, durationMs: Date.now() - started, ...nested, ...typeof content === "string" ? {} : { content } });
|
|
4399
4445
|
return {
|
|
4446
|
+
status,
|
|
4447
|
+
details,
|
|
4400
4448
|
message: { role: "tool", tool_call_id: id, content },
|
|
4401
4449
|
// A read is judged by what it returned (another range of the same lines is nothing new); a change by what it was asked to do too.
|
|
4402
4450
|
key: tool?.readOnly ? `${name}|${status}|${result.slice(0, 4e3)}` : `${name}|${call.function.arguments.slice(0, 4e3)}|${status}|${result.slice(0, 2e3)}`,
|
|
@@ -4407,7 +4455,7 @@ var Agent = class {
|
|
|
4407
4455
|
};
|
|
4408
4456
|
if (signal.aborted) return finish("skipped", SKIPPED_STOP);
|
|
4409
4457
|
if (truncated) {
|
|
4410
|
-
this.emit("tool_start", { runId, id, name, args: call.function.arguments });
|
|
4458
|
+
this.emit("tool_start", { runId, id, name, args: call.function.arguments, ...nested });
|
|
4411
4459
|
return finish("error", `Tool call "${name}" was not executed: the response hit the output token limit, so its arguments may be truncated. Re-issue the tool call with complete arguments.`);
|
|
4412
4460
|
}
|
|
4413
4461
|
const offered = await this.activeTools();
|
|
@@ -4416,10 +4464,10 @@ var Agent = class {
|
|
|
4416
4464
|
try {
|
|
4417
4465
|
args = call.function.arguments.trim() ? JSON.parse(call.function.arguments) : {};
|
|
4418
4466
|
} catch {
|
|
4419
|
-
this.emit("tool_start", { runId, id, name, args: call.function.arguments });
|
|
4467
|
+
this.emit("tool_start", { runId, id, name, args: call.function.arguments, ...nested });
|
|
4420
4468
|
return finish("error", "Error: the arguments are not valid JSON.");
|
|
4421
4469
|
}
|
|
4422
|
-
this.emit("tool_start", { runId, id, name, args });
|
|
4470
|
+
this.emit("tool_start", { runId, id, name, args, ...nested });
|
|
4423
4471
|
if (!tool) return finish("error", `Error: there is no tool named "${name}". Available tools: ${offered.map((t) => t.name).join(", ")}.`);
|
|
4424
4472
|
if (args === null || typeof args !== "object" || Array.isArray(args)) return finish("error", "Error: the arguments must be a JSON object.");
|
|
4425
4473
|
const problems = validateSchema(tool.parameters, args);
|
|
@@ -4450,13 +4498,14 @@ Fix the call and try again.`);
|
|
|
4450
4498
|
try {
|
|
4451
4499
|
const own = tool.whenStopped?.(args);
|
|
4452
4500
|
if (own !== void 0) {
|
|
4453
|
-
const norm = normalizeResult(own, tool.maxResultChars);
|
|
4501
|
+
const norm = normalizeResult(own, parentId ? NESTED_RESULT_CHARS : tool.maxResultChars);
|
|
4454
4502
|
return finish("skipped", norm.content, norm.details);
|
|
4455
4503
|
}
|
|
4456
4504
|
} catch {
|
|
4457
4505
|
}
|
|
4458
4506
|
return finish("skipped", SKIPPED_STOP);
|
|
4459
4507
|
};
|
|
4508
|
+
let inner = 0;
|
|
4460
4509
|
try {
|
|
4461
4510
|
const value = await raceAbort(Promise.resolve(tool.execute(args, {
|
|
4462
4511
|
signal,
|
|
@@ -4464,13 +4513,18 @@ Fix the call and try again.`);
|
|
|
4464
4513
|
workspace: this.workspace,
|
|
4465
4514
|
agent: this,
|
|
4466
4515
|
callId: id,
|
|
4467
|
-
|
|
4516
|
+
parentId,
|
|
4517
|
+
update: (content) => this.emit("tool_update", { runId, id, name, content, ...nested }),
|
|
4468
4518
|
progress: (made) => {
|
|
4469
4519
|
progress = made;
|
|
4520
|
+
},
|
|
4521
|
+
callTool: async (toolName, toolArgs, o) => {
|
|
4522
|
+
const out = await this.runTool({ id: `${id}.${++inner}`, type: "function", function: { name: toolName, arguments: JSON.stringify(toolArgs ?? {}) } }, runId, o?.signal ?? signal, false, id);
|
|
4523
|
+
return { status: out.status, text: textOf(out.message.content), details: out.details };
|
|
4470
4524
|
}
|
|
4471
4525
|
})), signal);
|
|
4472
4526
|
if (signal.aborted) return stoppedIn();
|
|
4473
|
-
const norm = normalizeResult(value, tool.maxResultChars);
|
|
4527
|
+
const norm = normalizeResult(value, parentId ? NESTED_RESULT_CHARS : tool.maxResultChars);
|
|
4474
4528
|
return finish("ok", norm.content, norm.details);
|
|
4475
4529
|
} catch (err) {
|
|
4476
4530
|
if (signal.aborted) return stoppedIn();
|
package/dist/index.d.ts
CHANGED
|
@@ -27,7 +27,7 @@ export { configurePdf, extractPdfText, formatPdfText, isPdf, type PdfLib } from
|
|
|
27
27
|
export { fileTools, type FileToolsOptions } from "./file-tools.js";
|
|
28
28
|
export { fileGuard, PartialReadError, type FileGuard } from "./file-guard.js";
|
|
29
29
|
export { connectMCP, MCPError, type MCPConnection, type MCPOptions, type MCPToolInfo } from "./mcp.js";
|
|
30
|
-
export { sandboxTool, runInSandbox, type SandboxOptions, type SandboxResult } from "./sandbox.js";
|
|
30
|
+
export { sandboxTool, runInSandbox, type SandboxOptions, type SandboxResult, type SandboxToolBridge } from "./sandbox.js";
|
|
31
31
|
export { parseSkill, parseFrontmatter } from "./skills.js";
|
|
32
32
|
export { collectCompletion, type CollectedCompletion } from "./completion.js";
|
|
33
33
|
export { buildSystemPrompt, estimateTokens, fitBudget, groupTurns } from "./context.js";
|
package/dist/sandbox.d.ts
CHANGED
|
@@ -1,21 +1,26 @@
|
|
|
1
1
|
import type { Tool } from "./types.js";
|
|
2
|
-
import { type Workspace } from "./workspace.js";
|
|
3
|
-
import type { FileGuard } from "./file-guard.js";
|
|
4
2
|
/**
|
|
5
3
|
* Isolation is best effort: the code runs in a Worker of the page's origin with network and storage
|
|
6
4
|
* globals removed. Code that can be trusted with nothing should run in a sandboxed iframe of its own.
|
|
7
5
|
*/
|
|
8
6
|
export interface SandboxOptions {
|
|
9
|
-
/** The agent's read-before-write guard: `fs.read` counts as reading, `fs.write` and `fs.remove` are checked like the file tools. */
|
|
10
|
-
guard?: FileGuard;
|
|
11
7
|
/** Kill the run after this long (default 10 s, max 60 s). */
|
|
12
8
|
timeoutMs?: number;
|
|
13
9
|
/** Leave fetch/WebSocket available inside the sandbox (default false). */
|
|
14
10
|
network?: boolean;
|
|
15
11
|
/** Longest console output kept (default 20 000 chars). */
|
|
16
12
|
maxLogChars?: number;
|
|
17
|
-
/**
|
|
18
|
-
|
|
13
|
+
/** Most tool calls one run may make (default 50). */
|
|
14
|
+
maxToolCalls?: number;
|
|
15
|
+
/** Longest code accepted (default 20 000 chars). */
|
|
16
|
+
maxCodeChars?: number;
|
|
17
|
+
}
|
|
18
|
+
/** What `runInSandbox` needs to give the code its `tools`. */
|
|
19
|
+
export interface SandboxToolBridge {
|
|
20
|
+
names: string[];
|
|
21
|
+
/** Resolves with the tool's text; rejects with what the model would be told when it did not succeed. */
|
|
22
|
+
call(name: string, args: unknown, signal: AbortSignal): Promise<string>;
|
|
23
|
+
max?: number;
|
|
19
24
|
}
|
|
20
25
|
export interface SandboxResult {
|
|
21
26
|
ok: boolean;
|
|
@@ -25,9 +30,10 @@ export interface SandboxResult {
|
|
|
25
30
|
error?: string;
|
|
26
31
|
durationMs: number;
|
|
27
32
|
}
|
|
28
|
-
/** Runs `code` once in a fresh sandbox
|
|
29
|
-
export declare function runInSandbox(
|
|
33
|
+
/** Runs `code` once in a fresh sandbox; `bridge` gives it its `tools`. */
|
|
34
|
+
export declare function runInSandbox(code: string, input: unknown, opts?: SandboxOptions & {
|
|
30
35
|
signal?: AbortSignal;
|
|
36
|
+
bridge?: SandboxToolBridge;
|
|
31
37
|
}): Promise<SandboxResult>;
|
|
32
38
|
/** The `run_js` tool. */
|
|
33
|
-
export declare function sandboxTool(
|
|
39
|
+
export declare function sandboxTool(opts?: SandboxOptions): Tool;
|