@runappsai/agent 0.0.0-stage → 0.1.0

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.
Files changed (84) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +162 -2
  3. package/dist/agent-core.umd.js +266 -0
  4. package/dist/agent.d.ts +222 -0
  5. package/dist/agent.js +1331 -0
  6. package/dist/agent.umd.js +732 -0
  7. package/dist/browser.d.ts +2 -0
  8. package/dist/browser.js +4 -0
  9. package/dist/chat-theme.d.ts +24 -0
  10. package/dist/chat-theme.js +101 -0
  11. package/dist/chat.d.ts +271 -0
  12. package/dist/chat.js +4097 -0
  13. package/dist/compaction.d.ts +48 -0
  14. package/dist/compaction.js +208 -0
  15. package/dist/completion.d.ts +29 -0
  16. package/dist/completion.js +88 -0
  17. package/dist/context.d.ts +44 -0
  18. package/dist/context.js +177 -0
  19. package/dist/debug-panel.d.ts +40 -0
  20. package/dist/debug-panel.js +262 -0
  21. package/dist/dialogs.d.ts +7 -0
  22. package/dist/dialogs.js +231 -0
  23. package/dist/directory-fs.d.ts +5 -0
  24. package/dist/directory-fs.js +118 -0
  25. package/dist/dom.d.ts +83 -0
  26. package/dist/dom.js +163 -0
  27. package/dist/edit.d.ts +22 -0
  28. package/dist/edit.js +133 -0
  29. package/dist/file-guard.d.ts +46 -0
  30. package/dist/file-guard.js +153 -0
  31. package/dist/file-tools.d.ts +16 -0
  32. package/dist/file-tools.js +339 -0
  33. package/dist/files-panel.d.ts +60 -0
  34. package/dist/files-panel.js +613 -0
  35. package/dist/index.cjs +4848 -0
  36. package/dist/index.d.ts +37 -0
  37. package/dist/index.js +44 -0
  38. package/dist/json-schema.d.ts +3 -0
  39. package/dist/json-schema.js +141 -0
  40. package/dist/llm.d.ts +95 -0
  41. package/dist/llm.js +5 -0
  42. package/dist/markdown.d.ts +4 -0
  43. package/dist/markdown.js +265 -0
  44. package/dist/mcp.d.ts +82 -0
  45. package/dist/mcp.js +325 -0
  46. package/dist/node.cjs +402 -0
  47. package/dist/node.d.ts +78 -0
  48. package/dist/node.js +432 -0
  49. package/dist/pdf.d.ts +52 -0
  50. package/dist/pdf.js +77 -0
  51. package/dist/provider.d.ts +135 -0
  52. package/dist/provider.js +181 -0
  53. package/dist/sandbox.d.ts +33 -0
  54. package/dist/sandbox.js +219 -0
  55. package/dist/select.d.ts +30 -0
  56. package/dist/select.js +185 -0
  57. package/dist/skill-zips.d.ts +28 -0
  58. package/dist/skill-zips.js +123 -0
  59. package/dist/skills.d.ts +20 -0
  60. package/dist/skills.js +111 -0
  61. package/dist/templates.d.ts +24 -0
  62. package/dist/templates.js +136 -0
  63. package/dist/tool.d.ts +28 -0
  64. package/dist/tool.js +102 -0
  65. package/dist/types.d.ts +571 -0
  66. package/dist/types.js +7 -0
  67. package/dist/ui.cjs +6246 -0
  68. package/dist/ui.d.ts +6 -0
  69. package/dist/ui.js +11 -0
  70. package/dist/vlist.d.ts +80 -0
  71. package/dist/vlist.js +277 -0
  72. package/dist/workspace.d.ts +343 -0
  73. package/dist/workspace.js +1203 -0
  74. package/dist/zip.d.ts +26 -0
  75. package/dist/zip.js +204 -0
  76. package/docs/agent.md +228 -0
  77. package/docs/chat-ui.md +307 -0
  78. package/docs/node.md +135 -0
  79. package/docs/providers.md +176 -0
  80. package/docs/reference.md +143 -0
  81. package/docs/skills.md +131 -0
  82. package/docs/tools.md +254 -0
  83. package/docs/workspace.md +198 -0
  84. package/package.json +59 -4
