@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.
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 +4099 -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 +6247 -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,339 @@
1
+ // The built-in file tools over a Workspace: list, read (with line
2
+ // ranges), write, edit (exact replacement), delete, move, copy, search. Their
3
+ // descriptions are what the model reads, so they say what each does and
4
+ // what comes back.
5
+ import { defineTool } from "./tool.js";
6
+ import { normalizePath } from "./workspace.js";
7
+ import { fileGuard, PartialReadError } from "./file-guard.js";
8
+ const MAX_LIST = 500;
9
+ const MAX_READ_LINES = 2000;
10
+ const MAX_READ_BYTES = 50 * 1024;
11
+ const MAX_SEARCH_HITS = 100;
12
+ const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
13
+ const IMAGE_TYPES = { "image/png": true, "image/jpeg": true, "image/gif": true, "image/webp": true };
14
+ const IMAGE_EXT = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp" };
15
+ function base64(bytes) {
16
+ let s = "";
17
+ for (let i = 0; i < bytes.length; i += 0x8000)
18
+ s += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
19
+ return btoa(s);
20
+ }
21
+ export function fileTools(ws, opts = {}) {
22
+ const files = opts.guard ?? fileGuard(ws, { enabled: opts.readBeforeWrite !== false });
23
+ const guard = files.enabled;
24
+ return [
25
+ defineTool({
26
+ name: "list_files",
27
+ description: `List the files under a folder of the workspace (recursive), one per line with the size in bytes. Output is truncated to 500 entries. Start at / to see everything; ${ws.skillsDir} holds the skills.`,
28
+ readOnly: true,
29
+ parameters: {
30
+ type: "object",
31
+ properties: { path: { type: "string", description: "Folder to list. Default /" } },
32
+ additionalProperties: false,
33
+ },
34
+ async execute({ path }) {
35
+ const files = await ws.list(path || "/");
36
+ if (!files.length)
37
+ return `No files under ${normalizePath(path || "/")}.`;
38
+ const lines = files.slice(0, MAX_LIST).map((f) => `${f.path} (${f.size} B)`);
39
+ if (files.length > MAX_LIST)
40
+ lines.push(`\n[${MAX_LIST} entries limit reached (${files.length} in all). List a sub-folder.]`);
41
+ return lines.join("\n");
42
+ },
43
+ }),
44
+ defineTool({
45
+ name: "read_file",
46
+ description: "Read the contents of a text file in the workspace; a PDF is read as the text of its pages, each under a `--- page N ---` line; a picture (PNG, JPEG, GIF, WebP) is shown to you when the model can see pictures. Output is truncated to 2000 lines or 50KB (whichever is hit first). Use offset/limit for large files; when you need the full file, continue with offset until complete. Reading a folder lists it.",
47
+ readOnly: true,
48
+ parameters: {
49
+ type: "object",
50
+ properties: {
51
+ path: { type: "string", description: "Absolute path in the workspace" },
52
+ offset: { type: "integer", minimum: 1, description: "Line number to start reading from (1-indexed)" },
53
+ limit: { type: "integer", minimum: 1, description: "Maximum number of lines to read" },
54
+ },
55
+ required: ["path"],
56
+ additionalProperties: false,
57
+ },
58
+ async execute({ path, offset, limit }, ctx) {
59
+ if (await ws.isFolder(path)) {
60
+ const files = await ws.list(path);
61
+ return `${normalizePath(path)} is a folder with ${files.length} file${files.length === 1 ? "" : "s"}:\n` +
62
+ files.slice(0, MAX_LIST).map((f) => `${f.path} (${f.size} B)`).join("\n");
63
+ }
64
+ // A picture, to a model that sees pictures: shown, not described.
65
+ const st0 = await ws.stat(path);
66
+ const pictureType = st0 && IMAGE_TYPES[(st0.contentType ?? "").split(";")[0].trim()] ? st0.contentType.split(";")[0].trim() : IMAGE_EXT[/\.([a-z0-9]+)$/i.exec(path)?.[1]?.toLowerCase() ?? ""];
67
+ if (st0 && pictureType && (await ctx.agent?.accepts("image")) === true) {
68
+ if (st0.size > MAX_IMAGE_BYTES)
69
+ return `${normalizePath(path)} is a picture of ${st0.size} bytes, more than the ${MAX_IMAGE_BYTES / 1024 / 1024} MB that can be shown; describe what you need from it to the user instead.`;
70
+ const { data } = await ws.read(path);
71
+ const bytes = typeof data === "string" ? new TextEncoder().encode(data) : data;
72
+ await files.saw(normalizePath(path));
73
+ return [
74
+ { type: "text", text: `${normalizePath(path)} (${pictureType}, ${bytes.byteLength} bytes):` },
75
+ { type: "image_url", image_url: { url: `data:${pictureType};base64,${base64(bytes)}` } },
76
+ ];
77
+ }
78
+ let doc;
79
+ try {
80
+ doc = await ws.readAsText(path);
81
+ }
82
+ catch (err) {
83
+ const st = await ws.stat(path);
84
+ if (st && /\.pdf$/i.test(path))
85
+ return `Could not read the PDF ${normalizePath(path)}: ${err.message}`;
86
+ throw err;
87
+ }
88
+ if (!doc) {
89
+ await files.saw(normalizePath(path));
90
+ const st = await ws.stat(path);
91
+ const blind = pictureType && (await ctx.agent?.accepts("image")) === false ? " The model in use cannot view pictures." : "";
92
+ return `${normalizePath(path)} is a binary file (${st?.contentType ?? "unknown type"}, ${st?.size ?? 0} bytes).${blind}`;
93
+ }
94
+ const text = doc.text;
95
+ const lines = text.split("\n");
96
+ const total = lines.length;
97
+ const start = Math.max(1, offset ?? 1);
98
+ if (start > total) {
99
+ await files.saw(normalizePath(path), { start: total + 1, end: total, total });
100
+ return `Offset ${start} is beyond end of file (${total} lines total)`;
101
+ }
102
+ const want = limit !== undefined ? Math.min(limit, MAX_READ_LINES) : MAX_READ_LINES;
103
+ const out = [];
104
+ let bytes = 0;
105
+ let end = start - 1;
106
+ for (let i = start - 1; i < total && out.length < want; i++) {
107
+ const b = new TextEncoder().encode(lines[i]).byteLength + 1;
108
+ if (bytes + b > MAX_READ_BYTES && out.length > 0)
109
+ break;
110
+ out.push(lines[i]);
111
+ bytes += b;
112
+ end = i + 1;
113
+ }
114
+ // What it has now seen of the file (a PDF's text is not its content: no fingerprint from it).
115
+ const fresh = await files.saw(normalizePath(path), { start, end, total, text: doc.kind === "text" ? text : undefined });
116
+ // Lines it already had (another limit, an overlapping range) are not progress.
117
+ if (fresh !== undefined)
118
+ ctx.progress?.(fresh);
119
+ let notice = "";
120
+ if (end < total) {
121
+ const next = end + 1;
122
+ if (bytes >= MAX_READ_BYTES || (limit === undefined && out.length >= MAX_READ_LINES))
123
+ notice = `\n\n[Showing lines ${start}-${end} of ${total}${bytes >= MAX_READ_BYTES ? " (50.0KB limit)" : ""}. Use offset=${next} to continue.]`;
124
+ else
125
+ notice = `\n\n[${total - end} more lines in file. Use offset=${next} to continue.]`;
126
+ }
127
+ return out.join("\n") + notice;
128
+ },
129
+ }),
130
+ defineTool({
131
+ name: "write_file",
132
+ description: "Create or overwrite a text file in the workspace with the given content. Folders are implied by the path. Prefer edit_file for small changes to an existing file." +
133
+ (guard ? " To overwrite an existing file, read it with read_file first; if it changed since you read it, read it again. Only when the user asked for the file to be rewritten from scratch, keeping nothing of it, pass replace: true to overwrite it without reading it." : ""),
134
+ parameters: {
135
+ type: "object",
136
+ properties: {
137
+ path: { type: "string" },
138
+ content: { type: "string" },
139
+ ...(guard ? { replace: { type: "boolean", description: "Overwrite an existing file without reading it first. Only when the user asked to rewrite it from scratch and keep nothing of it; never to skip reading a file whose content you are changing." } } : {}),
140
+ },
141
+ required: ["path", "content"],
142
+ additionalProperties: false,
143
+ },
144
+ async execute({ path, content, replace }, ctx) {
145
+ const p = normalizePath(path);
146
+ const existed = await ws.exists(p);
147
+ // What a replace threw away unread, said in the result (and so in the chat's tool card).
148
+ let discarded = "";
149
+ if (existed && replace === true && guard) {
150
+ const known = await files.known(p);
151
+ if (known !== "all") {
152
+ const old = await ws.readAsText(p).catch(() => null);
153
+ const n = old?.kind === "text" ? old.text.split("\n").length : 0;
154
+ const size = n ? ` (${n} line${n === 1 ? "" : "s"})` : "";
155
+ discarded = known === "part" ? ` Its previous content${size} was replaced, including the part you had not read.` : ` Its previous content${size} was replaced without being read.`;
156
+ }
157
+ }
158
+ else if (existed) {
159
+ try {
160
+ await files.check(p, "overwrite");
161
+ }
162
+ catch (err) {
163
+ if (!(err instanceof PartialReadError))
164
+ throw err;
165
+ // Read only in part: show the rest now (it counts as read), so the next write knows the whole file.
166
+ const doc = await ws.readAsText(p).catch(() => null);
167
+ if (doc?.kind !== "text")
168
+ throw err;
169
+ const lines = doc.text.split("\n"), total = lines.length, start = err.coveredTo + 1;
170
+ const out = [];
171
+ let bytes = 0, end = err.coveredTo;
172
+ for (let i = start - 1; i < total && out.length < MAX_READ_LINES; i++) {
173
+ const b = new TextEncoder().encode(lines[i]).byteLength + 1;
174
+ if (bytes + b > MAX_READ_BYTES && out.length > 0)
175
+ break;
176
+ out.push(lines[i]);
177
+ bytes += b;
178
+ end = i + 1;
179
+ }
180
+ const fresh = await files.saw(p, { start, end, total, text: doc.text });
181
+ if (fresh !== undefined)
182
+ ctx.progress?.(fresh);
183
+ const more = end < total ? ` Lines ${end + 1}-${total} are still unread: read them with read_file offset=${end + 1} before overwriting.` : "";
184
+ throw new Error(`${p} was not overwritten: you had read only lines 1-${err.coveredTo} of its ${total}. Here are lines ${start}-${end}, which now count as read.${more} Make sure your new content keeps what it should, then call write_file again, or change the file with edit_file.\n\n${out.join("\n")}`);
185
+ }
186
+ }
187
+ await ws.write(p, content);
188
+ await files.wrote(p);
189
+ return `${existed ? (discarded ? "Replaced" : "Updated") : "Created"} ${p} (${new TextEncoder().encode(content).byteLength} bytes).${discarded}`;
190
+ },
191
+ }),
192
+ defineTool({
193
+ name: "edit_file",
194
+ description: "Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby lines, merge them into one edit instead of emitting overlapping edits. Do not include large unchanged regions just to connect distant changes." +
195
+ (guard ? " Read the file with read_file before editing it; if it changed since you read it (the user may edit files while you work), read it again." : ""),
196
+ parameters: {
197
+ type: "object",
198
+ properties: {
199
+ path: { type: "string", description: "Absolute path in the workspace" },
200
+ edits: {
201
+ type: "array",
202
+ minItems: 1,
203
+ description: "One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits.",
204
+ items: {
205
+ type: "object",
206
+ properties: {
207
+ oldText: { type: "string", description: "Exact text for one targeted replacement. It must be unique in the original file." },
208
+ newText: { type: "string", description: "Replacement text for this targeted edit." },
209
+ },
210
+ required: ["oldText", "newText"],
211
+ additionalProperties: false,
212
+ },
213
+ },
214
+ oldText: { type: "string", description: "Shorthand for a single edit" },
215
+ newText: { type: "string" },
216
+ },
217
+ required: ["path"],
218
+ additionalProperties: false,
219
+ },
220
+ guidelines: [
221
+ "Use edit_file for precise changes (oldText must match exactly); when changing several places in one file, use one edit_file call with several entries in edits[].",
222
+ "Keep oldText as small as possible while still being unique in the file.",
223
+ ],
224
+ async execute(args) {
225
+ const p = normalizePath(args.path);
226
+ // The schema allows `edits` (an array) and the `oldText`/`newText` shorthand; nothing else gets this far.
227
+ const edits = Array.isArray(args.edits) ? [...args.edits] : [];
228
+ if (args.oldText !== undefined)
229
+ edits.push({ oldText: args.oldText, newText: args.newText ?? "" });
230
+ await files.check(p, "edit");
231
+ // The workspace applies them: a mount with its own edit() gets them as they are, anything else is read, edited and written back.
232
+ await ws.edit(p, edits);
233
+ await files.edited(p);
234
+ return `Successfully replaced ${edits.length} block(s) in ${p}.`;
235
+ },
236
+ }),
237
+ defineTool({
238
+ name: "delete_file",
239
+ description: "Delete a file from the workspace.",
240
+ parameters: {
241
+ type: "object",
242
+ properties: { path: { type: "string" } },
243
+ required: ["path"],
244
+ additionalProperties: false,
245
+ },
246
+ destructive: true,
247
+ confirm: ({ path }) => `Delete ${normalizePath(path)}?`,
248
+ async execute({ path }) {
249
+ const p = normalizePath(path);
250
+ await files.check(p, "delete");
251
+ await ws.delete(p);
252
+ files.forget(p);
253
+ return `Deleted ${p}.`;
254
+ },
255
+ }),
256
+ ...["move_file", "copy_file"].map((name) => defineTool({
257
+ name,
258
+ description: name === "move_file"
259
+ ? "Move or rename a file. The destination must not exist yet. References to the old path in other files are not changed: update them with edit_file."
260
+ : "Copy a file to a new path. The destination must not exist yet.",
261
+ parameters: {
262
+ type: "object",
263
+ properties: { from: { type: "string", description: "Existing file" }, to: { type: "string", description: "New path" } },
264
+ required: ["from", "to"],
265
+ additionalProperties: false,
266
+ },
267
+ async execute({ from, to }) {
268
+ const a = normalizePath(from), b = normalizePath(to);
269
+ if (a === b)
270
+ throw new Error("The source and the destination are the same path.");
271
+ if (!(await ws.exists(a)) || (await ws.isFolder(a)))
272
+ throw new Error(`No such file: ${a}`);
273
+ if (await ws.exists(b))
274
+ throw new Error(`${b} already exists. Choose another path, or delete it first.`);
275
+ if (name === "move_file" && ws.isReadOnly(a))
276
+ throw new Error(`${a} is read-only.`);
277
+ if (name === "move_file")
278
+ await files.check(a, "delete");
279
+ const { data, contentType } = await ws.read(a);
280
+ await ws.write(b, data, contentType);
281
+ await files.copied(a, b);
282
+ if (name === "move_file") {
283
+ await ws.delete(a);
284
+ files.forget(a);
285
+ }
286
+ return `${name === "move_file" ? "Moved" : "Copied"} ${a} to ${b}.`;
287
+ },
288
+ })),
289
+ defineTool({
290
+ name: "search_files",
291
+ description: "Search the text files of the workspace for a pattern (a literal string, or a regular expression with regex: true). Returns matching lines as path:line: text, at most 100; long lines are cut to 200 chars.",
292
+ readOnly: true,
293
+ parameters: {
294
+ type: "object",
295
+ properties: {
296
+ query: { type: "string", minLength: 1 },
297
+ path: { type: "string", description: "Folder to search. Default /" },
298
+ regex: { type: "boolean" },
299
+ },
300
+ required: ["query"],
301
+ additionalProperties: false,
302
+ },
303
+ async execute({ query, path, regex }, ctx) {
304
+ let re;
305
+ try {
306
+ re = regex ? new RegExp(query, "i") : new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "i");
307
+ }
308
+ catch (e) {
309
+ throw new Error(`Invalid regular expression: ${e.message}`);
310
+ }
311
+ const hits = [];
312
+ let scanned = 0;
313
+ for (const f of await ws.list(path || "/")) {
314
+ ctx.signal.throwIfAborted();
315
+ if (f.size > 2_000_000)
316
+ continue;
317
+ let text;
318
+ try {
319
+ text = await ws.readText(f.path);
320
+ }
321
+ catch {
322
+ continue;
323
+ }
324
+ scanned++;
325
+ const lines = text.split("\n");
326
+ for (let i = 0; i < lines.length && hits.length < MAX_SEARCH_HITS; i++) {
327
+ if (re.test(lines[i]))
328
+ hits.push(`${f.path}:${i + 1}: ${lines[i].trim().slice(0, 200)}`);
329
+ }
330
+ if (hits.length >= MAX_SEARCH_HITS)
331
+ break;
332
+ }
333
+ if (!hits.length)
334
+ return `No matches found (${scanned} text files searched).`;
335
+ return hits.join("\n") + (hits.length >= MAX_SEARCH_HITS ? `\n\n[${MAX_SEARCH_HITS} matches limit reached. Refine the pattern or search a sub-folder.]` : "");
336
+ },
337
+ }),
338
+ ];
339
+ }
@@ -0,0 +1,60 @@
1
+ import { type Workspace } from "./index.js";
2
+ export interface FilesStrings {
3
+ files: string;
4
+ upload: string;
5
+ newFile: string;
6
+ refresh: string;
7
+ close: string;
8
+ save: string;
9
+ download: string;
10
+ delete: string;
11
+ cancel: string;
12
+ ok: string;
13
+ confirmDeleteFile: string;
14
+ newFilePath: string;
15
+ noPreview: string;
16
+ changedByAgent: string;
17
+ noFiles: string;
18
+ discard: string;
19
+ saved: string;
20
+ downloadZip: string;
21
+ zipping: string;
22
+ wrap: string;
23
+ preview: string;
24
+ edit: string;
25
+ tooBig: string;
26
+ conflict: string;
27
+ readOnly: string;
28
+ autoSaved: string;
29
+ }
30
+ export interface FilesPanelOptions {
31
+ t: FilesStrings;
32
+ /** The element dialogs are placed over. */
33
+ root: HTMLElement;
34
+ /** Where the editor goes when a file is open: it covers this element (the transcript and composer) until closed. */
35
+ editorHost: HTMLElement;
36
+ notify(message: string, level?: "info" | "warning" | "error"): void;
37
+ /** Called after the panel changed the directory (a save, upload or delete). */
38
+ onChange?: () => void;
39
+ /** Called when the panel shows or hides, from wherever (its own close button, a link that opens a file). */
40
+ onShow?: (visible: boolean) => void;
41
+ }
42
+ export interface FilesPanel {
43
+ readonly el: HTMLElement;
44
+ readonly visible: boolean;
45
+ /** Shows the panel; with a path, opens that file. */
46
+ open(path?: string): Promise<void>;
47
+ close(): Promise<void>;
48
+ toggle(): Promise<void>;
49
+ setWorkspace(ws: Workspace | null): void;
50
+ refresh(): Promise<void>;
51
+ /** The agent wrote or deleted a path: marks it and reloads it if open. */
52
+ changed(path: string): void;
53
+ download(path: string): Promise<void>;
54
+ /** A folder as a zip, built in the browser. */
55
+ downloadFolder(path: string): Promise<void>;
56
+ dispose(): void;
57
+ }
58
+ /** A free path for `name` in `dir` (`-2`, `-3`… when taken). */
59
+ export declare function freePath(ws: Workspace, dir: string, name: string): Promise<string>;
60
+ export declare function filesPanel(opts: FilesPanelOptions): FilesPanel;