@runappsai/agent 0.1.6 → 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/index.cjs CHANGED
@@ -291,6 +291,7 @@ ${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"));
296
297
  const has = (name) => input.tools.some((t) => t.name === name);
@@ -316,7 +317,7 @@ Your notes from earlier conversations (${input.memoryPath ?? "/memory/notes.md"}
316
317
  if (visible.length && has("read_file")) {
317
318
  const esc = (t) => t.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
318
319
  out.push(
319
- "# 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 (fs.read 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>
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>
320
321
  <name>${esc(s.name)}</name>
321
322
  <description>${esc(s.description)}</description>
322
323
  <location>${esc(s.path)}</location>
@@ -2637,11 +2638,12 @@ function fileTools(ws, opts = {}) {
2637
2638
  properties: { path: { type: "string", description: "Folder to list. Default /" } },
2638
2639
  additionalProperties: false
2639
2640
  },
2640
- async execute({ path }) {
2641
+ async execute({ path }, ctx) {
2641
2642
  const files2 = await ws.list(path || "/");
2642
2643
  if (!files2.length) return `No files under ${normalizePath(path || "/")}.`;
2643
- const lines = files2.slice(0, MAX_LIST).map((f) => `${f.path} (${f.size} B)`);
2644
- if (files2.length > MAX_LIST) lines.push(`
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(`
2645
2647
  [${MAX_LIST} entries limit reached (${files2.length} in all). List a sub-folder.]`);
2646
2648
  return lines.join("\n");
2647
2649
  }
@@ -2700,13 +2702,14 @@ function fileTools(ws, opts = {}) {
2700
2702
  await files.saw(normalizePath(path), { start: total + 1, end: total, total });
2701
2703
  return `Offset ${start} is beyond end of file (${total} lines total)`;
2702
2704
  }
2703
- const want = limit !== void 0 ? Math.min(limit, MAX_READ_LINES) : MAX_READ_LINES;
2705
+ const whole = !!ctx?.parentId;
2706
+ const want = whole ? limit ?? Infinity : limit !== void 0 ? Math.min(limit, MAX_READ_LINES) : MAX_READ_LINES;
2704
2707
  const out = [];
2705
2708
  let bytes = 0;
2706
2709
  let end = start - 1;
2707
2710
  for (let i = start - 1; i < total && out.length < want; i++) {
2708
2711
  const b = new TextEncoder().encode(lines[i]).byteLength + 1;
2709
- if (bytes + b > MAX_READ_BYTES && out.length > 0) break;
2712
+ if (!whole && bytes + b > MAX_READ_BYTES && out.length > 0) break;
2710
2713
  out.push(lines[i]);
2711
2714
  bytes += b;
2712
2715
  end = i + 1;
@@ -3036,20 +3039,14 @@ if (isNode) {
3036
3039
  send = function (m) { self.postMessage(m); };
3037
3040
  }
3038
3041
  var pending = new Map(), seq = 0;
3039
- function rpc(op, args) {
3042
+ function callTool(name, args) {
3040
3043
  return new Promise(function (resolve, reject) {
3041
3044
  var id = ++seq;
3042
3045
  pending.set(id, { resolve: resolve, reject: reject });
3043
- send({ type: "fs", id: id, op: op, args: args });
3046
+ send({ type: "tool", id: id, name: name, args: args });
3044
3047
  });
3045
3048
  }
3046
- var fs = {
3047
- read: function (p) { return rpc("read", [p]); },
3048
- write: function (p, c) { return rpc("write", [p, c]); },
3049
- list: function (p) { return rpc("list", [p || "/"]); },
3050
- exists: function (p) { return rpc("exists", [p]); },
3051
- remove: function (p) { return rpc("delete", [p]); },
3052
- };
3049
+ var tools = {};
3053
3050
  var logs = [], logChars = 0, maxLog = 20000;
3054
3051
  function fmt(a) {
3055
3052
  if (typeof a === "string") return a;
@@ -3083,8 +3080,18 @@ async function run(msg) {
3083
3080
  var start = Date.now();
3084
3081
  try {
3085
3082
  var AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;
3086
- var fn = new AsyncFunction("fs", "input", "console", msg.code);
3087
- var value = await fn(fs, msg.input, sandboxConsole);
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);
3088
3095
  send({ type: "done", result: serialize(value), logs: logs.join("\\n"), durationMs: Date.now() - start });
3089
3096
  } catch (e) {
3090
3097
  send({ type: "error", error: (e && e.stack) || String(e), logs: logs.join("\\n"), durationMs: Date.now() - start });
@@ -3092,11 +3099,15 @@ async function run(msg) {
3092
3099
  }
3093
3100
  function onMessage(m) {
3094
3101
  if (m.type === "run") run(m);
3095
- else if (m.type === "fsResult") {
3102
+ else if (m.type === "toolResult") {
3096
3103
  var p = pending.get(m.id);
3097
3104
  if (!p) return;
3098
3105
  pending.delete(m.id);
3099
- if (m.ok) p.resolve(m.value); else p.reject(new Error(m.error));
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);
3100
3111
  }
3101
3112
  }
3102
3113
  if (isNode) port.on("message", onMessage); else self.onmessage = function (ev) { onMessage(ev.data); };
@@ -3111,6 +3122,12 @@ async function spawn() {
3111
3122
  onMessage: (fn) => {
3112
3123
  w2.onmessage = (ev) => fn(ev.data);
3113
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
+ },
3114
3131
  terminate: () => w2.terminate()
3115
3132
  };
3116
3133
  }
@@ -3120,85 +3137,90 @@ async function spawn() {
3120
3137
  return {
3121
3138
  post: (m) => w.postMessage(m),
3122
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
+ },
3123
3144
  terminate: () => w.terminate()
3124
3145
  };
3125
3146
  }
3126
- async function runInSandbox(ws, code, input, opts = {}) {
3147
+ async function runInSandbox(code, input, opts = {}) {
3127
3148
  const timeoutMs = Math.min(6e4, Math.max(100, opts.timeoutMs ?? 1e4));
3128
3149
  const worker = await spawn();
3129
3150
  const started = Date.now();
3151
+ const bridge = opts.bridge;
3130
3152
  return new Promise((resolve) => {
3131
3153
  let settled = false;
3154
+ const running = new AbortController();
3132
3155
  const finish = (r) => {
3133
3156
  if (settled) return;
3134
3157
  settled = true;
3135
3158
  clearTimeout(timer);
3136
3159
  opts.signal?.removeEventListener("abort", onAbort);
3137
3160
  worker.terminate();
3161
+ running.abort();
3138
3162
  resolve(r);
3139
3163
  };
3140
- const timer = setTimeout(() => finish({ ok: false, logs: "", error: `Timed out after ${timeoutMs} ms`, durationMs: Date.now() - started }), timeoutMs);
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();
3141
3182
  const onAbort = () => finish({ ok: false, logs: "", error: "Aborted", durationMs: Date.now() - started });
3142
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
+ };
3143
3200
  worker.onMessage(async (m) => {
3144
3201
  if (m.type === "done") {
3145
3202
  finish({ ok: true, result: m.result, logs: m.logs ?? "", durationMs: m.durationMs ?? Date.now() - started });
3146
3203
  } else if (m.type === "error") {
3147
3204
  finish({ ok: false, error: String(m.error), logs: m.logs ?? "", durationMs: m.durationMs ?? Date.now() - started });
3148
- } else if (m.type === "fs") {
3149
- const id = m.id;
3150
- const args = m.args ?? [];
3151
- try {
3152
- if (!ws) throw new Error("no workspace");
3153
- let value;
3154
- switch (m.op) {
3155
- case "read": {
3156
- const p = normalizePath(String(args[0]));
3157
- const doc = await ws.readAsText(p);
3158
- if (!doc) throw new Error(`${p} is a binary file`);
3159
- await opts.guard?.saw(p, { text: doc.kind === "text" ? doc.text : void 0 });
3160
- value = doc.text;
3161
- break;
3162
- }
3163
- case "write": {
3164
- const p = normalizePath(String(args[0]));
3165
- await opts.guard?.check(p, "overwrite");
3166
- await ws.write(p, String(args[1] ?? ""));
3167
- await opts.guard?.wrote(p);
3168
- value = true;
3169
- break;
3170
- }
3171
- case "list":
3172
- value = (await ws.list(String(args[0] ?? "/"))).map((f) => ({ path: f.path, size: f.size }));
3173
- break;
3174
- case "exists":
3175
- value = await ws.exists(String(args[0]));
3176
- break;
3177
- case "delete": {
3178
- const path = normalizePath(String(args[0]));
3179
- await opts.guard?.check(path, "delete");
3180
- if (opts.confirmDelete && !await opts.confirmDelete(path)) throw new Error(`the user declined deleting ${path}`);
3181
- await ws.delete(path);
3182
- opts.guard?.forget(path);
3183
- value = true;
3184
- break;
3185
- }
3186
- default:
3187
- 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 });
3188
3211
  }
3189
- worker.post({ type: "fsResult", id, ok: true, value });
3190
- } catch (e) {
3191
- worker.post({ type: "fsResult", id, ok: false, error: e.message });
3192
- }
3212
+ });
3193
3213
  }
3194
3214
  });
3195
- 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 });
3196
3216
  });
3197
3217
  }
3198
- function sandboxTool(ws, opts = {}) {
3218
+ function sandboxTool(opts = {}) {
3219
+ const maxCode = opts.maxCodeChars ?? 2e4;
3199
3220
  return defineTool({
3200
3221
  name: "run_js",
3201
- 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 `fs` for the workspace \u2014 `await fs.read(path)` \u2192 text, `await fs.write(path, text)`, `await fs.list(folder)` \u2192 [{path, size}], `await fs.exists(path)`.",
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.",
3202
3224
  parameters: {
3203
3225
  type: "object",
3204
3226
  properties: {
@@ -3211,13 +3233,22 @@ function sandboxTool(ws, opts = {}) {
3211
3233
  },
3212
3234
  maxResultChars: 24e3,
3213
3235
  async execute({ code, input, timeout_ms }, ctx) {
3214
- const confirmDelete = opts.confirmDelete ?? ((path) => ctx.agent?.settings.permissions === "auto" ? true : ctx.ui.confirm(`Allow run_js to delete ${path}?`, void 0, { danger: true, signal: ctx.signal }));
3215
- const r = await runInSandbox(ws, code, input, { ...opts, confirmDelete, timeoutMs: timeout_ms ?? opts.timeoutMs, signal: ctx.signal });
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 });
3216
3247
  const parts = [];
3217
3248
  if (r.logs) parts.push(`console:
3218
3249
  ${r.logs}`);
3219
3250
  if (r.ok) parts.push(r.result === void 0 ? "Returned: undefined" : `Returned: ${r.result}`);
3220
- else parts.push(`Error: ${r.error}`);
3251
+ else parts.push(/^\w*Error\b/.test(r.error ?? "") ? String(r.error) : `Error: ${r.error}`);
3221
3252
  parts.push(`(${r.durationMs} ms)`);
3222
3253
  return { content: parts.join("\n\n"), details: r };
3223
3254
  }
@@ -3406,6 +3437,8 @@ function nullUI() {
3406
3437
  function askUserTool() {
3407
3438
  return defineTool({
3408
3439
  name: "ask_user",
3440
+ // The model asks, between its steps; code in the middle of a run does not.
3441
+ callableFromCode: false,
3409
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.",
3410
3443
  parameters: {
3411
3444
  type: "object",
@@ -3472,6 +3505,7 @@ var MEMORY_PATH = "/memory/notes.md";
3472
3505
  var AGENTS_PATH = "/AGENTS.md";
3473
3506
  var MAX_NOTES_CHARS = 6e3;
3474
3507
  var MAX_RETRIES = 3;
3508
+ var NESTED_RESULT_CHARS = 2e6;
3475
3509
  var LOOP_WARN = 3;
3476
3510
  var LOOP_STOP = 6;
3477
3511
  function toWire(m, older) {
@@ -3615,7 +3649,7 @@ var Agent = class {
3615
3649
  tools.push(...fileTools(this.workspace, { guard }).filter((t) => !want || want.has(t.name)));
3616
3650
  }
3617
3651
  if (opts.askUser !== false) tools.push(askUserTool());
3618
- if (opts.sandbox !== false) tools.push(sandboxTool(this.workspace, { ...typeof opts.sandbox === "object" ? opts.sandbox : {}, guard }));
3652
+ if (opts.sandbox !== false) tools.push(sandboxTool(typeof opts.sandbox === "object" ? opts.sandbox : {}));
3619
3653
  const seen = /* @__PURE__ */ new Set();
3620
3654
  for (const t of tools) {
3621
3655
  if (seen.has(t.name)) throw new Error(`two tools are named "${t.name}"`);
@@ -4148,8 +4182,8 @@ var Agent = class {
4148
4182
  appName: this.opts.appName,
4149
4183
  instructions: typeof this.opts.instructions === "function" ? this.opts.instructions() : this.opts.instructions,
4150
4184
  tools,
4151
- // run_js reaches the files too; with neither, the directory is only where the session is kept.
4152
- workspaceDescription: ws && tools.some((t) => FILE_TOOL_NAMES.has(t.name) || t.name === "run_js") ? ws.describe() : void 0,
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,
4153
4187
  skills: ws ? await ws.skills() : [],
4154
4188
  hasSandbox: tools.some((t) => t.name === "run_js"),
4155
4189
  hasAskUser: tools.some((t) => t.name === "ask_user"),
@@ -4395,18 +4429,22 @@ var Agent = class {
4395
4429
  const id = call.id ?? "", name = call.function.name;
4396
4430
  this.emit("tool_start", { runId, id, name, args: call.function.arguments });
4397
4431
  this.emit("tool_end", { runId, id, name, status: "skipped", result: why, durationMs: 0 });
4398
- 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" };
4399
4433
  }
4400
- async runTool(call, runId, signal, truncated) {
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) {
4401
4436
  const id = call.id ?? "";
4437
+ const nested = parentId ? { parentId } : {};
4402
4438
  const name = call.function.name;
4403
4439
  const started = Date.now();
4404
4440
  let progress;
4405
4441
  let tool;
4406
4442
  const finish = (status, content, details) => {
4407
4443
  const result = textOf(content);
4408
- 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 } });
4409
4445
  return {
4446
+ status,
4447
+ details,
4410
4448
  message: { role: "tool", tool_call_id: id, content },
4411
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.
4412
4450
  key: tool?.readOnly ? `${name}|${status}|${result.slice(0, 4e3)}` : `${name}|${call.function.arguments.slice(0, 4e3)}|${status}|${result.slice(0, 2e3)}`,
@@ -4417,7 +4455,7 @@ var Agent = class {
4417
4455
  };
4418
4456
  if (signal.aborted) return finish("skipped", SKIPPED_STOP);
4419
4457
  if (truncated) {
4420
- this.emit("tool_start", { runId, id, name, args: call.function.arguments });
4458
+ this.emit("tool_start", { runId, id, name, args: call.function.arguments, ...nested });
4421
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.`);
4422
4460
  }
4423
4461
  const offered = await this.activeTools();
@@ -4426,10 +4464,10 @@ var Agent = class {
4426
4464
  try {
4427
4465
  args = call.function.arguments.trim() ? JSON.parse(call.function.arguments) : {};
4428
4466
  } catch {
4429
- this.emit("tool_start", { runId, id, name, args: call.function.arguments });
4467
+ this.emit("tool_start", { runId, id, name, args: call.function.arguments, ...nested });
4430
4468
  return finish("error", "Error: the arguments are not valid JSON.");
4431
4469
  }
4432
- this.emit("tool_start", { runId, id, name, args });
4470
+ this.emit("tool_start", { runId, id, name, args, ...nested });
4433
4471
  if (!tool) return finish("error", `Error: there is no tool named "${name}". Available tools: ${offered.map((t) => t.name).join(", ")}.`);
4434
4472
  if (args === null || typeof args !== "object" || Array.isArray(args)) return finish("error", "Error: the arguments must be a JSON object.");
4435
4473
  const problems = validateSchema(tool.parameters, args);
@@ -4460,13 +4498,14 @@ Fix the call and try again.`);
4460
4498
  try {
4461
4499
  const own = tool.whenStopped?.(args);
4462
4500
  if (own !== void 0) {
4463
- const norm = normalizeResult(own, tool.maxResultChars);
4501
+ const norm = normalizeResult(own, parentId ? NESTED_RESULT_CHARS : tool.maxResultChars);
4464
4502
  return finish("skipped", norm.content, norm.details);
4465
4503
  }
4466
4504
  } catch {
4467
4505
  }
4468
4506
  return finish("skipped", SKIPPED_STOP);
4469
4507
  };
4508
+ let inner = 0;
4470
4509
  try {
4471
4510
  const value = await raceAbort(Promise.resolve(tool.execute(args, {
4472
4511
  signal,
@@ -4474,13 +4513,18 @@ Fix the call and try again.`);
4474
4513
  workspace: this.workspace,
4475
4514
  agent: this,
4476
4515
  callId: id,
4477
- update: (content) => this.emit("tool_update", { runId, id, name, content }),
4516
+ parentId,
4517
+ update: (content) => this.emit("tool_update", { runId, id, name, content, ...nested }),
4478
4518
  progress: (made) => {
4479
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 };
4480
4524
  }
4481
4525
  })), signal);
4482
4526
  if (signal.aborted) return stoppedIn();
4483
- const norm = normalizeResult(value, tool.maxResultChars);
4527
+ const norm = normalizeResult(value, parentId ? NESTED_RESULT_CHARS : tool.maxResultChars);
4484
4528
  return finish("ok", norm.content, norm.details);
4485
4529
  } catch (err) {
4486
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
- /** Asked before `fs.remove(path)` deletes a file (the tool asks like delete_file does); false refuses. */
18
- confirmDelete?: (path: string) => boolean | Promise<boolean>;
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 bound to `ws` (null: no fs). */
29
- export declare function runInSandbox(ws: Workspace | null, code: string, input: unknown, opts?: SandboxOptions & {
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(ws: Workspace | null, opts?: SandboxOptions): Tool;
39
+ export declare function sandboxTool(opts?: SandboxOptions): Tool;