@@ -0,0 +1,143 @@
1
+ # API reference
2
+
3
+ Three entry points:
4
+
5
+ | Import | |
6
+ |---|---|
7
+ | `@runappsai/agent` | The core — everything below except the last two sections. No DOM: browsers, Node, Deno, workers. |
8
+ | `@runappsai/agent/ui` | The chat UI and browser helpers ([Chat UI](#chat-ui--guide) below). |
9
+ | `@runappsai/agent/node` | Node helpers ([Node](#node--guide) below). |
10
+ | `@runappsai/agent/browser` | `agent.umd.js`: the core and the UI as one script, on `window.RunAppsAgent` (`/browser/core`: the core alone). |
11
+
12
+ ## Providers — [guide](providers.md)
13
+
14
+ | Export | |
15
+ |---|---|
16
+ | `openAIProvider({ baseURL, apiKey?, headers?, models?, streamUsage?, fetch?, name? })` | Any OpenAI-compatible API. |
17
+ | `runappsProvider(client)` | The RunApps SDK client. |
18
+ | `toProvider(providerOrClient)` | A provider as is, a RunApps client wrapped. |
19
+ | `ProviderError(status, message, { code?, retryAfter? })` | Throw from your provider; 408 / 429 / 5xx / 0 are retried. |
20
+ | `sseData(body, signal?)` | Yields the `data:` payloads of a server-sent event stream. |
21
+ | `modelAccepts(model, kind)` | Whether a catalogue entry takes `"image"` / `"video"` / `"audio"` (from `input_modalities`, or a `vision` capability). |
22
+ | types | `ModelProvider`, `ModelInfo`, `InputKind`, `OpenAIProviderOptions`, `RunAppsClientLike`, `ChatMessage`, `ContentPart`, `ChatTool`, `ChatToolCall`, `ChatCompletionParams`, `ChatCompletionChunk`, `ChatCompletion`, `Usage` |
23
+
24
+ ## Agent — [guide](agent.md)
25
+
26
+ `createAgent(provider, options)` → `Agent` (also `new Agent(provider, options)`).
27
+
28
+ | Member | |
29
+ |---|---|
30
+ | `prompt(content, { signal })` | Start a run (queued as a follow-up while one is running). → `RunResult` |
31
+ | `steer(content)` | Insert into the running run (starts one when idle). |
32
+ | `followUp(content)` | Run after the current run. → `RunResult` |
33
+ | `continue()` | Carry on without a new message. → `RunResult` |
34
+ | `abort()` | Stop the run. |
35
+ | `rewind(index)` | Drop the messages from `index` on. |
36
+ | `remove(start, end?)` | Delete messages `start` to `end` (a question and its answer). |
37
+ | `clear()` | Start over under the same id (messages, queue, usage), saved. |
38
+ | `modelInfo()`, `accepts(kind)` | The catalogue's entry for the model in use; whether it takes `"image"` / `"video"` / `"audio"` (`true` / `false` / `undefined`). |
39
+ | `compact(focus?)` | Summarise older turns now. → `boolean` |
40
+ | `queued`, `dequeue(message)`, `clearQueue()` | What waits. |
41
+ | `on(event, handler)` / `on("*", (name, event) => …)` | Subscribe; returns an unsubscribe function. |
42
+ | `ready()` | Resolves once a saved session is loaded. |
43
+ | `configure(patch)`, `settings` | `model`, `maxTurns`, `maxTokens`, `permissions`, `reasoningEffort`. |
44
+ | `limits()` → `{ input, output }`, `context()` → `{ used, window }` | Model limits, context use. |
45
+ | `useSkill(name)` | Load a skill for the next prompt. |
46
+ | `systemPrompt()` | The system prompt as it would be sent. |
47
+ | `export()` → `SessionData`, `reset()` | Save / forget the conversation. |
48
+ | `messages`, `usage`, `busy`, `model`, `id`, `provider`, `workspace`, `tools`, `ui`, `lastEnd` | State. |
49
+
50
+ Options: see [the options table](agent.md#options). Events: see [Events](agent.md#events).
51
+
52
+ ## Tools — [guide](tools.md)
53
+
54
+ | Export | |
55
+ |---|---|
56
+ | `defineTool({ name, description, parameters?, execute, destructive?, readOnly?, endsRun?, vision?, confirm?, guidelines?, maxResultChars? })` | A tool (`confirm` returns a question, `{ title, message }` or `false`). |
57
+ | `fileTools(workspace, { readBeforeWrite?, guard? })` | The file tools for a workspace. |
58
+ | `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 })`). |
59
+ | `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. |
60
+ | `sandboxTool(workspace, options)`, `runInSandbox(workspace, code, input, options)` | The `run_js` sandbox. |
61
+ | `askUserTool()` | The `ask_user` tool. |
62
+ | `normalizeResult(value)` | How a tool's return value becomes the model's result. |
63
+ | `validateSchema(schema, value)` → `string[]` | The JSON Schema check used on arguments (the errors, empty when valid). |
64
+ | types | `Tool`, `ToolDefinition`, `ToolContext`, `ToolConfirm`, `ToolResultValue`, `ToolStatus`, `JSONSchema`, `FileToolsOptions`, `FileGuard`, `MCPConnection`, `MCPOptions`, `MCPToolInfo` |
65
+
66
+ ## Dialogs
67
+
68
+ | Export | |
69
+ |---|---|
70
+ | `domUI()` | Plain `<dialog>`s (the default). |
71
+ | `nullUI()` | Declines every question. |
72
+ | types | `AgentUI` (`confirm`, `select`, `input`, `notify`), `SelectOption` |
73
+
74
+ ## Workspace — [guide](workspace.md), [skills](skills.md)
75
+
76
+ `openWorkspace(provider | null, options)` → `Workspace` (also `Workspace.open(...)`).
77
+
78
+ Options: `id`, `project`, `dir`, `store`, `skills`, `skillsDir`, `userSkills`, `userSkillsDir`, `fetch`, `indexedDB`, `inflate`.
79
+
80
+ | Member | |
81
+ |---|---|
82
+ | `list(prefix)`, `stat(path)`, `exists(path)`, `isFolder(path)` | Look. |
83
+ | `read(path)` → `{ data, size, contentType }`, `readText(path)`, `readAsText(path)` | Read (PDFs as text). |
84
+ | `write(path, content, contentType?)`, `edit(path, edits)`, `delete(path)`, `clearWork()`, `destroy()` | Change (`edit`: `{ oldText, newText }` replacements; a mount's own `edit()` gets them). |
85
+ | `mount(prefix, fs)`, `unmount(prefix)`, `mountOf(path)`, `isReadOnly(path)`, `isSkillPath(path)` | Mounts. |
86
+ | `onChange(fn)` | `{ path, kind, remote }` for every write and delete. |
87
+ | `getData(key)`, `putData(key, value)`, `deleteData(key)` | Your data kept with the directory. |
88
+ | `skills()`, `skillBody(name)`, `installSkill(source, { name?, unpack? })`, `removeSkill(name)`, `refreshSkills()` | Skills. |
89
+ | `sessions.list()`, `.get(id)`, `.save(data)`, `.delete(id)`, `.clear()` | Saved conversations. |
90
+ | `describe()` | What the system prompt says about the directory. |
91
+ | `close()` | Release the database (it reopens on use). |
92
+ | `id`, `dbName`, `skillsDir`, `userSkillsDir`, `root` | State. |
93
+
94
+ | Export | |
95
+ |---|---|
96
+ | `memoryFS(files, { description?, readonly? })` | An in-memory `AgentFS` to mount. |
97
+ | `listTemplates(workspace)`, `expandSlash(workspace, text)` | Prompt templates. |
98
+ | `parseSkill(text, path)`, `parseFrontmatter(text)`, `skillFoldersOf(paths, name)`, `skillZipFS(...)`, `subFS(fs, base)` | Skill helpers. |
99
+ | `normalizePath(path)` | `/a/../b//c` → `/b/c`. |
100
+ | `guessType(path, data)`, `decodeText(bytes)` | A content type from a name; UTF-8 text or null. |
101
+ | `titleOf(session)`, `UNTITLED` | A session's title (the user's first words). |
102
+ | `configurePdf({ url?, workerUrl?, load? })`, `extractPdfText(bytes)`, `formatPdfText(path, result)`, `isPdf(path, type?, data?)` | PDFs. |
103
+ | `DEFAULT_SKILLS_DIR`, `DEFAULT_USER_SKILLS_DIR` | `/.agent/skills`, `/skills`. |
104
+ | types | `AgentFS` (`list`, `read`; optional `write`, `edit`, `delete`, `stat`), `TextEdit`, `FileStat`, `Skill`, `SkillSource`, `LazySkill`, `WorkspaceOptions`, `WorkspaceRead`, `WorkspaceChange`, `SessionStore`, `SessionData`, `SessionSummary`, `RunEnd`, `WorkspaceStore`, `WorkspaceStoreFactory`, `FileRecord` (for a `store` of your own) |
105
+
106
+ ## Lower level
107
+
108
+ | Export | |
109
+ |---|---|
110
+ | `collectCompletion(stream, params, opts)` | Gathers a streamed completion (text, thinking, tool calls). |
111
+ | `buildSystemPrompt(input)`, `estimateTokens(messages)`, `fitBudget(...)`, `groupTurns(...)` | Context building. |
112
+ | `planCut(messages, keepRecentTokens)`, `serializeConversation(messages)`, `splitForSummary(text, maxChars)`, `summaryOf(message)`, `summaryMessage(summary)` | Compaction. |
113
+ | `applyEdits(text, edits)`, `normalizeForFuzzyMatch(text)` | The edit matching of `edit_file`. |
114
+ | `parseCommandArgs(text)`, `substituteArgs(template, args)` | Template arguments. |
115
+ | `listZip(bytes)`, `readZipEntry(bytes, entry)`, `buildZip(entries)` | Zip files. |
116
+
117
+ ## Chat UI — [guide](chat-ui.md)
118
+
119
+ From `@runappsai/agent/ui`.
120
+
121
+ | Export | |
122
+ |---|---|
123
+ | `renderChat(element, options)` → `ChatHandle` | The chat. |
124
+ | `selectBox(host, { options, value, filterAt?, placeholder?, filterLabel? })` → `SelectBox` | The dropdown (`el`, `value`, `setOptions`, `close()`). |
125
+ | `enhanceSelect(select, host)` → `SelectBox & { destroy() }` | Give a `<select>` the dropdown's look; `destroy()` puts the plain one back. |
126
+ | `VirtualList` | The transcript's virtual list. |
127
+ | `renderMarkdown(text)`, `renderInline(text)`, `escapeHTML(text)` | The Markdown renderer. |
128
+ | `CHAT_PALETTES`, `CHAT_COLOR_TOKENS`, `CHAT_SHARED_TOKENS` | Theming. |
129
+ | `directoryFS(handle, { description?, readonly? })` | A folder the user picked (File System Access API) as an `AgentFS`. |
130
+ | types | `ChatOptions`, `ChatHandle`, `ChatPalette`, `ChatVars`, `ChatToken`, `ChatColorToken`, `SelectBox`, `VRow`, `VListOptions` |
131
+
132
+ ## Node — [guide](node.md)
133
+
134
+ From `@runappsai/agent/node` (Node 18+).
135
+
136
+ | Export | |
137
+ |---|---|
138
+ | `nodeFS(folder, { description?, readonly?, ignore? })` | A folder on disk as an `AgentFS` (`dir`). |
139
+ | `nodeStore(folder?)` → `WorkspaceStoreFactory` | The workspace's storage on disk (`store`); default `~/.runapps-agent`. |
140
+ | `terminalUI({ input?, output?, rl?, ask? })` → `AgentUI` | Dialogs in the terminal. |
141
+ | `lineReader({ input?, output? })` → `{ ask(prompt, signal?), rl, close() }` | Queued terminal lines, one reader per input. |
142
+ | `nodePdf()` | Read PDFs with the `pdfjs-dist` package. |
143
+ | types | `NodeFSOptions`, `TerminalUIOptions`, `LineReader` |
package/docs/skills.md ADDED
@@ -0,0 +1,131 @@
1
+ # Skills
2
+
3
+ A skill is a folder of instructions (and optionally reference files and scripts) that the agent loads when a task calls for it — the same format as Claude Code and pi skills. Only each skill's name and description are in the system prompt; the agent reads the rest when it needs it, so a large skill costs nothing until it is used.
4
+
5
+ ## A skill
6
+
7
+ ```
8
+ unit-convert/
9
+ ├── SKILL.md
10
+ ├── references/
11
+ │ └── factors.md
12
+ └── scripts/
13
+ └── convert.js
14
+ ```
15
+
16
+ `SKILL.md` starts with frontmatter:
17
+
18
+ ```markdown
19
+ ---
20
+ name: unit-convert
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
+ ---
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 }`).
25
+ 3. Answer with the result and the factor used.
26
+ ```
27
+
28
+ | Frontmatter | |
29
+ |---|---|
30
+ | `name` | Lowercase, digits and hyphens. Defaults to the folder name. |
31
+ | `description` | Required. What the skill does and when to use it — see below. |
32
+ | `disable-model-invocation: true` | The agent never picks it by itself; it runs only when asked with `/skill:name`. |
33
+ | `license`, `compatibility`, `allowed-tools`, `metadata` | Kept on the `Skill` object. |
34
+
35
+ Package skills as a zip: either `SKILL.md` at the root (one skill, named after the zip), or one folder per skill.
36
+
37
+ Scripts run only as JavaScript (`run_js`: a Worker, no shell, no Python, no network). The agent is told that a script in another language is to be read, ported to JavaScript and run that way — so a skill written with Python helpers still works when its logic is portable.
38
+
39
+ ### Writing the description
40
+
41
+ The description is all the model sees before deciding to load a skill, so it decides whether the skill is ever used. Say what it does and *when*: the situations, the kinds of request, the words a user would use, in one to three sentences.
42
+
43
+ ```yaml
44
+ # rarely used: a feature list
45
+ description: Novel writing engine with character, plot and dialogue tools.
46
+
47
+ # used reliably: scope, situations, user phrasing
48
+ description: Writes web-novel chapters from an outline in the genre's style (xianxia, romance, system, urban…). Use when the user gives an outline or chapter brief and asks for the text, a title, a blurb, or a rewrite ("make it punchier", "funnier").
49
+ ```
50
+
51
+ Keep the first sentence self-contained, name concrete triggers, and leave the how-to for the body.
52
+
53
+ ## Where skills come from
54
+
55
+ The agent reads skills from **`/.agent/skills/<name>/`**. That folder is virtual and read-only: it is generated in memory when the workspace opens (and whenever the user's skills change) from two sources.
56
+
57
+ ### 1. The app's skills — the `skills` option
58
+
59
+ ```js
60
+ openWorkspace(provider, {
61
+ skills: [
62
+ "/skills.zip", // a URL or a path in your bundle
63
+ "files:packs/design.zip", // RunApps: a file in the user's storage
64
+ someFile, // a Blob / File from an <input>
65
+ { name: "review", data: zipBytes }, // bytes, with a name
66
+ ],
67
+ });
68
+ ```
69
+
70
+ They are read in place each time the page opens them — never unpacked, never stored (a URL is fetched once per page; `workspace.refreshSkills()` fetches again). The user cannot remove them (`Skill.builtin`).
71
+
72
+ ### Lazy skills: load on first use
73
+
74
+ For many skills, or skills kept on your server, give each one's name and description and a way to get its zip. The zip is fetched only the first time the skill is used — when the agent reads one of its files, or the user types `/skill:name`:
75
+
76
+ ```js
77
+ openWorkspace(provider, {
78
+ // a function returning the list — sync or async — is called at open and by refreshSkills()
79
+ skills: async () => {
80
+ const list = await fetch("/api/skills").then((r) => r.json());
81
+ return list.map((s) => ({
82
+ name: s.name,
83
+ description: s.description,
84
+ load: () => fetch(`/api/skills/${s.name}.zip`).then((r) => r.blob()),
85
+ // or: load: () => `/api/skills/${s.name}.zip` (a URL is fetched for you)
86
+ }));
87
+ },
88
+ });
89
+ ```
90
+
91
+ - Listing costs nothing: the prompt, the skills menu and the `/` menu show lazy skills without loading them (`Skill.lazy`).
92
+ - `load()` returns a Blob, ArrayBuffer, Uint8Array, or a URL / `files:` path to fetch. It runs once per page; every conversation shares the result.
93
+ - A failed load is reported to the agent ("the skill … could not be loaded: …") and tried again the next time.
94
+ - Lazy and ordinary sources can be mixed in one list.
95
+
96
+ ### 2. The user's skills — `/skills/`
97
+
98
+ Unless turned off, each app has a **`/skills/`** folder shared by every conversation, visible in the chat's files panel:
99
+
100
+ - **zips** the user uploads (Skills menu → Upload zip, or `workspace.installSkill(file)`) are kept as `/skills/<name>.zip` and read in place;
101
+ - **folders** `/skills/<name>/SKILL.md` — written by the user, or by the agent when asked to make a skill (its prompt tells it where).
102
+
103
+ A user's skill with the same name as one of the app's takes its place.
104
+
105
+ ```js
106
+ const added = await workspace.installSkill(file); // a zip File / Blob / bytes / URL → /skills/<name>.zip
107
+ await workspace.installSkill(file, { name: "my-tool", unpack: true }); // as editable files in /skills/my-tool/
108
+ await workspace.removeSkill("my-tool"); // the user's only; the app's cannot be removed
109
+ ```
110
+
111
+ ### Only the app's skills
112
+
113
+ ```js
114
+ openWorkspace(provider, { userSkills: false, skills: appSkills });
115
+ ```
116
+
117
+ No `/skills/` folder, nothing to upload or remove (the chat's Skills menu shows neither), `installSkill` refuses, and the agent is not told it may make skills.
118
+
119
+ ## Using skills
120
+
121
+ - The model loads a skill by itself when a task matches its description (unless `disable-model-invocation`).
122
+ - The user types **`/skill:name`** (with arguments after it) to use one explicitly; the chat's Skills menu puts it in the composer.
123
+ - From code: `agent.useSkill("name")` loads it for the next prompt.
124
+
125
+ ```js
126
+ const skills = await workspace.skills();
127
+ // [{ name, description, path, dir, builtin?, lazy?, from?, disableModelInvocation? }]
128
+ const { body } = await workspace.skillBody("unit-convert");
129
+ ```
130
+
131
+ `skillsDir` (default `/.agent/skills`) and `userSkillsDir` (default `/skills`) move the two folders.
package/docs/tools.md ADDED
@@ -0,0 +1,254 @@
1
+ # Tools
2
+
3
+ A tool is a function the model may call. Describe it, declare its arguments as JSON Schema, and implement `execute`.
4
+
5
+ ```js
6
+ import { defineTool } from "@runappsai/agent";
7
+
8
+ const getWeather = defineTool({
9
+ name: "get_weather",
10
+ description: "Current weather for a city. Use when the user asks about the weather or what to wear.",
11
+ parameters: {
12
+ type: "object",
13
+ properties: {
14
+ city: { type: "string", description: "City name, e.g. 'Lisbon'" },
15
+ unit: { type: "string", enum: ["c", "f"], default: "c" },
16
+ },
17
+ required: ["city"],
18
+ additionalProperties: false,
19
+ },
20
+ async execute({ city, unit = "c" }, { signal }) {
21
+ const res = await fetch(`/api/weather?city=${encodeURIComponent(city)}&unit=${unit}`, { signal });
22
+ return res.json(); // any JSON value is sent to the model as JSON
23
+ },
24
+ });
25
+
26
+ createAgent(provider, { tools: [getWeather] });
27
+ ```
28
+
29
+ ## Writing a good tool
30
+
31
+ - **`name`** — `^[A-Za-z0-9_-]{1,64}$`. Verbs in snake_case read best (`create_invoice`).
32
+ - **`description`** — what it does *and when to use it*. The model decides from this alone.
33
+ - **`parameters`** — close objects with `additionalProperties: false` and list `required`. Arguments are checked against the schema before `execute` runs; a mismatch goes back to the model as a readable error and the model corrects the call.
34
+ - **`guidelines`** — one or more sentences for the system prompt when a rule is too long for the description (`"Always call list_invoices before create_invoice to avoid duplicates."`).
35
+
36
+ ## What `execute` gets
37
+
38
+ ```js
39
+ execute(args, ctx)
40
+ ```
41
+
42
+ | `ctx` | |
43
+ |---|---|
44
+ | `signal` | Aborted when the user stops the run. Pass it to `fetch` and long loops. |
45
+ | `update(text)` | Report progress; shown live by the chat UI (a `tool_update` event). |
46
+ | `ui` | The agent's dialogs (`confirm`, `select`, `input`, `notify`). |
47
+ | `workspace` | The agent's workspace, or null. |
48
+ | `agent` | The agent. |
49
+ | `callId` | The model's id for this call. |
50
+ | `progress(made)` | Say whether this call brought anything new (see [Calls that go nowhere](#calls-that-go-nowhere)). |
51
+
52
+ ```js
53
+ const exportReport = defineTool({
54
+ name: "export_report",
55
+ description: "Export the report as a PDF into the workspace.",
56
+ async execute(_args, { update, workspace, signal }) {
57
+ update("Collecting data…");
58
+ const data = await loadData({ signal });
59
+ update(`Rendering ${data.pages} pages…`);
60
+ const pdf = await renderPdf(data, { signal });
61
+ await workspace.write("/exports/report.pdf", pdf, "application/pdf");
62
+ return "Saved /exports/report.pdf";
63
+ },
64
+ });
65
+ ```
66
+
67
+ ## What `execute` returns
68
+
69
+ | Return | The model gets |
70
+ |---|---|
71
+ | a string | the string |
72
+ | a number, boolean, object, array | JSON |
73
+ | content parts `[{ type: "text", … }, { type: "image_url", … }]` | text and pictures |
74
+ | `{ content, details }` | `content` only; `details` stays for your app (in the `tool_end` event) |
75
+ | `undefined`, `null`, `""` | `"OK"` |
76
+
77
+ Results longer than `maxResultChars` (default 32 000 characters) are cut, with a note saying so. A thrown error is sent to the model as an error result.
78
+
79
+ A tool message can only carry text in the OpenAI format, so pictures (and audio or video) a tool returns go to the model in a user message right after the batch's results, each labelled with the call it came from. Only the latest two batches' pictures are sent again on later turns — each costs thousands of tokens; older ones are replaced by a note telling the model to call the tool again for the current state.
80
+
81
+ ```js
82
+ // A screenshot back to a vision model
83
+ execute: async () => [
84
+ { type: "text", text: "The current canvas:" },
85
+ { type: "image_url", image_url: { url: await canvas.toDataURL("image/png") } },
86
+ ]
87
+ ```
88
+
89
+ ## Asking before acting
90
+
91
+ ```js
92
+ const deleteProject = defineTool({
93
+ name: "delete_project",
94
+ description: "Delete a project and all its files.",
95
+ parameters: { type: "object", properties: { id: { type: "string" } }, required: ["id"], additionalProperties: false },
96
+ destructive: true, // asks "Allow delete_project?" first
97
+ confirm: ({ id }) => `Delete project ${id} and all its files?`, // or your own question
98
+ execute: ({ id }) => api.deleteProject(id),
99
+ });
100
+ ```
101
+
102
+ Under `permissions: "ask"` (the default) a tool with `destructive: true` or a `confirm` asks the user first. `confirm` may return `false` to run without asking this time (`({ id }) => isDraft(id) ? false : "Delete …?"`), or `{ title, message }` to show the details under the question (`message` goes to `ui.confirm`'s second argument — the arguments, what will happen). A declined call returns `"declined"` to the model. `{ title, always: { label, onChoose } }` adds a third answer to the question ("Always allow"): the call runs and `onChoose()` is called — where you stop asking from then on (turn your app's auto-apply setting on). `ok` names the confirm button ("Apply"), and `body: () => element` puts content of your own in the question — a diff with a checkbox per change, say: the chat shows it under the message, the user sets what they like in it, and `execute` reads that from the element (keep a reference in the tool's closure); a terminal leaves it out. See [Permissions and dialogs](agent.md#permissions-and-dialogs) for the other modes.
103
+
104
+ ### Refusing a call before it is asked: `validate`
105
+
106
+ The schema checks the shape of the arguments; `validate(args)` checks what the schema cannot — the text to replace is not in the document, the record changed since it was read. It runs after the schema check and before any question: return (or throw) the reason and the call ends there, the model gets the reason as its error, and the user is never asked to approve a call that would fail.
107
+
108
+ ```js
109
+ defineTool({
110
+ name: "edit_doc",
111
+ // …
112
+ validate: ({ oldText }) => (doc.includes(oldText) ? undefined : "oldText is not in the document; read it again"),
113
+ confirm: () => "Apply this change?",
114
+ execute: ({ oldText, newText }) => { /* … */ },
115
+ });
116
+ ```
117
+
118
+ `execute` still has to check again when it can be called with something that changed in between (the user typed while the question waited).
119
+
120
+ ## Stopped while running: `whenStopped`
121
+
122
+ When the user stops the run while a call is still running, the run ends at once; the call's own work may go on (a batch already started). By default the model is told the call was skipped. `whenStopped(args)` returns what it should be told instead — how far the call got — so a later turn does not redo it:
123
+
124
+ ```js
125
+ defineTool({
126
+ name: "run_batch",
127
+ // …
128
+ whenStopped: (args) => JSON.stringify({ ok: false, error: "stopped by the user", done: finishedOf(args.ids) }),
129
+ });
130
+ ```
131
+
132
+ ## How the chat shows a call: `display`
133
+
134
+ `renderChat` shows a call as a card: the tool's name, its arguments, its result. A tool for people who never see tool names says it in its own words (the model never sees any of this; an exception in one of these falls back to the default):
135
+
136
+ ```js
137
+ defineTool({
138
+ name: "add_node",
139
+ // …
140
+ display: {
141
+ label: (args) => `Add a ${args.type} node`, // the card's title and the folded line ("Add a Text node ×2")
142
+ icon: "<svg …>", // the card's icon
143
+ render: ({ args, status, result, details }) => chipsFor(args, result), // your element under the title, visible while folded
144
+ outcome: ({ result }) => summaryOf(result), // beside the status mark ("Added", "$0.12")
145
+ },
146
+ });
147
+ ```
148
+
149
+ `render` runs when the call starts (`status: "running"`) and again with the result; `details` is what `execute` returned as details (live calls; a reopened conversation has only the result text). The arguments and the raw result stay in the card, behind its fold. `display: { hidden: true }` gives a tool no card at all (nor a line in the exported conversation): a call the user need not see.
150
+
151
+ ## Tools that end the run
152
+
153
+ Normally every tool call is followed by another model call, so the model can use the result. A tool whose result the model does not need can say `endsRun: true`: when a reply has text and calls only such tools, the agent runs them and the run ends there — no further call, no tokens spent resending the conversation. Called alongside other tools, or in a reply with no text, the run goes on as usual. The chat's next-message suggestion (`nextPrompt`) is such a tool.
154
+
155
+ ## Tools for models that see
156
+
157
+ `vision: true` offers a tool only while the model in use is known to see pictures — a screenshot tool, say, is useless to a text-only model, and offering it invites a call whose result it cannot read:
158
+
159
+ ```js
160
+ const screenshot = defineTool({
161
+ name: "capture_page",
162
+ description: "A picture of the page as the user sees it now.",
163
+ readOnly: true,
164
+ vision: true,
165
+ execute: async () => [{ type: "text", text: "The page:" }, { type: "image_url", image_url: { url: await snap() } }],
166
+ });
167
+ ```
168
+
169
+ ## Calls that go nowhere
170
+
171
+ Models sometimes circle: they read the same lines again with another limit, repeat a search, retry a call that fails the same way. The agent watches each round of tool calls for anything new:
172
+
173
+ - A tool that **changes things** succeeding with arguments it has not had before is progress.
174
+ - A **read-only** tool (`readOnly: true`) is progress only when its result is one the run has not had since the last change — reading another range of lines already read is not (`read_file` reports that itself).
175
+ - The same error again is not progress; a declined call or the user steering is.
176
+
177
+ After three rounds in a row without anything new the model is told to use what it has already read; after six the run ends with an error. Mark your look-only tools `readOnly: true`, and call `ctx.progress(false)` when a call returned nothing new in a way the result text does not show (a refreshed timestamp, say). `loopGuard: { warn, stop }` changes the counts; `loopGuard: false` turns it off.
178
+
179
+ ```js
180
+ const listOrders = defineTool({
181
+ name: "list_orders",
182
+ description: "List the user's orders, newest first.",
183
+ readOnly: true,
184
+ execute: async (_args, ctx) => {
185
+ const { orders, fetchedAt } = await api.orders();
186
+ return { orders }; // fetchedAt left out: it would make every result look new
187
+ },
188
+ });
189
+ ```
190
+
191
+ ## MCP servers
192
+
193
+ `connectMCP(url, options)` connects to a [Model Context Protocol](https://modelcontextprotocol.io) server over Streamable HTTP and returns its tools, ready for an agent. No SDK: plain `fetch`, in browsers and Node.
194
+
195
+ ```js
196
+ import { connectMCP, createAgent } from "@runappsai/agent";
197
+
198
+ const github = await connectMCP("https://mcp.example.com/mcp", { token: githubToken });
199
+ const agent = createAgent(provider, {
200
+ tools: [...myTools, ...github.tools],
201
+ instructions: [myInstructions, github.instructions].filter(Boolean).join("\n\n"),
202
+ });
203
+ // …
204
+ await github.close(); // ends the session on the server
205
+ ```
206
+
207
+ | Option | Default | |
208
+ |---|---|---|
209
+ | `token` | | Sent as `Authorization: Bearer …`. |
210
+ | `headers` | | More request headers. |
211
+ | `name` | the server's own | What the server is called in tool descriptions and confirmations (the name the user gave it). |
212
+ | `prefix` | the server's name | Tool names are `<prefix>__<tool>` (64 characters at most), so two servers' tools never clash. |
213
+ | `confirm` | `"always"` | Ask before every call (`"ask"` permissions); `"unless-read-only"` lets tools the server marks `readOnlyHint` run without asking; `"never"`. The question names the server and the tool and shows the arguments. |
214
+ | `images` | `false` | Pass pictures a tool returns to the model; otherwise they are named, not sent. |
215
+ | `timeoutMs` | `60000` | Longest a request may take. |
216
+ | `maxTools`, `maxResultChars` | `64`, `32000` | Limits. |
217
+ | `fetch` | global | Your own fetch (a proxy, tests). |
218
+ | `signal` | | Cancels connecting. |
219
+
220
+ The connection has `tools`, `serverTools` (what the server said about each), `server` (`{ name, version, title }`), `instructions`, `refresh()` (read the list again) and `close()`.
221
+
222
+ What it handles: the session id the server gives, answers that come as JSON or as an event stream, progress notifications (shown as the call's `tool_update`), a session the server has forgotten (started again once), stopping a call (the server is sent a cancellation), and requests the server makes of the client (`ping` is answered; sampling and the like are declined). A tool's text, resources and links go to the model; `isError` results become errors. Errors never include the token or the server's response headers; a call that fails after it was sent says its effect on the server is unknown, so the model does not repeat a side effect blindly.
223
+
224
+ In a browser the server must allow your page's origin (CORS) and expose the `Mcp-Session-Id` header. OAuth sign-in and local (stdio) servers are not supported: get the token yourself and pass it.
225
+
226
+ ## Built-in tools
227
+
228
+ | Tool | | Option |
229
+ |---|---|---|
230
+ | `ask_user` | One to three questions to the user, with options or free text, when a request is unclear. | `askUser: false` removes it |
231
+ | `run_js` | JavaScript the model writes, run in a Worker: no DOM, no network, a captured console, and `fs` bound to the workspace. The model computes, parses and transforms data with it instead of guessing, and runs skills' scripts. | `sandbox: false`, or `{ timeoutMs, network }` |
232
+ | `list_files` | Files under a folder, with sizes. | with a workspace |
233
+ | `read_file` | A file, 2000 lines / 50 KB per call, `offset` and `limit` to continue; a PDF as text; a picture shown to a model that sees pictures. | |
234
+ | `write_file` | Create or replace a file (`replace: true`: without reading it first, for a rewrite from scratch). | |
235
+ | `edit_file` | One or more exact replacements — the model sends only the changed pieces; tolerant of curly quotes, dashes and trailing spaces. A mount with its own `edit()` applies them itself ([Workspace](workspace.md#mounting-your-apps-data)). | |
236
+ | `delete_file` | Delete a file (asks). | |
237
+ | `move_file`, `copy_file` | Move/rename or copy a file; never over an existing one. What was read of the source counts as read of the copy. | |
238
+ | `search_files` | Search file contents. | |
239
+
240
+ ### Read before write
241
+
242
+ The agent does not change a file from a stale or partial view of it — the user may be editing files while it works:
243
+
244
+ - **Overwrite** (`write_file`, `fs.write` in `run_js`) of an existing file needs the model to have read all of it in this conversation. After a partial read, `write_file` refuses once and puts the unread lines in its error (up to one read's worth: 2000 lines or 50 KB); they count as read, so the next `write_file` goes through, or the error says from which `offset` to read on. `fs.write` just says to read the rest.
245
+ - **`replace: true`** on `write_file` overwrites an existing file without reading it, for when the user asked for it to be rewritten from scratch. The result says what went unread (`Replaced /a.js (3 bytes). Its previous content (3 lines) was replaced without being read.`), so it shows in the tool card. The parameter exists only while the guard is on.
246
+ - **Edit** (`edit_file`) needs it to have read the file — part is enough, since an edit only replaces the text it quotes.
247
+ - **Delete** (`delete_file`, `fs.remove`) of a file it read is refused if the file changed since; a file it never read can be deleted.
248
+ - Any of them is refused when the file **changed since the model read it** — the user edited it in the files panel, your app changed a mounted document, another tab wrote it. The model is told why and reads the file again.
249
+
250
+ New files can always be written, and the model's own writes count as read. `fs.read` in `run_js` counts as reading. A file's version is its modified time, size and a fingerprint of its content (files over 4 MB: time and size), so even a same-size change in the same instant shows. What the model has read is forgotten when the conversation is compacted or rewound, since it no longer has those contents. Turn it all off with `readBeforeWrite: false`.
251
+
252
+ The file tools come with a workspace; `fileTools: ["read_file", "list_files", "search_files"]` gives a read-only agent, `fileTools: false` none.
253
+
254
+ `sandboxTool(workspace, options)` and `runInSandbox(workspace, code, input)` are exported if you want the sandbox on its own.