@runappsai/agent 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +162 -2
- package/dist/agent-core.umd.js +266 -0
- package/dist/agent.d.ts +222 -0
- package/dist/agent.js +1331 -0
- package/dist/agent.umd.js +732 -0
- package/dist/browser.d.ts +2 -0
- package/dist/browser.js +4 -0
- package/dist/chat-theme.d.ts +24 -0
- package/dist/chat-theme.js +101 -0
- package/dist/chat.d.ts +271 -0
- package/dist/chat.js +4099 -0
- package/dist/compaction.d.ts +48 -0
- package/dist/compaction.js +208 -0
- package/dist/completion.d.ts +29 -0
- package/dist/completion.js +88 -0
- package/dist/context.d.ts +44 -0
- package/dist/context.js +177 -0
- package/dist/debug-panel.d.ts +40 -0
- package/dist/debug-panel.js +262 -0
- package/dist/dialogs.d.ts +7 -0
- package/dist/dialogs.js +231 -0
- package/dist/directory-fs.d.ts +5 -0
- package/dist/directory-fs.js +118 -0
- package/dist/dom.d.ts +83 -0
- package/dist/dom.js +163 -0
- package/dist/edit.d.ts +22 -0
- package/dist/edit.js +133 -0
- package/dist/file-guard.d.ts +46 -0
- package/dist/file-guard.js +153 -0
- package/dist/file-tools.d.ts +16 -0
- package/dist/file-tools.js +339 -0
- package/dist/files-panel.d.ts +60 -0
- package/dist/files-panel.js +613 -0
- package/dist/index.cjs +4848 -0
- package/dist/index.d.ts +37 -0
- package/dist/index.js +44 -0
- package/dist/json-schema.d.ts +3 -0
- package/dist/json-schema.js +141 -0
- package/dist/llm.d.ts +95 -0
- package/dist/llm.js +5 -0
- package/dist/markdown.d.ts +4 -0
- package/dist/markdown.js +265 -0
- package/dist/mcp.d.ts +82 -0
- package/dist/mcp.js +325 -0
- package/dist/node.cjs +402 -0
- package/dist/node.d.ts +78 -0
- package/dist/node.js +432 -0
- package/dist/pdf.d.ts +52 -0
- package/dist/pdf.js +77 -0
- package/dist/provider.d.ts +135 -0
- package/dist/provider.js +181 -0
- package/dist/sandbox.d.ts +33 -0
- package/dist/sandbox.js +219 -0
- package/dist/select.d.ts +30 -0
- package/dist/select.js +185 -0
- package/dist/skill-zips.d.ts +28 -0
- package/dist/skill-zips.js +123 -0
- package/dist/skills.d.ts +20 -0
- package/dist/skills.js +111 -0
- package/dist/templates.d.ts +24 -0
- package/dist/templates.js +136 -0
- package/dist/tool.d.ts +28 -0
- package/dist/tool.js +102 -0
- package/dist/types.d.ts +571 -0
- package/dist/types.js +7 -0
- package/dist/ui.cjs +6247 -0
- package/dist/ui.d.ts +6 -0
- package/dist/ui.js +11 -0
- package/dist/vlist.d.ts +80 -0
- package/dist/vlist.js +277 -0
- package/dist/workspace.d.ts +343 -0
- package/dist/workspace.js +1203 -0
- package/dist/zip.d.ts +26 -0
- package/dist/zip.js +204 -0
- package/docs/agent.md +228 -0
- package/docs/chat-ui.md +307 -0
- package/docs/node.md +135 -0
- package/docs/providers.md +176 -0
- package/docs/reference.md +143 -0
- package/docs/skills.md +131 -0
- package/docs/tools.md +254 -0
- package/docs/workspace.md +198 -0
- package/package.json +59 -4
package/dist/zip.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export interface ZipEntry {
|
|
2
|
+
/** Path inside the zip, `/`-separated, no leading slash. */
|
|
3
|
+
name: string;
|
|
4
|
+
size: number;
|
|
5
|
+
compressedSize: number;
|
|
6
|
+
method: number;
|
|
7
|
+
isDir: boolean;
|
|
8
|
+
/** Offset of the local header. */
|
|
9
|
+
offset: number;
|
|
10
|
+
/** CRC-32 of the uncompressed bytes, from the central directory. */
|
|
11
|
+
crc?: number;
|
|
12
|
+
}
|
|
13
|
+
export type Inflate = (compressed: Uint8Array) => Promise<Uint8Array> | Uint8Array;
|
|
14
|
+
export declare const MAX_ZIP_BYTES: number;
|
|
15
|
+
export declare function listZip(bytes: Uint8Array): ZipEntry[];
|
|
16
|
+
export declare function readZipEntry(bytes: Uint8Array, entry: ZipEntry, inflate?: Inflate): Promise<Uint8Array>;
|
|
17
|
+
/**
|
|
18
|
+
* A zip of `entries` (paths relative, `/`-separated; data as bytes or
|
|
19
|
+
* text), deflated when the runtime can, UTF-8 names. For downloads of a
|
|
20
|
+
* directory from the browser; no external dependency.
|
|
21
|
+
*/
|
|
22
|
+
export declare function buildZip(entries: Array<{
|
|
23
|
+
path: string;
|
|
24
|
+
data: Uint8Array | string;
|
|
25
|
+
mtime?: number;
|
|
26
|
+
}>): Promise<Uint8Array>;
|
package/dist/zip.js
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
// A zip reader for skills packs: central directory + per-entry inflate.
|
|
2
|
+
// Stored and deflate entries only; zip64 is refused. Inflation uses the
|
|
3
|
+
// platform's DecompressionStream("deflate-raw") when it exists (browsers,
|
|
4
|
+
// Node ≥ 20.12) or an `inflate` function the caller supplies (tests pass
|
|
5
|
+
// zlib.inflateRawSync).
|
|
6
|
+
export const MAX_ZIP_BYTES = 50 * 1024 * 1024;
|
|
7
|
+
const SIG_EOCD = 0x06054b50;
|
|
8
|
+
const SIG_EOCD64_LOCATOR = 0x07064b50;
|
|
9
|
+
const SIG_CENTRAL = 0x02014b50;
|
|
10
|
+
const SIG_LOCAL = 0x04034b50;
|
|
11
|
+
export function listZip(bytes) {
|
|
12
|
+
if (bytes.byteLength > MAX_ZIP_BYTES)
|
|
13
|
+
throw new Error(`zip larger than ${MAX_ZIP_BYTES} bytes`);
|
|
14
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
15
|
+
// End of central directory: scan back over a possible comment (≤ 64 KB).
|
|
16
|
+
let eocd = -1;
|
|
17
|
+
for (let i = bytes.byteLength - 22; i >= Math.max(0, bytes.byteLength - 22 - 65_535); i--) {
|
|
18
|
+
if (view.getUint32(i, true) === SIG_EOCD) {
|
|
19
|
+
eocd = i;
|
|
20
|
+
break;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
if (eocd < 0)
|
|
24
|
+
throw new Error("not a zip file");
|
|
25
|
+
if (eocd >= 20 && view.getUint32(eocd - 20, true) === SIG_EOCD64_LOCATOR) {
|
|
26
|
+
throw new Error("zip64 archives are not supported");
|
|
27
|
+
}
|
|
28
|
+
const count = view.getUint16(eocd + 10, true);
|
|
29
|
+
const cdSize = view.getUint32(eocd + 12, true);
|
|
30
|
+
const cdOffset = view.getUint32(eocd + 16, true);
|
|
31
|
+
if (count === 0xffff || cdSize === 0xffffffff || cdOffset === 0xffffffff) {
|
|
32
|
+
throw new Error("zip64 archives are not supported");
|
|
33
|
+
}
|
|
34
|
+
const entries = [];
|
|
35
|
+
let p = cdOffset;
|
|
36
|
+
const utf8 = new TextDecoder("utf-8");
|
|
37
|
+
const cp437 = new TextDecoder("latin1");
|
|
38
|
+
for (let n = 0; n < count; n++) {
|
|
39
|
+
if (p + 46 > bytes.byteLength || view.getUint32(p, true) !== SIG_CENTRAL) {
|
|
40
|
+
throw new Error("zip central directory is damaged");
|
|
41
|
+
}
|
|
42
|
+
const flags = view.getUint16(p + 8, true);
|
|
43
|
+
const method = view.getUint16(p + 10, true);
|
|
44
|
+
const compressedSize = view.getUint32(p + 20, true);
|
|
45
|
+
const size = view.getUint32(p + 24, true);
|
|
46
|
+
const nameLen = view.getUint16(p + 28, true);
|
|
47
|
+
const extraLen = view.getUint16(p + 30, true);
|
|
48
|
+
const commentLen = view.getUint16(p + 32, true);
|
|
49
|
+
const offset = view.getUint32(p + 42, true);
|
|
50
|
+
if (compressedSize === 0xffffffff || size === 0xffffffff || offset === 0xffffffff) {
|
|
51
|
+
throw new Error("zip64 archives are not supported");
|
|
52
|
+
}
|
|
53
|
+
const nameBytes = bytes.subarray(p + 46, p + 46 + nameLen);
|
|
54
|
+
const name = ((flags & 0x800) ? utf8 : cp437).decode(nameBytes).replace(/\\/g, "/");
|
|
55
|
+
entries.push({ name, size, compressedSize, method, isDir: name.endsWith("/"), offset, crc: view.getUint32(p + 16, true) });
|
|
56
|
+
p += 46 + nameLen + extraLen + commentLen;
|
|
57
|
+
}
|
|
58
|
+
return entries;
|
|
59
|
+
}
|
|
60
|
+
export async function readZipEntry(bytes, entry, inflate) {
|
|
61
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
62
|
+
const p = entry.offset;
|
|
63
|
+
if (p + 30 > bytes.byteLength || view.getUint32(p, true) !== SIG_LOCAL) {
|
|
64
|
+
throw new Error(`zip entry "${entry.name}" is damaged`);
|
|
65
|
+
}
|
|
66
|
+
const nameLen = view.getUint16(p + 26, true);
|
|
67
|
+
const extraLen = view.getUint16(p + 28, true);
|
|
68
|
+
const start = p + 30 + nameLen + extraLen;
|
|
69
|
+
// Sizes come from the central directory: with a data descriptor
|
|
70
|
+
// (flag bit 3) the local header's are zero.
|
|
71
|
+
if (start + entry.compressedSize > bytes.byteLength)
|
|
72
|
+
throw new Error(`zip entry "${entry.name}" is damaged`);
|
|
73
|
+
const data = bytes.subarray(start, start + entry.compressedSize);
|
|
74
|
+
if (entry.method === 0) {
|
|
75
|
+
if (data.byteLength !== entry.size || (entry.crc !== undefined && crc32(data) !== entry.crc))
|
|
76
|
+
throw new Error(`zip entry "${entry.name}" is damaged`);
|
|
77
|
+
return data;
|
|
78
|
+
}
|
|
79
|
+
if (entry.method !== 8)
|
|
80
|
+
throw new Error(`zip entry "${entry.name}" uses an unsupported compression method (${entry.method})`);
|
|
81
|
+
const out = await (inflate ? inflate(data) : inflateRaw(data));
|
|
82
|
+
if (out.byteLength !== entry.size)
|
|
83
|
+
throw new Error(`zip entry "${entry.name}" inflated to the wrong size`);
|
|
84
|
+
return out;
|
|
85
|
+
}
|
|
86
|
+
async function inflateRaw(data) {
|
|
87
|
+
const DS = globalThis.DecompressionStream;
|
|
88
|
+
if (!DS) {
|
|
89
|
+
throw new Error("this runtime has no DecompressionStream; pass an `inflate` function (e.g. zlib.inflateRawSync)");
|
|
90
|
+
}
|
|
91
|
+
const stream = new Blob([data]).stream().pipeThrough(new DS("deflate-raw"));
|
|
92
|
+
const buf = await new Response(stream).arrayBuffer();
|
|
93
|
+
return new Uint8Array(buf);
|
|
94
|
+
}
|
|
95
|
+
/* ------------------------------------------------------------------ */
|
|
96
|
+
/* Writing */
|
|
97
|
+
/* ------------------------------------------------------------------ */
|
|
98
|
+
let crcTable = null;
|
|
99
|
+
function crc32(data) {
|
|
100
|
+
if (!crcTable) {
|
|
101
|
+
crcTable = new Uint32Array(256);
|
|
102
|
+
for (let n = 0; n < 256; n++) {
|
|
103
|
+
let c = n;
|
|
104
|
+
for (let k = 0; k < 8; k++)
|
|
105
|
+
c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
|
106
|
+
crcTable[n] = c >>> 0;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
let crc = 0xffffffff;
|
|
110
|
+
for (let i = 0; i < data.length; i++)
|
|
111
|
+
crc = crcTable[(crc ^ data[i]) & 0xff] ^ (crc >>> 8);
|
|
112
|
+
return (crc ^ 0xffffffff) >>> 0;
|
|
113
|
+
}
|
|
114
|
+
/** Deflates with the browser's CompressionStream when it has one; else the bytes are stored as they are. */
|
|
115
|
+
async function deflateRaw(data) {
|
|
116
|
+
if (typeof CompressionStream === "undefined" || data.length < 64)
|
|
117
|
+
return { bytes: data, method: 0 };
|
|
118
|
+
try {
|
|
119
|
+
const stream = new Blob([data]).stream().pipeThrough(new CompressionStream("deflate-raw"));
|
|
120
|
+
const out = new Uint8Array(await new Response(stream).arrayBuffer());
|
|
121
|
+
return out.length < data.length ? { bytes: out, method: 8 } : { bytes: data, method: 0 };
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
return { bytes: data, method: 0 };
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
function dosDateTime(ms) {
|
|
128
|
+
const d = new Date(ms);
|
|
129
|
+
const date = ((Math.max(1980, d.getFullYear()) - 1980) << 9) | ((d.getMonth() + 1) << 5) | d.getDate();
|
|
130
|
+
const time = (d.getHours() << 11) | (d.getMinutes() << 5) | (d.getSeconds() >> 1);
|
|
131
|
+
return { date, time };
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* A zip of `entries` (paths relative, `/`-separated; data as bytes or
|
|
135
|
+
* text), deflated when the runtime can, UTF-8 names. For downloads of a
|
|
136
|
+
* directory from the browser; no external dependency.
|
|
137
|
+
*/
|
|
138
|
+
export async function buildZip(entries) {
|
|
139
|
+
// Without zip64 the end record counts entries in 16 bits (0xffff itself means zip64).
|
|
140
|
+
if (entries.length > 0xfffe)
|
|
141
|
+
throw new Error(`too many files for one zip (${entries.length}; at most ${0xfffe})`);
|
|
142
|
+
const enc = new TextEncoder();
|
|
143
|
+
const locals = [];
|
|
144
|
+
const centrals = [];
|
|
145
|
+
let offset = 0;
|
|
146
|
+
for (const e of entries) {
|
|
147
|
+
const name = enc.encode(e.path.replace(/^\/+/, ""));
|
|
148
|
+
const raw = typeof e.data === "string" ? enc.encode(e.data) : e.data;
|
|
149
|
+
const crc = crc32(raw);
|
|
150
|
+
const { bytes, method } = await deflateRaw(raw);
|
|
151
|
+
const { date, time } = dosDateTime(e.mtime ?? Date.now());
|
|
152
|
+
const lh = new DataView(new ArrayBuffer(30));
|
|
153
|
+
lh.setUint32(0, 0x04034b50, true);
|
|
154
|
+
lh.setUint16(4, 20, true);
|
|
155
|
+
lh.setUint16(6, 0x0800, true);
|
|
156
|
+
lh.setUint16(8, method, true);
|
|
157
|
+
lh.setUint16(10, time, true);
|
|
158
|
+
lh.setUint16(12, date, true);
|
|
159
|
+
lh.setUint32(14, crc, true);
|
|
160
|
+
lh.setUint32(18, bytes.length, true);
|
|
161
|
+
lh.setUint32(22, raw.length, true);
|
|
162
|
+
lh.setUint16(26, name.length, true);
|
|
163
|
+
lh.setUint16(28, 0, true);
|
|
164
|
+
const ch = new DataView(new ArrayBuffer(46));
|
|
165
|
+
ch.setUint32(0, 0x02014b50, true);
|
|
166
|
+
ch.setUint16(4, 20, true);
|
|
167
|
+
ch.setUint16(6, 20, true);
|
|
168
|
+
ch.setUint16(8, 0x0800, true);
|
|
169
|
+
ch.setUint16(10, method, true);
|
|
170
|
+
ch.setUint16(12, time, true);
|
|
171
|
+
ch.setUint16(14, date, true);
|
|
172
|
+
ch.setUint32(16, crc, true);
|
|
173
|
+
ch.setUint32(20, bytes.length, true);
|
|
174
|
+
ch.setUint32(24, raw.length, true);
|
|
175
|
+
ch.setUint16(28, name.length, true);
|
|
176
|
+
ch.setUint16(30, 0, true);
|
|
177
|
+
ch.setUint16(32, 0, true);
|
|
178
|
+
ch.setUint16(34, 0, true);
|
|
179
|
+
ch.setUint16(36, 0, true);
|
|
180
|
+
ch.setUint32(38, 0, true);
|
|
181
|
+
ch.setUint32(42, offset, true);
|
|
182
|
+
locals.push(new Uint8Array(lh.buffer), name, bytes);
|
|
183
|
+
centrals.push(new Uint8Array(ch.buffer), name);
|
|
184
|
+
offset += 30 + name.length + bytes.length;
|
|
185
|
+
}
|
|
186
|
+
const cdSize = centrals.reduce((n, b) => n + b.length, 0);
|
|
187
|
+
const end = new DataView(new ArrayBuffer(22));
|
|
188
|
+
end.setUint32(0, 0x06054b50, true);
|
|
189
|
+
end.setUint16(4, 0, true);
|
|
190
|
+
end.setUint16(6, 0, true);
|
|
191
|
+
end.setUint16(8, entries.length, true);
|
|
192
|
+
end.setUint16(10, entries.length, true);
|
|
193
|
+
end.setUint32(12, cdSize, true);
|
|
194
|
+
end.setUint32(16, offset, true);
|
|
195
|
+
end.setUint16(20, 0, true);
|
|
196
|
+
const parts = [...locals, ...centrals, new Uint8Array(end.buffer)];
|
|
197
|
+
const out = new Uint8Array(parts.reduce((n, b) => n + b.length, 0));
|
|
198
|
+
let p = 0;
|
|
199
|
+
for (const b of parts) {
|
|
200
|
+
out.set(b, p);
|
|
201
|
+
p += b.length;
|
|
202
|
+
}
|
|
203
|
+
return out;
|
|
204
|
+
}
|
package/docs/agent.md
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
# The agent
|
|
2
|
+
|
|
3
|
+
`createAgent(provider, options)` returns an `Agent`: it sends the conversation to the model, runs the tools the model calls, feeds the results back, and repeats until the model answers.
|
|
4
|
+
|
|
5
|
+
```js
|
|
6
|
+
import { createAgent, openWorkspace } from "@runappsai/agent";
|
|
7
|
+
|
|
8
|
+
const workspace = await openWorkspace(provider, { id: "notes-app" });
|
|
9
|
+
const agent = createAgent(provider, {
|
|
10
|
+
model: "gpt-4.1",
|
|
11
|
+
appName: "Notes",
|
|
12
|
+
instructions: "You help the user keep their notes tidy.",
|
|
13
|
+
tools: [searchNotes, createNote],
|
|
14
|
+
workspace,
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
const result = await agent.prompt("Summarise this week's meeting notes into /summary.md");
|
|
18
|
+
// result: { runId, reason: "done" | "aborted" | "max_turns" | "error", text, usage, error? }
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Runs and turns
|
|
22
|
+
|
|
23
|
+
One `prompt()` is a **run**. A run is made of **turns**: one model call, then the tool calls it asked for. The run ends when:
|
|
24
|
+
|
|
25
|
+
- the model answers without calling tools — `reason: "done"`, `text` is the answer;
|
|
26
|
+
- `maxTurns` model calls were made (default 100) — `"max_turns"`; `agent.continue()` carries on;
|
|
27
|
+
- you call `agent.abort()` — `"aborted"`;
|
|
28
|
+
- a call failed for good — `"error"`, with `error`.
|
|
29
|
+
|
|
30
|
+
`prompt()` resolves with the result; it does not throw for these. Calling `prompt()` while a run is active queues the message like `followUp()`.
|
|
31
|
+
|
|
32
|
+
Tool calls in a turn run one after another; `parallelTools: true` runs them at once. A tool that throws sends its message back to the model as an error, so the model can fix the call. A reply cut short by `max_tokens` runs none of its tool calls (each is told to re-issue with complete arguments). Rounds of tool calls that bring nothing new — the same results, lines already read, the same errors — get a warning to the model after three in a row and stop the run after six ([Calls that go nowhere](tools.md#calls-that-go-nowhere)).
|
|
33
|
+
|
|
34
|
+
## Talking to a running agent
|
|
35
|
+
|
|
36
|
+
```js
|
|
37
|
+
agent.prompt("Clean up /notes"); // starts a run
|
|
38
|
+
|
|
39
|
+
agent.steer("Skip the archive folder"); // insert into the current run
|
|
40
|
+
agent.followUp("Then email me a summary"); // run after the current run ends
|
|
41
|
+
await agent.abort(); // stop now
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
- **`steer(content)`** — checked after each tool call. The rest of that batch is skipped (each skipped call gets a "skipped" result), and the message joins the next turn, so the model sees it at once. When the agent is idle it starts a run like `prompt()`.
|
|
45
|
+
- **`followUp(content)`** — waits until the current run ends, then starts a run of its own. Returns that run's promise.
|
|
46
|
+
- **`agent.queued`** lists what waits (`{ kind: "steer" | "followUp", message }`); `dequeue(message)` takes one out, `clearQueue()` all of them.
|
|
47
|
+
- **`abort()`** — stops the run; pending tool calls get a "skipped" result so the conversation stays valid, and open dialogs close as dismissed.
|
|
48
|
+
- **`continue()`** — carries on from where the conversation stands, without a new user message: after `max_turns`, or to retry after an error.
|
|
49
|
+
- **`rewind(index)`** — drops the messages from `index` on (`agent.messages[index]` is usually a user message).
|
|
50
|
+
- **`remove(start, end?)`** — deletes messages `start` to `end` (exclusive, default the end) and saves: delete whole turns (a user message up to the next one) so every tool call keeps its result. Listeners get `rewind` with `start`.
|
|
51
|
+
- Each run puts what it spent on the last reply it wrote, as `runUsage` (`{ total_cost, prompt_tokens, completion_tokens, calls }`; compaction included). It is saved with the conversation and never sent to the model.
|
|
52
|
+
|
|
53
|
+
Content is a string or content parts:
|
|
54
|
+
|
|
55
|
+
```js
|
|
56
|
+
agent.prompt([
|
|
57
|
+
{ type: "text", text: "What is in this picture?" },
|
|
58
|
+
{ type: "image_url", image_url: { url: "data:image/png;base64,…" } },
|
|
59
|
+
]);
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## Events
|
|
63
|
+
|
|
64
|
+
`agent.on(name, handler)` returns a function that unsubscribes. `agent.on("*", (name, event) => …)` receives everything.
|
|
65
|
+
|
|
66
|
+
```js
|
|
67
|
+
agent.on("run_start", ({ message }) => drawUserMessage(message)); // message is null for continue()
|
|
68
|
+
agent.on("reasoning_delta", ({ text }) => thinkingBox.textContent = text);
|
|
69
|
+
agent.on("text_delta", ({ text }) => answerBox.innerHTML = markdown(text));
|
|
70
|
+
agent.on("message_reset", () => answerBox.textContent = ""); // a retried call: drop what was shown
|
|
71
|
+
agent.on("tool_call_delta", ({ index, name, arguments: json }) => draftCard(index, name, json)); // arguments as they stream
|
|
72
|
+
agent.on("tool_start", ({ id, name, args }) => addCard(id, name, args));
|
|
73
|
+
agent.on("tool_update", ({ id, content }) => cardProgress(id, content));
|
|
74
|
+
agent.on("tool_end", ({ id, status, result, durationMs }) => finishCard(id, status, result));
|
|
75
|
+
agent.on("run_end", ({ reason, error, usage }) => setBusy(false));
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
| Event | Payload | When |
|
|
79
|
+
|---|---|---|
|
|
80
|
+
| `run_start` | `runId`, `message` | A run starts (`message` null for `continue()`) |
|
|
81
|
+
| `turn_start` / `turn_end` | `runId`, `turn`, (`usage`) | Around each model call and its tools |
|
|
82
|
+
| `request` / `response` | the request sent; timing, finish reason, usage, message; `purpose: "compaction"` for summary calls | Each model call (debug views, counting calls) |
|
|
83
|
+
| `reasoning_delta` | `delta`, `text` | Thinking streams in |
|
|
84
|
+
| `text_delta` | `delta`, `text` | Answer text streams in |
|
|
85
|
+
| `message_reset` | `reason` | A call is retried after it streamed: discard what was shown |
|
|
86
|
+
| `message_end` | `message`, `truncated` | An assistant message is complete |
|
|
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 |
|
|
89
|
+
| `queued` | `kind`, `message` | `steer()` or `followUp()` added to the queue |
|
|
90
|
+
| `steered` | `messages` | Queued steering entered the conversation (draw it now) |
|
|
91
|
+
| `compaction_start` / `compaction` | `runId?`; `summary`, `tokensBefore`, `tokensAfter`, … | Older turns are being / were summarised |
|
|
92
|
+
| `rewind` | `index` | `rewind()` dropped messages (`clear()`: index 0) |
|
|
93
|
+
| `session_saved` | `id` | The session was written to the workspace |
|
|
94
|
+
| `run_end` | `RunResult` | A run ended |
|
|
95
|
+
|
|
96
|
+
`status` of a tool call is `"ok"`, `"error"`, `"declined"` (the user said no), `"blocked"` (`onToolCall` refused it) or `"skipped"` (stopped or steered past).
|
|
97
|
+
|
|
98
|
+
## Permissions and dialogs
|
|
99
|
+
|
|
100
|
+
Tools marked `destructive: true`, or with a `confirm()`, ask the user before they run:
|
|
101
|
+
|
|
102
|
+
```js
|
|
103
|
+
createAgent(provider, {
|
|
104
|
+
tools,
|
|
105
|
+
permissions: "ask", // default: ask for destructive tools
|
|
106
|
+
// permissions: "auto", // never ask
|
|
107
|
+
// permissions: ({ name, args, tool }) => name !== "delete_file" || confirmInMyUI(args),
|
|
108
|
+
onToolCall: ({ name, args }) => (name === "send_email" && !args.to.endsWith("@mycompany.com") ? { block: true, reason: "Only internal addresses." } : undefined),
|
|
109
|
+
});
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
Questions go through the agent's **`ui`**: `confirm`, `select`, `input` and `notify`. The default, `domUI()`, uses plain `<dialog>`s in the page's language and colour scheme; the chat UI answers them inline above its composer. To use your app's own dialogs, pass an object implementing `AgentUI`:
|
|
113
|
+
|
|
114
|
+
```js
|
|
115
|
+
const ui = {
|
|
116
|
+
async confirm(title, message, { ok, cancel, danger, signal } = {}) {
|
|
117
|
+
return myDialogs.confirm({ title, message, ok, cancel, danger, signal }); // true / false
|
|
118
|
+
},
|
|
119
|
+
async select(title, options, { message, multi, allowOther, signal } = {}) {
|
|
120
|
+
return myDialogs.pick({ title, options, message, multi, allowOther, signal }); // string[] or null
|
|
121
|
+
},
|
|
122
|
+
async input(title, { message, placeholder, multiline, initial, signal } = {}) {
|
|
123
|
+
return myDialogs.prompt({ title, message, placeholder, multiline, initial, signal }); // string or null
|
|
124
|
+
},
|
|
125
|
+
notify(message, level = "info") { myToasts.show(message, level); },
|
|
126
|
+
};
|
|
127
|
+
createAgent(provider, { ui });
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
When `signal` aborts (the user stopped the run), close the dialog as dismissed. `nullUI()` answers nothing (every question is declined) — for agents without a person in the loop.
|
|
131
|
+
|
|
132
|
+
## Sessions
|
|
133
|
+
|
|
134
|
+
With a workspace, an agent saves its conversation after every turn, under its `id`, in the workspace's IndexedDB database. An agent created with the id of a saved session continues it:
|
|
135
|
+
|
|
136
|
+
```js
|
|
137
|
+
const agent = createAgent(provider, { id: "chat-42", workspace });
|
|
138
|
+
await agent.ready(); // the saved session is loaded
|
|
139
|
+
console.log(agent.messages.length);
|
|
140
|
+
|
|
141
|
+
const list = await workspace.sessions.list(); // [{ id, title, messages, createdAt, savedAt, … }], newest first
|
|
142
|
+
await workspace.sessions.delete("chat-41");
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
- A session's `title` is the user's first words (what they typed, for a slash command), kept once known.
|
|
146
|
+
- `persist: false` keeps a conversation in memory only.
|
|
147
|
+
- `agent.export()` returns the session (`SessionData`) for storage of your own; `createAgent(provider, { restore: data })` continues it.
|
|
148
|
+
- `agent.lastEnd` says how the last run ended when it did not finish (`{ reason, error?, at }`), and is saved with the session until the next run starts.
|
|
149
|
+
- `agent.clear()` starts the conversation over under the same id — stops a run, drops the queue, messages, title, usage — and saves that; the workspace's files stay. `agent.reset()` forgets the messages in memory only (not while running).
|
|
150
|
+
|
|
151
|
+
## Context and compaction
|
|
152
|
+
|
|
153
|
+
The agent knows the model's window and longest reply from the provider's catalogue (`agent.limits()` → `{ input, output }`; `agent.context()` → `{ used, window }`). Each call asks for the model's longest reply (`maxTokens: "auto"`).
|
|
154
|
+
|
|
155
|
+
The window counts everything a request carries: the system prompt, the tools' schemas and the conversation. When the conversation comes within about 16k tokens of the window, the older turns are **summarised by the model** into a structured checkpoint (goal, constraints, progress, decisions, next steps, critical context) and replaced by it; the newest ~20k tokens stay as they were. The next compaction updates the summary rather than rewriting it; a history too long for one request (after switching to a model with a smaller window, say) is summarised piece by piece, each piece updating the summary so far. A summary call asks for at most 80% of `reserveTokens`, never the model's whole output. If the summary fails, old tool results are shortened and old turns dropped instead. Summary calls appear as `request` / `response` events with `purpose: "compaction"`. Files whose contents were summarised away must be read again before they are changed; files read or written in the kept turns stay read.
|
|
156
|
+
|
|
157
|
+
```js
|
|
158
|
+
createAgent(provider, {
|
|
159
|
+
compaction: { reserveTokens: 16_384, keepRecentTokens: 20_000 }, // tune
|
|
160
|
+
// compaction: false, // only shorten/drop, never summarise
|
|
161
|
+
// compaction: async (plan, agent) => mySummary(plan.toSummarize, plan.previousSummary, plan.focus),
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
await agent.compact("keep every API name we discussed"); // now, with a focus
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
## Pictures and models that see them
|
|
168
|
+
|
|
169
|
+
Some models see pictures, some only read text. The agent asks the catalogue (`input_modalities`, see [Providers](providers.md#telling-the-agent-about-models)) and acts on the answer:
|
|
170
|
+
|
|
171
|
+
| The model in use | |
|
|
172
|
+
|---|---|
|
|
173
|
+
| sees pictures | Pictures in messages and tool results go to it. `read_file` on a PNG, JPEG, GIF or WebP shows the picture (up to 5 MB). Tools marked `vision: true` are offered. |
|
|
174
|
+
| is text-only | No picture is ever sent to it: each one becomes a line saying a picture was there and the model cannot see it (it says so to the user instead of guessing). `vision` tools are not offered. |
|
|
175
|
+
| unknown (no catalogue, or not listed) | Pictures are sent as they are; `vision` tools are not offered. |
|
|
176
|
+
|
|
177
|
+
```js
|
|
178
|
+
await agent.accepts("image"); // true / false / undefined (also "video", "audio")
|
|
179
|
+
await agent.modelInfo(); // the catalogue's entry for the model in use
|
|
180
|
+
createAgent(provider, { vision: true }); // you know better: true offers vision tools, false never sends pictures
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
A tool result's pictures go to the model in a user message after the batch's results (OpenAI's format keeps tool messages to text); only the latest two batches' pictures are sent again on later turns. The chat UI marks the models that see pictures in its model list, and when the current one cannot, keeps attached pictures as files and tells the user.
|
|
184
|
+
|
|
185
|
+
## Memory and project instructions
|
|
186
|
+
|
|
187
|
+
With a workspace that has the file tools, two files mean something:
|
|
188
|
+
|
|
189
|
+
- **`/AGENTS.md`** — your instructions for the project, added to the system prompt.
|
|
190
|
+
- **`/memory/notes.md`** — the agent's own notes. The prompt tells it to append a line there to remember something for later, and shows the notes at the start of every conversation.
|
|
191
|
+
|
|
192
|
+
Both live in the workspace's directory: shared by every conversation that uses the same directory. When the directory is the user's own project — their app's files, a folder on disk — the agent should not put notes of its own there, nor take instructions from a file someone else wrote: `memoryFile: false` and `instructionsFile: false` turn them off, or name other paths (`memoryFile: "/.notes/agent.md"`).
|
|
193
|
+
|
|
194
|
+
## Options
|
|
195
|
+
|
|
196
|
+
| Option | Default | |
|
|
197
|
+
|---|---|---|
|
|
198
|
+
| `model` | provider's default | Model id. |
|
|
199
|
+
| `instructions` | | Your system instructions (a function is re-read every turn). |
|
|
200
|
+
| `appName` | | Your app's name, used in the system prompt. |
|
|
201
|
+
| `tools` | `[]` | Tools from `defineTool`. |
|
|
202
|
+
| `workspace` | `null` | A `Workspace`: files, skills, sessions. |
|
|
203
|
+
| `fileTools` | all | `false`, or a subset: `["read_file", "list_files"]` for a read-only agent. |
|
|
204
|
+
| `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)). |
|
|
205
|
+
| `sandbox` | on | The `run_js` tool; `false` removes it, `{ timeoutMs, network }` configures it. |
|
|
206
|
+
| `askUser` | on | The `ask_user` tool. |
|
|
207
|
+
| `ui` | `domUI()` | Dialogs (`AgentUI`). |
|
|
208
|
+
| `permissions` | `"ask"` | `"ask"`, `"auto"`, or a function per call. |
|
|
209
|
+
| `onToolCall` | | Return `{ block: true, reason }` to refuse a call. |
|
|
210
|
+
| `maxTurns` | `100` | Model calls per run. |
|
|
211
|
+
| `maxTokens` | `"auto"` | `max_tokens` per call: the model's maximum, or a number. |
|
|
212
|
+
| `maxInputTokens` | `"auto"` | The context budget: the model's window, or a number that caps it (never above the window the catalogue gives). |
|
|
213
|
+
| `parallelTools` | `false` | Run a turn's tool calls at once. |
|
|
214
|
+
| `keepTurns` | `4` | Turns kept intact when old turns have to be dropped. |
|
|
215
|
+
| `vision` | from the catalogue | Whether the model sees pictures; see [Pictures](#pictures-and-models-that-see-them). |
|
|
216
|
+
| `memoryFile` | `"/memory/notes.md"` | The memory notes file; `false` for none. |
|
|
217
|
+
| `instructionsFile` | `"/AGENTS.md"` | The project instructions file; `false` for none. |
|
|
218
|
+
| `loopGuard` | `{ warn: 3, stop: 6 }` | Rounds without anything new before the model is warned / the run stops; `false` turns it off. |
|
|
219
|
+
| `temperature`, `top_p` | | Sent as is. |
|
|
220
|
+
| `extra` | | Any other request field (`reasoning_effort`, …). |
|
|
221
|
+
| `compaction` | on | See above. |
|
|
222
|
+
| `id` | random | Session id. |
|
|
223
|
+
| `persist` | `true` with a workspace | Save after every turn. |
|
|
224
|
+
| `restore` | | A `SessionData` to continue. |
|
|
225
|
+
| `prompt` | | RunApps private prompt reference (`{ id, vars }`), sent with every request. |
|
|
226
|
+
| `serverTools` | | RunApps only: `["web_search", "web_fetch"]` run by the gateway, for an agent with no tools of its own. |
|
|
227
|
+
|
|
228
|
+
Change settings on a live agent with `agent.configure({ model, maxTurns, maxTokens, permissions, reasoningEffort })`; `agent.settings` reads them back.
|