@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
package/dist/mcp.d.ts ADDED
@@ -0,0 +1,82 @@
1
+ import type { JSONSchema, Tool } from "./types.js";
2
+ export interface MCPOptions {
3
+ /** Sent as `Authorization: Bearer <token>`. */
4
+ token?: string;
5
+ /** More request headers. */
6
+ headers?: Record<string, string>;
7
+ /**
8
+ * Prefix of the tool names the model sees (`<prefix>__<tool>`). Default:
9
+ * the server's name. Names are cut to the 64 characters a tool name may have.
10
+ */
11
+ prefix?: string;
12
+ /**
13
+ * When the user is asked before a call (under permissions "ask"):
14
+ * `"always"` (the default), `"unless-read-only"` (tools the server marks
15
+ * `readOnlyHint` run without asking) or `"never"`.
16
+ */
17
+ confirm?: "always" | "unless-read-only" | "never";
18
+ /** What the server is called in tool descriptions and confirmations (default: the name it gives itself). */
19
+ name?: string;
20
+ /** Pass pictures a tool returns on to the model (default false: they are named, not sent). */
21
+ images?: boolean;
22
+ /** Longest a request may take, in ms (default 60 000). */
23
+ timeoutMs?: number;
24
+ /** Most tools taken from the server (default 64). */
25
+ maxTools?: number;
26
+ /** Longest tool result sent to the model, in characters (default 32 000). */
27
+ maxResultChars?: number;
28
+ /** Your own fetch (a proxy, tests). */
29
+ fetch?: typeof fetch;
30
+ /** The client name the server is told (default "runapps-agent"). */
31
+ clientName?: string;
32
+ signal?: AbortSignal;
33
+ }
34
+ /** One tool as the server described it. */
35
+ export interface MCPToolInfo {
36
+ name: string;
37
+ title?: string;
38
+ description?: string;
39
+ inputSchema: JSONSchema;
40
+ annotations?: {
41
+ title?: string;
42
+ readOnlyHint?: boolean;
43
+ destructiveHint?: boolean;
44
+ idempotentHint?: boolean;
45
+ openWorldHint?: boolean;
46
+ };
47
+ }
48
+ export interface MCPConnection {
49
+ /** The server's tools, ready for `createAgent({ tools })`. */
50
+ readonly tools: Tool[];
51
+ /** What the server said about each tool. */
52
+ readonly serverTools: readonly MCPToolInfo[];
53
+ /** The server's name and version, as it gave them. */
54
+ readonly server: {
55
+ name: string;
56
+ version?: string;
57
+ title?: string;
58
+ };
59
+ /** Instructions the server gave for using it, if any (worth adding to the agent's instructions). */
60
+ readonly instructions?: string;
61
+ /** Read the tool list again (after the server says it changed). */
62
+ refresh(signal?: AbortSignal): Promise<Tool[]>;
63
+ /** Ends the session on the server; the tools stop working. */
64
+ close(): Promise<void>;
65
+ }
66
+ /** An MCP server's error, or a failed request to it. Never carries the token or the response's headers. */
67
+ export declare class MCPError extends Error {
68
+ readonly status?: number | undefined;
69
+ readonly code?: number | undefined;
70
+ constructor(message: string, status?: number | undefined, code?: number | undefined);
71
+ }
72
+ /**
73
+ * Connects to an MCP server (Streamable HTTP) and returns its tools.
74
+ *
75
+ * ```js
76
+ * const github = await connectMCP("https://mcp.example.com/mcp", { token });
77
+ * const agent = createAgent(provider, { tools: github.tools });
78
+ * // later
79
+ * await github.close();
80
+ * ```
81
+ */
82
+ export declare function connectMCP(url: string | URL, opts?: MCPOptions): Promise<MCPConnection>;
package/dist/mcp.js ADDED
@@ -0,0 +1,325 @@
1
+ // MCP tools: connect to a Model Context Protocol server over Streamable
2
+ // HTTP and hand its tools to an agent. Plain fetch, no SDK: initialize,
3
+ // tools/list (paginated), tools/call, the session id header, answers that
4
+ // come as JSON or as an event stream, progress notifications, cancellation
5
+ // on abort, and DELETE to end the session.
6
+ import { sseData } from "./provider.js";
7
+ import { defineTool } from "./tool.js";
8
+ const PROTOCOL_VERSION = "2025-06-18";
9
+ /** An MCP server's error, or a failed request to it. Never carries the token or the response's headers. */
10
+ export class MCPError extends Error {
11
+ status;
12
+ code;
13
+ constructor(message, status, code) {
14
+ super(message);
15
+ this.status = status;
16
+ this.code = code;
17
+ this.name = "MCPError";
18
+ }
19
+ }
20
+ /**
21
+ * Connects to an MCP server (Streamable HTTP) and returns its tools.
22
+ *
23
+ * ```js
24
+ * const github = await connectMCP("https://mcp.example.com/mcp", { token });
25
+ * const agent = createAgent(provider, { tools: github.tools });
26
+ * // later
27
+ * await github.close();
28
+ * ```
29
+ */
30
+ export async function connectMCP(url, opts = {}) {
31
+ opts.signal?.throwIfAborted();
32
+ const endpoint = new URL(url);
33
+ if (endpoint.protocol !== "https:" && endpoint.protocol !== "http:")
34
+ throw new MCPError("An MCP endpoint is an http(s) URL.");
35
+ const doFetch = opts.fetch ?? globalThis.fetch.bind(globalThis);
36
+ const timeoutMs = opts.timeoutMs ?? 60_000;
37
+ let session;
38
+ let protocol;
39
+ let nextId = 1;
40
+ let closed = false;
41
+ // opts.signal cancels connecting only: once connected, the connection lives until close().
42
+ let connecting = opts.signal;
43
+ const headers = (json) => ({
44
+ ...(opts.headers ?? {}),
45
+ ...(json ? { "Content-Type": "application/json", Accept: "application/json, text/event-stream" } : {}),
46
+ ...(opts.token ? { Authorization: `Bearer ${opts.token}` } : {}),
47
+ ...(session ? { "Mcp-Session-Id": session } : {}),
48
+ ...(protocol ? { "MCP-Protocol-Version": protocol } : {}),
49
+ });
50
+ const post = (body, signal) => doFetch(endpoint, {
51
+ method: "POST",
52
+ headers: headers(true),
53
+ body: JSON.stringify(body),
54
+ signal,
55
+ redirect: "error",
56
+ credentials: "omit",
57
+ });
58
+ /** Answers a request the server makes of us: ping, everything else "not supported". */
59
+ const answerServer = (m) => {
60
+ const reply = m.method === "ping"
61
+ ? { jsonrpc: "2.0", id: m.id, result: {} }
62
+ : { jsonrpc: "2.0", id: m.id, error: { code: -32601, message: `${m.method} is not supported by this client` } };
63
+ void post(reply, AbortSignal.timeout(timeoutMs)).then((r) => r.body?.cancel()).catch(() => undefined);
64
+ };
65
+ /** One request: its result, reading through notifications (progress) and server requests on the way. */
66
+ const request = async (method, params, signal, onProgress, retried = false) => {
67
+ if (closed)
68
+ throw new MCPError("The MCP connection is closed.");
69
+ const id = nextId++;
70
+ const timeout = AbortSignal.timeout(timeoutMs);
71
+ const combined = anySignal([timeout, ...(signal ? [signal] : []), ...(connecting ? [connecting] : [])]);
72
+ const body = { jsonrpc: "2.0", id, method, ...(params ? { params: onProgress ? { ...params, _meta: { progressToken: id } } : params } : {}) };
73
+ const cancel = () => {
74
+ // Tell the server to stop (a request already running may still have its effect).
75
+ if (method !== "initialize")
76
+ void post({ jsonrpc: "2.0", method: "notifications/cancelled", params: { requestId: id, reason: "The user stopped it." } }, AbortSignal.timeout(5000)).then((r) => r.body?.cancel()).catch(() => undefined);
77
+ };
78
+ signal?.addEventListener("abort", cancel, { once: true });
79
+ try {
80
+ let res;
81
+ try {
82
+ res = await post(body, combined);
83
+ }
84
+ catch (err) {
85
+ signal?.throwIfAborted();
86
+ if (timeout.aborted)
87
+ throw new MCPError(`${method} timed out after ${Math.round(timeoutMs / 1000)} s.`);
88
+ throw new MCPError(`Could not reach the MCP server (${err.message}). Check the address, its CORS settings and your network.`);
89
+ }
90
+ if (res.status === 404 && session && !retried && method !== "initialize") {
91
+ // The server forgot the session: start a new one and ask again.
92
+ await res.body?.cancel();
93
+ session = undefined;
94
+ await initialize(signal);
95
+ return request(method, params, signal, onProgress, true);
96
+ }
97
+ if (!res.ok) {
98
+ await res.body?.cancel();
99
+ throw new MCPError(`The MCP server answered ${method} with HTTP ${res.status}${res.status === 401 || res.status === 403 ? " (check the token)" : ""}.`, res.status);
100
+ }
101
+ const sid = res.headers.get("mcp-session-id");
102
+ if (sid)
103
+ session = sid;
104
+ const handle = (m) => {
105
+ if (m.id === id && (m.result || m.error)) {
106
+ if (m.error)
107
+ throw new MCPError(`${method}: ${m.error.message}`, undefined, m.error.code);
108
+ return m.result ?? {};
109
+ }
110
+ if (m.method && m.id !== undefined)
111
+ answerServer(m);
112
+ else if (m.method === "notifications/progress" && m.params?.progressToken === id && onProgress) {
113
+ const p = m.params;
114
+ onProgress(p.message ?? (p.total ? `${p.progress ?? 0} / ${p.total}` : String(p.progress ?? "")));
115
+ }
116
+ return undefined;
117
+ };
118
+ const type = res.headers.get("content-type") ?? "";
119
+ if (type.includes("text/event-stream") && res.body) {
120
+ for await (const data of sseData(res.body, combined)) {
121
+ let m;
122
+ try {
123
+ m = JSON.parse(data);
124
+ }
125
+ catch {
126
+ continue;
127
+ }
128
+ for (const one of Array.isArray(m) ? m : [m]) {
129
+ const result = handle(one);
130
+ if (result) {
131
+ void res.body.cancel().catch(() => undefined);
132
+ return result;
133
+ }
134
+ }
135
+ }
136
+ signal?.throwIfAborted();
137
+ if (timeout.aborted)
138
+ throw new MCPError(`${method} timed out after ${Math.round(timeoutMs / 1000)} s.`);
139
+ throw new MCPError(`The MCP server ended the stream without answering ${method}.`);
140
+ }
141
+ let parsed;
142
+ try {
143
+ parsed = await res.json();
144
+ }
145
+ catch {
146
+ throw new MCPError(`The MCP server's answer to ${method} is not JSON.`);
147
+ }
148
+ for (const one of Array.isArray(parsed) ? parsed : [parsed]) {
149
+ const result = handle(one);
150
+ if (result)
151
+ return result;
152
+ }
153
+ throw new MCPError(`The MCP server did not answer ${method}.`);
154
+ }
155
+ finally {
156
+ signal?.removeEventListener("abort", cancel);
157
+ }
158
+ };
159
+ const notify = async (method) => {
160
+ const res = await post({ jsonrpc: "2.0", method }, anySignal([AbortSignal.timeout(timeoutMs), ...(connecting ? [connecting] : [])]));
161
+ await res.body?.cancel();
162
+ };
163
+ let serverInfo = { name: "mcp" };
164
+ let instructions;
165
+ const initialize = async (signal) => {
166
+ protocol = undefined;
167
+ const result = await request("initialize", {
168
+ protocolVersion: PROTOCOL_VERSION,
169
+ capabilities: {},
170
+ clientInfo: { name: opts.clientName ?? "runapps-agent", version: "1" },
171
+ }, signal);
172
+ protocol = typeof result.protocolVersion === "string" ? result.protocolVersion : PROTOCOL_VERSION;
173
+ const info = result.serverInfo;
174
+ if (info?.name)
175
+ serverInfo = { name: info.name, version: info.version, title: info.title };
176
+ if (typeof result.instructions === "string")
177
+ instructions = result.instructions;
178
+ await notify("notifications/initialized");
179
+ };
180
+ await initialize(opts.signal);
181
+ let infos = [];
182
+ let tools = [];
183
+ const prefix = clean(opts.prefix ?? serverInfo.name).slice(0, 24) || "mcp";
184
+ const label = opts.name || serverInfo.title || serverInfo.name;
185
+ const load = async (signal) => {
186
+ const all = [];
187
+ const cursors = new Set();
188
+ let cursor;
189
+ do {
190
+ const page = await request("tools/list", cursor ? { cursor } : {}, signal);
191
+ if (!Array.isArray(page.tools))
192
+ throw new MCPError("The MCP server's tool list is malformed.");
193
+ for (const t of page.tools) {
194
+ if (!t || typeof t.name !== "string" || !t.name)
195
+ throw new MCPError("The MCP server listed a tool without a name.");
196
+ const schema = t.inputSchema && typeof t.inputSchema === "object" ? t.inputSchema : { type: "object" };
197
+ all.push({ ...t, inputSchema: { type: "object", properties: {}, ...schema } });
198
+ }
199
+ if (all.length > (opts.maxTools ?? 64))
200
+ throw new MCPError(`The MCP server has more than ${opts.maxTools ?? 64} tools (maxTools).`);
201
+ cursor = typeof page.nextCursor === "string" && page.nextCursor ? page.nextCursor : undefined;
202
+ if (cursor) {
203
+ if (cursors.has(cursor))
204
+ throw new MCPError("The MCP server's tool list repeats a page.");
205
+ cursors.add(cursor);
206
+ }
207
+ } while (cursor);
208
+ infos = all;
209
+ const used = new Set();
210
+ tools = all.map((info) => {
211
+ let name = `${prefix}__${clean(info.name)}`.slice(0, 64);
212
+ for (let n = 2; used.has(name); n++)
213
+ name = `${name.slice(0, 60)}_${n}`;
214
+ used.add(name);
215
+ const readOnly = info.annotations?.readOnlyHint === true;
216
+ const ask = opts.confirm === "never" ? false : opts.confirm === "unless-read-only" ? !readOnly : true;
217
+ const title = info.title ?? info.annotations?.title ?? info.name;
218
+ return defineTool({
219
+ name,
220
+ description: `[${label} — MCP server] ${title !== info.name ? `${title}. ` : ""}${info.description ?? ""}`.trim().slice(0, 4000),
221
+ parameters: info.inputSchema,
222
+ readOnly,
223
+ destructive: info.annotations?.destructiveHint === true || (!readOnly && ask),
224
+ maxResultChars: opts.maxResultChars,
225
+ confirm: ask
226
+ ? (args) => ({ title: `Run ${label} / ${info.name}?`, message: JSON.stringify(args, null, 2).slice(0, 4000) })
227
+ : () => false,
228
+ async execute(args, ctx) {
229
+ let result;
230
+ try {
231
+ result = await request("tools/call", { name: info.name, arguments: args }, ctx.signal, (text) => text && ctx.update(text));
232
+ }
233
+ catch (err) {
234
+ ctx.signal.throwIfAborted();
235
+ if (err instanceof MCPError && err.code !== undefined)
236
+ throw err;
237
+ // The call may have reached the server: say so, so the model does not repeat a side effect blindly.
238
+ throw new MCPError(`${err.message} Whether ${info.name} took effect on the server is unknown; do not repeat it without checking.`);
239
+ }
240
+ const parts = contentOf(result, opts.images === true);
241
+ if (result.isError === true)
242
+ throw new MCPError(parts.map((p) => (p.type === "text" ? p.text : "")).join("\n").trim() || `${info.name} reported an error.`);
243
+ return parts.length === 1 && parts[0].type === "text" ? parts[0].text : parts;
244
+ },
245
+ });
246
+ });
247
+ return tools;
248
+ };
249
+ try {
250
+ await load(opts.signal);
251
+ }
252
+ catch (err) {
253
+ await end();
254
+ throw err;
255
+ }
256
+ connecting = undefined;
257
+ async function end() {
258
+ if (closed)
259
+ return;
260
+ closed = true;
261
+ if (!session)
262
+ return;
263
+ try {
264
+ const res = await doFetch(endpoint, { method: "DELETE", headers: headers(false), redirect: "error", credentials: "omit", signal: AbortSignal.timeout(5000) });
265
+ await res.body?.cancel();
266
+ }
267
+ catch { /* the server may not support it, or be gone */ }
268
+ }
269
+ return {
270
+ get tools() { return tools; },
271
+ get serverTools() { return infos; },
272
+ server: serverInfo,
273
+ instructions,
274
+ refresh: load,
275
+ close: end,
276
+ };
277
+ }
278
+ /** What a tools/call result becomes for the model: text, pictures when allowed, everything else named. */
279
+ function contentOf(result, images) {
280
+ const blocks = Array.isArray(result.content) ? result.content : [];
281
+ const parts = [];
282
+ for (const b of blocks) {
283
+ if (!b || typeof b !== "object")
284
+ continue;
285
+ if (b.type === "text" && typeof b.text === "string")
286
+ parts.push({ type: "text", text: b.text });
287
+ else if (b.type === "image" && typeof b.data === "string") {
288
+ const mime = typeof b.mimeType === "string" ? b.mimeType : "image/png";
289
+ if (images)
290
+ parts.push({ type: "image_url", image_url: { url: `data:${mime};base64,${b.data}` } });
291
+ else
292
+ parts.push({ type: "text", text: `[A picture (${mime}, ${Math.round((b.data.length * 3) / 4)} bytes) was returned; it is not shown here.]` });
293
+ }
294
+ else if (b.type === "audio")
295
+ parts.push({ type: "text", text: `[Audio (${String(b.mimeType ?? "audio")}) was returned; it is not shown here.]` });
296
+ else if (b.type === "resource" && b.resource && typeof b.resource === "object") {
297
+ const r = b.resource;
298
+ parts.push({ type: "text", text: typeof r.text === "string" ? `${r.uri ? `${r.uri}:\n` : ""}${r.text}` : `[Resource ${r.uri ?? ""} (${r.mimeType ?? "binary"}); its content is not shown here.]` });
299
+ }
300
+ else if (b.type === "resource_link")
301
+ parts.push({ type: "text", text: `[Link: ${String(b.name ?? "")} ${String(b.uri ?? "")}]`.replace(/\s+\]/, "]") });
302
+ }
303
+ if (!parts.length && result.structuredContent !== undefined)
304
+ parts.push({ type: "text", text: JSON.stringify(result.structuredContent) });
305
+ if (!parts.length)
306
+ parts.push({ type: "text", text: "OK" });
307
+ return parts;
308
+ }
309
+ function clean(s) {
310
+ return s.replace(/[^A-Za-z0-9_-]+/g, "_").replace(/^_+|_+$/g, "");
311
+ }
312
+ function anySignal(signals) {
313
+ const any = AbortSignal.any;
314
+ if (any)
315
+ return any(signals);
316
+ const c = new AbortController();
317
+ for (const s of signals) {
318
+ if (s.aborted) {
319
+ c.abort(s.reason);
320
+ break;
321
+ }
322
+ s.addEventListener("abort", () => c.abort(s.reason), { once: true });
323
+ }
324
+ return c.signal;
325
+ }