@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/sandbox.js CHANGED
@@ -1,10 +1,10 @@
1
1
  // A JavaScript sandbox for the model: its code runs in a Worker (browser)
2
2
  // or a worker thread (Node) with no DOM and, by default, no network, a
3
- // captured console, and an `fs` bridged to the workspace. The `run_js`
4
- // tool wraps it so the model can compute, transform data and run a
5
- // skill's scripts instead of guessing.
3
+ // captured console, and a `tools` object that calls the agent's own tools
4
+ // (the files too, through the file tools). The `run_js` tool wraps it so
5
+ // the model can compute, transform data and run a skill's scripts instead
6
+ // of guessing.
6
7
  import { defineTool } from "./tool.js";
7
- import { normalizePath } from "./workspace.js";
8
8
  // The worker program. Plain JS, no imports, so it can run as a blob URL
9
9
  // Worker and as a worker_threads eval script alike.
10
10
  const WORKER_SOURCE = `
@@ -19,20 +19,14 @@ if (isNode) {
19
19
  send = function (m) { self.postMessage(m); };
20
20
  }
21
21
  var pending = new Map(), seq = 0;
22
- function rpc(op, args) {
22
+ function callTool(name, args) {
23
23
  return new Promise(function (resolve, reject) {
24
24
  var id = ++seq;
25
25
  pending.set(id, { resolve: resolve, reject: reject });
26
- send({ type: "fs", id: id, op: op, args: args });
26
+ send({ type: "tool", id: id, name: name, args: args });
27
27
  });
28
28
  }
29
- var fs = {
30
- read: function (p) { return rpc("read", [p]); },
31
- write: function (p, c) { return rpc("write", [p, c]); },
32
- list: function (p) { return rpc("list", [p || "/"]); },
33
- exists: function (p) { return rpc("exists", [p]); },
34
- remove: function (p) { return rpc("delete", [p]); },
35
- };
29
+ var tools = {};
36
30
  var logs = [], logChars = 0, maxLog = 20000;
37
31
  function fmt(a) {
38
32
  if (typeof a === "string") return a;
@@ -66,8 +60,18 @@ async function run(msg) {
66
60
  var start = Date.now();
67
61
  try {
68
62
  var AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;
69
- var fn = new AsyncFunction("fs", "input", "console", msg.code);
70
- var value = await fn(fs, msg.input, sandboxConsole);
63
+ (msg.tools || []).forEach(function (name) {
64
+ tools[name] = function (args) { return callTool(name, args === undefined ? {} : args); };
65
+ });
66
+ var fn = new AsyncFunction("input", "console", "tools", msg.code);
67
+ // A tool the code may not call says so, rather than "tools.x is not a function".
68
+ var offered = new Proxy(Object.freeze(tools), {
69
+ get: function (t, k) {
70
+ if (k in t || typeof k !== "string" || k === "then" || k === "toJSON") return t[k];
71
+ return function () { return Promise.reject(new Error("tools." + k + " cannot be called from run_js; call it directly if you have it")); };
72
+ },
73
+ });
74
+ var value = await fn(msg.input, sandboxConsole, offered);
71
75
  send({ type: "done", result: serialize(value), logs: logs.join("\\n"), durationMs: Date.now() - start });
72
76
  } catch (e) {
73
77
  send({ type: "error", error: (e && e.stack) || String(e), logs: logs.join("\\n"), durationMs: Date.now() - start });
@@ -75,11 +79,15 @@ async function run(msg) {
75
79
  }
76
80
  function onMessage(m) {
77
81
  if (m.type === "run") run(m);
78
- else if (m.type === "fsResult") {
82
+ else if (m.type === "toolResult") {
79
83
  var p = pending.get(m.id);
80
84
  if (!p) return;
81
85
  pending.delete(m.id);
82
- if (m.ok) p.resolve(m.value); else p.reject(new Error(m.error));
86
+ if (m.ok) { p.resolve(m.value); return; }
87
+ // The host's words, without this program's frames in them.
88
+ var err = new Error(m.error);
89
+ err.stack = m.error;
90
+ p.reject(err);
83
91
  }
84
92
  }
85
93
  if (isNode) port.on("message", onMessage); else self.onmessage = function (ev) { onMessage(ev.data); };
@@ -92,6 +100,7 @@ async function spawn() {
92
100
  return {
93
101
  post: (m) => w.postMessage(m),
94
102
  onMessage: (fn) => { w.onmessage = (ev) => fn(ev.data); },
103
+ onFail: (fn) => { w.onerror = (ev) => { ev.preventDefault(); fn(ev.message || "The sandbox worker could not run; the page's Content-Security-Policy may block it."); }; },
95
104
  terminate: () => w.terminate(),
96
105
  };
97
106
  }
@@ -102,16 +111,23 @@ async function spawn() {
102
111
  return {
103
112
  post: (m) => w.postMessage(m),
104
113
  onMessage: (fn) => w.on("message", (m) => fn(m)),
114
+ onFail: (fn) => {
115
+ w.on("error", (e) => fn(e instanceof Error ? e.message : String(e)));
116
+ w.on("exit", () => fn("The sandbox worker exited before the code finished."));
117
+ },
105
118
  terminate: () => w.terminate(),
106
119
  };
107
120
  }
108
- /** Runs `code` once in a fresh sandbox bound to `ws` (null: no fs). */
109
- export async function runInSandbox(ws, code, input, opts = {}) {
121
+ /** Runs `code` once in a fresh sandbox; `bridge` gives it its `tools`. */
122
+ export async function runInSandbox(code, input, opts = {}) {
110
123
  const timeoutMs = Math.min(60_000, Math.max(100, opts.timeoutMs ?? 10_000));
111
124
  const worker = await spawn();
112
125
  const started = Date.now();
126
+ const bridge = opts.bridge;
113
127
  return new Promise((resolve) => {
114
128
  let settled = false;
129
+ // Whatever the code left running ends with it: a call still queued never starts, one in progress is stopped.
130
+ const running = new AbortController();
115
131
  const finish = (r) => {
116
132
  if (settled)
117
133
  return;
@@ -119,11 +135,53 @@ export async function runInSandbox(ws, code, input, opts = {}) {
119
135
  clearTimeout(timer);
120
136
  opts.signal?.removeEventListener("abort", onAbort);
121
137
  worker.terminate();
138
+ running.abort();
122
139
  resolve(r);
123
140
  };
124
- const timer = setTimeout(() => finish({ ok: false, logs: "", error: `Timed out after ${timeoutMs} ms`, durationMs: Date.now() - started }), timeoutMs);
141
+ // The limit is on the code's own time: waiting for a tool (a backtest, the user's answer) does not count.
142
+ let left = timeoutMs, resumed = 0, waiting = 0;
143
+ let timer;
144
+ const startClock = () => {
145
+ resumed = Date.now();
146
+ timer = setTimeout(() => finish({ ok: false, logs: "", error: `Timed out after ${timeoutMs} ms`, durationMs: Date.now() - started }), Math.max(0, left));
147
+ };
148
+ const whileWaiting = async (work) => {
149
+ if (waiting++ === 0) {
150
+ clearTimeout(timer);
151
+ left -= Date.now() - resumed;
152
+ }
153
+ try {
154
+ return await work();
155
+ }
156
+ finally {
157
+ if (--waiting === 0 && !settled)
158
+ startClock();
159
+ }
160
+ };
161
+ startClock();
125
162
  const onAbort = () => finish({ ok: false, logs: "", error: "Aborted", durationMs: Date.now() - started });
126
163
  opts.signal?.addEventListener("abort", onAbort, { once: true });
164
+ // Stopped while the worker was starting: an abort event is not sent twice.
165
+ if (opts.signal?.aborted)
166
+ return onAbort();
167
+ worker.onFail((why) => finish({ ok: false, logs: "", error: why, durationMs: Date.now() - started }));
168
+ // One tool at a time, as the agent runs the model's calls (a page has one backtest, one question at a time).
169
+ let toolCalls = 0;
170
+ let queue = Promise.resolve();
171
+ const callTool = (name, args) => {
172
+ if (!bridge?.names.includes(name))
173
+ throw new Error(`there is no tool named "${name}"`);
174
+ const max = bridge.max ?? 50;
175
+ if (++toolCalls > max)
176
+ throw new Error(`this run has used its ${max} tool calls; return what you have and continue in another run_js`);
177
+ const turn = queue.then(() => {
178
+ if (settled)
179
+ throw new Error("the code has finished");
180
+ return bridge.call(name, args, running.signal);
181
+ });
182
+ queue = turn.catch(() => { });
183
+ return turn;
184
+ };
127
185
  worker.onMessage(async (m) => {
128
186
  if (m.type === "done") {
129
187
  finish({ ok: true, result: m.result, logs: m.logs ?? "", durationMs: m.durationMs ?? Date.now() - started });
@@ -131,65 +189,27 @@ export async function runInSandbox(ws, code, input, opts = {}) {
131
189
  else if (m.type === "error") {
132
190
  finish({ ok: false, error: String(m.error), logs: m.logs ?? "", durationMs: m.durationMs ?? Date.now() - started });
133
191
  }
134
- else if (m.type === "fs") {
135
- const id = m.id;
136
- const args = m.args ?? [];
137
- try {
138
- if (!ws)
139
- throw new Error("no workspace");
140
- let value;
141
- switch (m.op) {
142
- case "read": {
143
- // Text files as they are; a PDF as the text of its pages.
144
- const p = normalizePath(String(args[0]));
145
- const doc = await ws.readAsText(p);
146
- if (!doc)
147
- throw new Error(`${p} is a binary file`);
148
- await opts.guard?.saw(p, { text: doc.kind === "text" ? doc.text : undefined });
149
- value = doc.text;
150
- break;
151
- }
152
- case "write": {
153
- const p = normalizePath(String(args[0]));
154
- await opts.guard?.check(p, "overwrite");
155
- await ws.write(p, String(args[1] ?? ""));
156
- await opts.guard?.wrote(p);
157
- value = true;
158
- break;
159
- }
160
- case "list":
161
- value = (await ws.list(String(args[0] ?? "/"))).map((f) => ({ path: f.path, size: f.size }));
162
- break;
163
- case "exists":
164
- value = await ws.exists(String(args[0]));
165
- break;
166
- case "delete": {
167
- const path = normalizePath(String(args[0]));
168
- await opts.guard?.check(path, "delete");
169
- if (opts.confirmDelete && !(await opts.confirmDelete(path)))
170
- throw new Error(`the user declined deleting ${path}`);
171
- await ws.delete(path);
172
- opts.guard?.forget(path);
173
- value = true;
174
- break;
175
- }
176
- default: throw new Error(`unknown fs op ${String(m.op)}`);
192
+ else if (m.type === "tool") {
193
+ void whileWaiting(async () => {
194
+ try {
195
+ worker.post({ type: "toolResult", id: m.id, ok: true, value: await callTool(String(m.name), m.args) });
196
+ }
197
+ catch (e) {
198
+ worker.post({ type: "toolResult", id: m.id, ok: false, error: e.message });
177
199
  }
178
- worker.post({ type: "fsResult", id, ok: true, value });
179
- }
180
- catch (e) {
181
- worker.post({ type: "fsResult", id, ok: false, error: e.message });
182
- }
200
+ });
183
201
  }
184
202
  });
185
- worker.post({ type: "run", code, input, network: !!opts.network, maxLogChars: opts.maxLogChars });
203
+ worker.post({ type: "run", code, input, network: !!opts.network, maxLogChars: opts.maxLogChars, tools: bridge?.names });
186
204
  });
187
205
  }
188
206
  /** The `run_js` tool. */
189
- export function sandboxTool(ws, opts = {}) {
207
+ export function sandboxTool(opts = {}) {
208
+ const maxCode = opts.maxCodeChars ?? 20_000;
190
209
  return defineTool({
191
210
  name: "run_js",
192
- 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 — `await fs.read(path)` → text, `await fs.write(path, text)`, `await fs.list(folder)` → [{path, size}], `await fs.exists(path)`.",
211
+ 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\` — \`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.`,
212
+ 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.",
193
213
  parameters: {
194
214
  type: "object",
195
215
  properties: {
@@ -202,16 +222,26 @@ export function sandboxTool(ws, opts = {}) {
202
222
  },
203
223
  maxResultChars: 24_000,
204
224
  async execute({ code, input, timeout_ms }, ctx) {
205
- // fs.remove asks first, as delete_file does, unless the agent allows everything.
206
- const confirmDelete = opts.confirmDelete ?? ((path) => ctx.agent?.settings.permissions === "auto" ? true : ctx.ui.confirm(`Allow run_js to delete ${path}?`, undefined, { danger: true, signal: ctx.signal }));
207
- const r = await runInSandbox(ws, code, input, { ...opts, confirmDelete, timeoutMs: timeout_ms ?? opts.timeoutMs, signal: ctx.signal });
225
+ if (code.length > maxCode)
226
+ throw new Error(`the code is ${code.length} characters; the limit is ${maxCode}. Do less in one run.`);
227
+ const bridge = {
228
+ names: ctx.agent.tools.filter((t) => t.name !== "run_js" && !t.endsRun && !t.vision && !t.display?.hidden && t.callableFromCode !== false).map((t) => t.name),
229
+ max: opts.maxToolCalls,
230
+ call: async (name, args, signal) => {
231
+ const r = await ctx.callTool(name, args, { signal });
232
+ if (r.status !== "ok")
233
+ throw new Error(r.text.replace(/^Error:\s*/, ""));
234
+ return r.text;
235
+ },
236
+ };
237
+ const r = await runInSandbox(code, input, { ...opts, timeoutMs: timeout_ms ?? opts.timeoutMs, signal: ctx.signal, bridge });
208
238
  const parts = [];
209
239
  if (r.logs)
210
240
  parts.push(`console:\n${r.logs}`);
211
241
  if (r.ok)
212
242
  parts.push(r.result === undefined ? "Returned: undefined" : `Returned: ${r.result}`);
213
243
  else
214
- parts.push(`Error: ${r.error}`);
244
+ parts.push(/^\w*Error\b/.test(r.error ?? "") ? String(r.error) : `Error: ${r.error}`);
215
245
  parts.push(`(${r.durationMs} ms)`);
216
246
  return { content: parts.join("\n\n"), details: r };
217
247
  },
package/dist/types.d.ts CHANGED
@@ -18,6 +18,8 @@ export interface ToolContext {
18
18
  agent: Agent;
19
19
  /** The model's id for this call (`tool_call_id`). */
20
20
  callId: string;
21
+ /** Set when another tool made this call (`ctx.callTool`, `tools.x()` in run_js): the result is for code, not for the model to read, so a tool need not page it. */
22
+ parentId?: string;
21
23
  /** Report progress; the app sees it as a `tool_update` event. */
22
24
  update(content: string): void;
23
25
  /**
@@ -26,6 +28,24 @@ export interface ToolContext {
26
28
  * already had the same one). `read_file` says false for lines already read.
27
29
  */
28
30
  progress(made: boolean): void;
31
+ /**
32
+ * Calls another of the agent's tools from inside this one, through the same
33
+ * gate as the model's calls: schema, the tool's `validate`, `onToolCall`,
34
+ * permissions and its `confirm`, the stop button. The app sees `tool_start`
35
+ * and `tool_end` with `parentId` set to this call. The result is not cut to
36
+ * the tool's `maxResultChars` (2 000 000 chars at most) and is not added to
37
+ * the conversation.
38
+ */
39
+ callTool(name: string, args: unknown, opts?: {
40
+ signal?: AbortSignal;
41
+ }): Promise<ToolCallResult>;
42
+ }
43
+ /** How a call made with `ctx.callTool` ended. */
44
+ export interface ToolCallResult {
45
+ status: ToolStatus;
46
+ /** The result, or what the model would be told about a call that did not succeed. */
47
+ text: string;
48
+ details?: unknown;
29
49
  }
30
50
  /**
31
51
  * What `execute` may return. A string goes to the model as is; content
@@ -94,6 +114,8 @@ export interface ToolDefinition<A = Record<string, unknown>> {
94
114
  endsRun?: boolean;
95
115
  /** Longest result sent to the model, in characters (default 32 000). */
96
116
  maxResultChars?: number;
117
+ /** `false`: the model may call it, code in `run_js` may not (`tools.x()` says so). Default: both. */
118
+ callableFromCode?: boolean;
97
119
  /**
98
120
  * Only useful to a model that sees pictures (a screenshot tool, say): it
99
121
  * is offered only while the model in use is known to take images
@@ -151,6 +173,8 @@ export interface ToolDisplay<A = any> {
151
173
  result?: string;
152
174
  details?: unknown;
153
175
  }) => HTMLElement | null | undefined;
176
+ /** The workspace file this call is about: its card then offers to open and download it. Default: the built-in `read_file`, `write_file` and `edit_file` only, so a `path` argument of your own is not taken for a file. */
177
+ file?: (args: A) => string | null | undefined;
154
178
  /** A short outcome beside the status mark when the call ends ("$0.12", "3 nodes"). */
155
179
  outcome?: (call: {
156
180
  args: A;
@@ -325,21 +349,25 @@ export interface AgentEventMap {
325
349
  delta: string;
326
350
  arguments: string;
327
351
  };
352
+ /** `parentId`: the call this one was made from (`ctx.callTool`, `tools.x()` in run_js); not in the conversation. */
328
353
  tool_start: {
329
354
  runId: string;
330
355
  id: string;
356
+ parentId?: string;
331
357
  name: string;
332
358
  args: unknown;
333
359
  };
334
360
  tool_update: {
335
361
  runId: string;
336
362
  id: string;
363
+ parentId?: string;
337
364
  name: string;
338
365
  content: string;
339
366
  };
340
367
  tool_end: {
341
368
  runId: string;
342
369
  id: string;
370
+ parentId?: string;
343
371
  name: string;
344
372
  status: ToolStatus;
345
373
  /** What the model was told (as text: pictures are named). */
@@ -546,12 +574,15 @@ export interface AgentOptions {
546
574
  /**
547
575
  * The `run_js` sandbox tool (default on): the model computes and runs
548
576
  * scripts in a Worker with no DOM and no network. `false` removes it;
549
- * an object configures it (timeout, network).
577
+ * an object configures it (timeout, network, limits). The code calls the
578
+ * agent's other tools as `tools.read_file({ path })`.
550
579
  */
551
580
  sandbox?: boolean | {
552
581
  timeoutMs?: number;
553
582
  network?: boolean;
554
583
  maxLogChars?: number;
584
+ maxToolCalls?: number;
585
+ maxCodeChars?: number;
555
586
  };
556
587
  /** The `ask_user` tool (default on). */
557
588
  askUser?: boolean;
package/dist/ui.cjs CHANGED
@@ -2077,6 +2077,7 @@ var STRINGS = {
2077
2077
  actRun: "ran {n} snippet(s)",
2078
2078
  actAsk: "asked you {n} time(s)",
2079
2079
  actOther: "used {name}",
2080
+ runCode: "Run code",
2080
2081
  ingRead: "Reading",
2081
2082
  ingList: "Listing",
2082
2083
  ingSearch: "Searching",
@@ -2326,6 +2327,7 @@ var STRINGS = {
2326
2327
  actRun: "\u8FD0\u884C\u4E86 {n} \u6BB5\u4EE3\u7801",
2327
2328
  actAsk: "\u8BE2\u95EE\u4E86\u4F60 {n} \u6B21",
2328
2329
  actOther: "\u8C03\u7528\u4E86 {name}",
2330
+ runCode: "\u8FD0\u884C\u4EE3\u7801",
2329
2331
  ingRead: "\u6B63\u5728\u8BFB\u53D6",
2330
2332
  ingList: "\u6B63\u5728\u67E5\u770B",
2331
2333
  ingSearch: "\u6B63\u5728\u641C\u7D22",
@@ -2736,6 +2738,7 @@ var CSS = tokenCSS() + `
2736
2738
  .ra-tg .ra-tgb{display:flex;flex-direction:column;gap:8px;margin-top:6px}
2737
2739
  .ra-tool{border:1px solid var(--ra-border);border-radius:6px;overflow:hidden;font-size:14px}
2738
2740
  .ra-tool.fail{border-color:var(--ra-red)}
2741
+ .ra-tnest{display:flex;flex-direction:column;gap:4px;margin:6px 0}
2739
2742
  .ra-tool>summary{display:flex;align-items:center;gap:8px;padding:7px 10px;cursor:pointer;list-style:none;user-select:none}
2740
2743
  .ra-tool>summary::-webkit-details-marker{display:none}
2741
2744
  .ra-tool>summary:hover{background:var(--ra-muted)}
@@ -3291,6 +3294,14 @@ function inlineUI(askArea, toasts, t, onChange) {
3291
3294
  }
3292
3295
  };
3293
3296
  }
3297
+ var FILE_CARD_TOOLS = /* @__PURE__ */ new Set(["read_file", "write_file", "edit_file"]);
3298
+ var isFile = async (ws, path) => {
3299
+ try {
3300
+ return await ws.exists(path) && !await ws.isFolder(path);
3301
+ } catch {
3302
+ return false;
3303
+ }
3304
+ };
3294
3305
  var LAST_KEY = (project) => `__runapps_agent_chat:${project}:last`;
3295
3306
  function readLast(project) {
3296
3307
  try {
@@ -4180,12 +4191,12 @@ function renderChat(target, opts) {
4180
4191
  if (code.closest("pre") || code.classList.contains("ra-path")) continue;
4181
4192
  const text = code.textContent?.trim() ?? "";
4182
4193
  if (!/^\/[^\s`'"<>]+$/.test(text) || text.length > 200) continue;
4183
- void ws.exists(text).then((ok) => {
4194
+ void isFile(ws, text).then((ok) => {
4184
4195
  if (ok && !code.classList.contains("ra-path")) {
4185
4196
  code.classList.add("ra-path");
4186
4197
  code.dataset.path = text;
4187
4198
  code.title = t.open;
4188
- code.insertAdjacentHTML("beforeend", I.download(11));
4199
+ code.insertAdjacentHTML("beforeend", I.file(11));
4189
4200
  }
4190
4201
  });
4191
4202
  }
@@ -4255,8 +4266,9 @@ function renderChat(target, opts) {
4255
4266
  const end = h("span", "ra-tend");
4256
4267
  end.innerHTML = '<span class="ra-spin"></span>';
4257
4268
  sum.innerHTML = `<span class="ra-chev">${I.chev()}</span>`;
4258
- const title2 = h("span", "ra-tname", label ?? name);
4259
- if (label) {
4269
+ const shown = label ?? (name === "run_js" ? t.runCode : void 0);
4270
+ const title2 = h("span", "ra-tname", shown ?? name);
4271
+ if (shown) {
4260
4272
  title2.title = name;
4261
4273
  title2.classList.add("own");
4262
4274
  }
@@ -4264,18 +4276,6 @@ function renderChat(target, opts) {
4264
4276
  const tb = h("div", "ra-tbody");
4265
4277
  const argsPre = h("pre", "", name === "run_js" && args && typeof args === "object" && typeof args.code === "string" ? args.code : typeof args === "string" ? args : JSON.stringify(args, null, 2));
4266
4278
  tb.append(h("div", "ra-tlabel", t.args), argsPre);
4267
- const path = args && typeof args === "object" && typeof args.path === "string" ? args.path : null;
4268
- if (path && name !== "delete_file" && name !== "list_files" && name !== "search_files") {
4269
- const acts2 = h("div", "ra-tacts");
4270
- const o = h("button", "ra-open", `${t.open} ${path}`);
4271
- o.type = "button";
4272
- o.addEventListener("click", () => openPath(path));
4273
- const d2 = h("button", "ra-open", t.download);
4274
- d2.type = "button";
4275
- d2.addEventListener("click", () => void panel.download(path));
4276
- acts2.append(o, d2);
4277
- tb.append(acts2);
4278
- }
4279
4279
  el.append(sum, tb);
4280
4280
  const card = { el, name, args, end, body: tb, update: null, result: null };
4281
4281
  renderCustom(card, { status: "running" });
@@ -4363,15 +4363,40 @@ function renderChat(target, opts) {
4363
4363
  chev.innerHTML = I.chev(12);
4364
4364
  sum.append(chev);
4365
4365
  };
4366
- const addCard = (id, name, args, body) => {
4366
+ const addCard = (id, name, args, body, parent) => {
4367
4367
  const card = makeCard(name, args);
4368
- groupIn(body).append(card.el);
4368
+ if (parent) {
4369
+ if (!parent.nested) {
4370
+ parent.nested = h("div", "ra-tnest");
4371
+ parent.body.append(parent.nested);
4372
+ }
4373
+ parent.nested.append(card.el);
4374
+ } else groupIn(body).append(card.el);
4369
4375
  cards.set(id, card);
4370
4376
  refreshGroup(card.el);
4371
4377
  list.schedule();
4372
4378
  return card;
4373
4379
  };
4374
4380
  const imagesOf = (content) => Array.isArray(content) ? content.flatMap((p) => p.type === "image_url" && /^(data:image\/|https?:)/.test(p.image_url.url) ? [p.image_url.url] : []) : [];
4381
+ const offerFile = async (card) => {
4382
+ const ws = agent?.workspace;
4383
+ const d = displayOf(card.name), a = card.args;
4384
+ const path = d?.file ? tryDisplay(() => d.file(card.args)) : FILE_CARD_TOOLS.has(card.name) && a && typeof a === "object" && typeof a.path === "string" ? a.path : null;
4385
+ if (!ws || !path || !await isFile(ws, path)) return;
4386
+ const acts2 = h("div", "ra-tacts");
4387
+ const o = h("button", "ra-open", `${t.open} ${path}`);
4388
+ o.type = "button";
4389
+ o.addEventListener("click", () => openPath(path));
4390
+ acts2.append(o);
4391
+ if (!onOpenFile) {
4392
+ const dl = h("button", "ra-open", t.download);
4393
+ dl.type = "button";
4394
+ dl.addEventListener("click", () => void panel.download(path));
4395
+ acts2.append(dl);
4396
+ }
4397
+ card.body.querySelector(":scope>pre")?.after(acts2);
4398
+ list.schedule();
4399
+ };
4375
4400
  const finishCard = (card, status, result, durationMs, images = [], details) => {
4376
4401
  const ok = status === "ok";
4377
4402
  const fail2 = status === "error" || status === "blocked";
@@ -4391,6 +4416,10 @@ function renderChat(target, opts) {
4391
4416
  card.el.classList.toggle("fail", fail2);
4392
4417
  renderCustom(card, { status, result, details });
4393
4418
  card.update?.remove();
4419
+ if (ok) {
4420
+ if (card.el.open) void offerFile(card);
4421
+ else card.el.addEventListener("toggle", () => void offerFile(card), { once: true });
4422
+ }
4394
4423
  if (!card.result) {
4395
4424
  card.result = h("pre", "");
4396
4425
  card.body.append(h("div", "ra-tlabel", status === "error" ? t.error : t.result), card.result);
@@ -6071,7 +6100,7 @@ ${c.text}` })));
6071
6100
  on("tool_start", (ev) => {
6072
6101
  if (hiddenTools.has(ev.name)) return;
6073
6102
  flushActive(true);
6074
- const card = addCard(ev.id, ev.name, ev.args, ensureActive().body);
6103
+ const card = addCard(ev.id, ev.name, ev.args, ensureActive().body, ev.parentId ? cards.get(ev.parentId) : void 0);
6075
6104
  const r = describeRunning({ name: ev.name, args: ev.args }, card.el);
6076
6105
  showPending(r.title ? `${r.verb} ${r.what}` : r.verb, toolPreview(ev.name, ev.args));
6077
6106
  });
package/dist/workspace.js CHANGED
@@ -10,7 +10,7 @@
10
10
  // stored) and from `<userSkillsDir>` (default `/skills`), the user's own
11
11
  // skills shared by every directory of the app: zips (uploaded, read in
12
12
  // place, never unpacked) and folders (written by the user or the agent).
13
- // The file tools in file-tools.ts and the sandbox's `fs` work on it.
13
+ // The file tools in file-tools.ts work on it.
14
14
  import { toProvider } from "./provider.js";
15
15
  import { readZipEntry, MAX_ZIP_BYTES } from "./zip.js";
16
16
  import { parseSkill } from "./skills.js";
package/docs/agent.md CHANGED
@@ -85,7 +85,7 @@ agent.on("run_end", ({ reason, error, usage }) => setBusy(false));
85
85
  | `message_reset` | `reason` | A call is retried after it streamed: discard what was shown |
86
86
  | `message_end` | `message`, `truncated` | An assistant message is complete |
87
87
  | `tool_call_delta` | `index`, `id`, `name`, `delta`, `arguments` | A tool call's arguments stream in (raw JSON so far, cut anywhere); nothing runs before the reply ends |
88
- | `tool_start` / `tool_update` / `tool_end` | `id`, `name`, `args` / `content` / `status`, `result`, `details`, `durationMs` (and `content` with the pictures when the result had any) | Tool calls |
88
+ | `tool_start` / `tool_update` / `tool_end` | `id`, `name`, `args` / `content` / `status`, `result`, `details`, `durationMs` (and `content` with the pictures when the result had any) | Tool calls `parentId` on a call made from inside another (`run_js`'s `tools`). |
89
89
  | `queued` | `kind`, `message` | `steer()` or `followUp()` added to the queue |
90
90
  | `steered` | `messages` | Queued steering entered the conversation (draw it now) |
91
91
  | `compaction_start` / `compaction` | `runId?`; `summary`, `tokensBefore`, `tokensAfter`, … | Older turns are being / were summarised |
@@ -223,7 +223,7 @@ Both live in the workspace's directory: shared by every conversation that uses t
223
223
  | `workspace` | `null` | A `Workspace`: files, skills, sessions. |
224
224
  | `fileTools` | all | `false`, or a subset: `["read_file", "list_files"]` for a read-only agent. |
225
225
  | `readBeforeWrite` | `true` | Refuse to overwrite or edit an existing file the model has not read, or that changed since it read it (see [Tools](tools.md#read-before-write)). |
226
- | `sandbox` | on | The `run_js` tool; `false` removes it, `{ timeoutMs, network }` configures it. |
226
+ | `sandbox` | on | The `run_js` tool; `false` removes it, `{ timeoutMs, network, maxToolCalls, maxCodeChars }` configures it. The code calls the agent's tools, see [Tools](tools.md#calling-tools-from-run_js). |
227
227
  | `askUser` | on | The `ask_user` tool. |
228
228
  | `ui` | `domUI()` | Dialogs (`AgentUI`). |
229
229
  | `permissions` | `"ask"` | `"ask"`, `"auto"`, or a function per call. |
package/docs/chat-ui.md CHANGED
@@ -98,7 +98,7 @@ Typing `/` lists the built-in commands, then the directory's prompt templates an
98
98
  | `vars` | | Colour and font overrides (see Theming). |
99
99
  | `className` | | Extra classes on the chat's root. |
100
100
  | `debug` | `false` | The *Debug* panel. |
101
- | `onOpenFile(path)` | | Open file links yourself instead of in the files panel. |
101
+ | `onOpenFile(path)` | | Open file links yourself instead of in the files panel; tool cards then offer no download. |
102
102
  | `nextPrompt` | `false` | Suggest the user's next message: the model calls a built-in `suggest_next_prompt` tool with its final reply when an obvious next request follows (it ends the run, so no further call); the suggestion shows greyed in the empty input, Tab takes it, typing or Esc drops it. Needs the chat to own its agent. |
103
103
  | `onLink(href, text)` | | Called when a link in the conversation (a reply, its thinking, a tool card) is clicked, before the chat's own handling; return `true` when you handled it (e.g. your app's own documentation links open in your viewer). |
104
104
  | `files` | on with a workspace | The *Files* button and panel; `false` for a host with its own file view (links go to `onOpenFile`). |
@@ -259,7 +259,7 @@ The header then has no *Chats* or *New chat*; a **Clear** button, shown once the
259
259
  The chat fills the element you give it and can live in a side panel of your own page. Things to know when it does:
260
260
 
261
261
  - **Moving it** — taking the element out of the page and putting it back (a framework re-render) resets its scroll position, as for any scrolled element. Keep the element where it is, or save `element.querySelector(".ra-log").scrollTop` before and set it after.
262
- - **Your file view** — `files: false` hides the chat's Files panel; file paths in replies call `onOpenFile(path)`.
262
+ - **Your file view** — `files: false` hides the chat's Files panel; file paths in replies call `onOpenFile(path)`. Only a path that is a file of the workspace becomes a link: a card offers it for `read_file`, `write_file`, `edit_file` and a tool with `display.file`, not for any argument named `path`.
263
263
  - **Your buttons** — `headerActions: [button]` puts them in the chat's header; give each an `aria-label` (in a narrow chat the labels fold to icons).
264
264
  - **Your colours** — `palette: { light: {…}, dark: {…} }` with your page's tokens, and `vars: { font }`.
265
265
  - **Your focus styles** — a generic rule of yours such as `textarea:focus-visible { outline: … }` does not reach the composer's text area: the rounded box shows focus.
package/docs/node.md CHANGED
@@ -132,4 +132,4 @@ nodePdf();
132
132
 
133
133
  ## The sandbox
134
134
 
135
- `run_js` runs in Node through `worker_threads`, with the same limits as in a browser: no network, a time limit, `fs` bound to the workspace. Remove it with `sandbox: false`.
135
+ `run_js` runs in Node through `worker_threads`, with the same limits as in a browser: no network, a time limit, `tools` for the agent's other tools. Remove it with `sandbox: false`.
package/docs/reference.md CHANGED
@@ -59,9 +59,9 @@ Options: see [the options table](agent.md#options). Events: see [Events](agent.m
59
59
  |---|---|
60
60
  | `defineTool({ name, description, parameters?, execute, destructive?, readOnly?, endsRun?, vision?, confirm?, guidelines?, maxResultChars? })` | A tool (`confirm` returns a question, `{ title, message }` or `false`). |
61
61
  | `fileTools(workspace, { readBeforeWrite?, guard? })` | The file tools for a workspace. |
62
- | `fileGuard(workspace, { enabled? })` → `FileGuard` | What the model has read (`saw`, `wrote`, `edited`, `copied`, `check`, `forget`, `clear`); the agent shares one between the file tools and `run_js` (`sandboxTool(ws, { guard })`). |
62
+ | `fileGuard(workspace, { enabled? })` → `FileGuard` | What the model has read (`saw`, `wrote`, `edited`, `copied`, `check`, `forget`, `clear`); the agent passes one to its file tools. |
63
63
  | `connectMCP(url, { token?, headers?, prefix?, confirm?, images?, timeoutMs?, maxTools?, maxResultChars?, fetch?, signal? })` → `MCPConnection` | An MCP server's tools (`tools`, `serverTools`, `server`, `instructions`, `refresh()`, `close()`). `MCPError` for its failures. |
64
- | `sandboxTool(workspace, options)`, `runInSandbox(workspace, code, input, options)` | The `run_js` sandbox. |
64
+ | `sandboxTool(options)`, `runInSandbox(code, input, options)` | The `run_js` sandbox. `runInSandbox`'s `bridge` gives the code `tools`. |
65
65
  | `askUserTool()` | The `ask_user` tool. |
66
66
  | `normalizeResult(value)` | How a tool's return value becomes the model's result. |
67
67
  | `validateSchema(schema, value)` → `string[]` | The JSON Schema check used on arguments (the errors, empty when valid). |
package/docs/skills.md CHANGED
@@ -21,7 +21,7 @@ name: unit-convert
21
21
  description: Convert between units (length, mass, temperature, volume) with exact factors. Use whenever the user asks to convert a quantity, e.g. "10 lb to kg".
22
22
  ---
23
23
  1. Read `references/factors.md` for the factor.
24
- 2. Run `scripts/convert.js` with run_js (fs.read it, pass `input = { value, factor }`).
24
+ 2. Run `scripts/convert.js` with run_js (read it, pass `input = { value, factor }`).
25
25
  3. Answer with the result and the factor used.
26
26
  ```
27
27