@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
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import type { ChatCompletion, ChatCompletionChunk, ChatCompletionParams } from "./llm.js";
|
|
2
|
+
/** A model in the provider's catalogue (all but `id` optional). */
|
|
3
|
+
export interface ModelInfo {
|
|
4
|
+
id: string;
|
|
5
|
+
/** The provider's default (used when the agent names no model). */
|
|
6
|
+
is_default?: boolean;
|
|
7
|
+
/** "text" for chat models; others are left out of the model picker. */
|
|
8
|
+
capability?: string;
|
|
9
|
+
/** Context window in tokens. */
|
|
10
|
+
max_input_tokens?: number;
|
|
11
|
+
/** Most tokens one reply may have. */
|
|
12
|
+
max_tokens?: number;
|
|
13
|
+
/** Request options the model takes; `inputs.reasoning_effort.enum` lists its thinking levels. */
|
|
14
|
+
options?: {
|
|
15
|
+
inputs?: Record<string, {
|
|
16
|
+
enum?: unknown[];
|
|
17
|
+
default?: unknown;
|
|
18
|
+
}>;
|
|
19
|
+
};
|
|
20
|
+
/** What the model takes as input: `["text", "image"]`, also `"video"`, `"audio"` (RunApps' `/v1/models`). */
|
|
21
|
+
input_modalities?: string[];
|
|
22
|
+
/** What a call costs whoever makes it; the chat's settings and `/context` show it. */
|
|
23
|
+
price?: ModelPrice;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* A model's price to its caller: `input` / `output` per million tokens and
|
|
27
|
+
* `per_call` added to every call, all in `currency` (an ISO code, default
|
|
28
|
+
* `"USD"`). The provider's `usage.total_cost` is in the same currency.
|
|
29
|
+
*/
|
|
30
|
+
export interface ModelPrice {
|
|
31
|
+
input?: number;
|
|
32
|
+
output?: number;
|
|
33
|
+
per_call?: number;
|
|
34
|
+
currency?: string;
|
|
35
|
+
}
|
|
36
|
+
/** A kind of input a model may or may not take besides text. */
|
|
37
|
+
export type InputKind = "image" | "video" | "audio";
|
|
38
|
+
/**
|
|
39
|
+
* Whether `model` takes `kind` as input: from its `input_modalities`, or —
|
|
40
|
+
* for pictures — its `vision` capability. Undefined when the catalogue does
|
|
41
|
+
* not say (an OpenAI-style `/models`, a model it does not list).
|
|
42
|
+
*/
|
|
43
|
+
export declare function modelAccepts(model: ModelInfo | undefined, kind: InputKind): boolean | undefined;
|
|
44
|
+
export interface ModelProvider {
|
|
45
|
+
/**
|
|
46
|
+
* One streamed chat completion: OpenAI's `chat.completion.chunk`s —
|
|
47
|
+
* `delta.content`, `delta.reasoning_content` (or `reasoning`),
|
|
48
|
+
* `delta.tool_calls` by `index`, `finish_reason`, `usage`. Stop when
|
|
49
|
+
* `signal` aborts. Throw a `ProviderError` with the HTTP status for
|
|
50
|
+
* failures, so 408/429/5xx are retried (and `retryAfter` honoured).
|
|
51
|
+
*/
|
|
52
|
+
stream(params: ChatCompletionParams, init?: {
|
|
53
|
+
signal?: AbortSignal;
|
|
54
|
+
}): AsyncIterable<ChatCompletionChunk>;
|
|
55
|
+
/** One whole completion (compaction summaries). Without it, `stream` is collected. */
|
|
56
|
+
complete?(params: ChatCompletionParams, init?: {
|
|
57
|
+
signal?: AbortSignal;
|
|
58
|
+
}): Promise<ChatCompletion>;
|
|
59
|
+
/** The catalogue: context windows, output limits, the default model, thinking levels. Without it, safe defaults. */
|
|
60
|
+
models?(opts?: {
|
|
61
|
+
capability?: string;
|
|
62
|
+
}): Promise<ModelInfo[]>;
|
|
63
|
+
/**
|
|
64
|
+
* A file from the provider's own storage, for `files:<path>` skills
|
|
65
|
+
* sources; `etag` is the one read last time — answer null when unchanged.
|
|
66
|
+
*/
|
|
67
|
+
readFile?(path: string, opts?: {
|
|
68
|
+
etag?: string;
|
|
69
|
+
}): Promise<{
|
|
70
|
+
bytes: Uint8Array;
|
|
71
|
+
etag?: string;
|
|
72
|
+
} | null>;
|
|
73
|
+
/** Names the app's local storage (IndexedDB) when the host gives no `project`. */
|
|
74
|
+
name?: string;
|
|
75
|
+
}
|
|
76
|
+
/** A failed model call. `status` is the HTTP status (0: no answer at all). */
|
|
77
|
+
export declare class ProviderError extends Error {
|
|
78
|
+
readonly status: number;
|
|
79
|
+
readonly code?: string;
|
|
80
|
+
/** Seconds to wait before trying again, when the server said. */
|
|
81
|
+
readonly retryAfter?: number;
|
|
82
|
+
constructor(status: number, message: string, opts?: {
|
|
83
|
+
code?: string;
|
|
84
|
+
retryAfter?: number;
|
|
85
|
+
});
|
|
86
|
+
/** The RunApps SDK's name for `status`. */
|
|
87
|
+
get statusCode(): number;
|
|
88
|
+
}
|
|
89
|
+
/** The status of any provider's error: ProviderError, the RunApps SDK's APIError, or anything with a `status`. */
|
|
90
|
+
export declare function errorStatus(err: unknown): number | undefined;
|
|
91
|
+
/** The parts of the RunApps SDK client a provider needs. */
|
|
92
|
+
export interface RunAppsClientLike {
|
|
93
|
+
chat: {
|
|
94
|
+
stream(params: ChatCompletionParams, init?: {
|
|
95
|
+
signal?: AbortSignal;
|
|
96
|
+
}): AsyncIterable<ChatCompletionChunk>;
|
|
97
|
+
create?(params: ChatCompletionParams, init?: {
|
|
98
|
+
signal?: AbortSignal;
|
|
99
|
+
}): Promise<ChatCompletion>;
|
|
100
|
+
};
|
|
101
|
+
models?: {
|
|
102
|
+
list?(opts?: {
|
|
103
|
+
capability?: string;
|
|
104
|
+
}): Promise<unknown[]>;
|
|
105
|
+
};
|
|
106
|
+
files?: {
|
|
107
|
+
stat(path: string): Promise<{
|
|
108
|
+
etag?: string;
|
|
109
|
+
}>;
|
|
110
|
+
get(path: string): Promise<Blob>;
|
|
111
|
+
};
|
|
112
|
+
projectName?: string;
|
|
113
|
+
}
|
|
114
|
+
/** The RunApps SDK client as a provider: the gateway's models and catalogue, the user's RunApps storage for `files:` skills. */
|
|
115
|
+
export declare function runappsProvider(client: RunAppsClientLike): ModelProvider;
|
|
116
|
+
/** A provider, or a RunApps SDK client made into one. */
|
|
117
|
+
export declare function toProvider(p: ModelProvider | RunAppsClientLike): ModelProvider;
|
|
118
|
+
export interface OpenAIProviderOptions {
|
|
119
|
+
/** The API root, e.g. `https://api.openai.com/v1` or your own proxy (`/api/llm`). */
|
|
120
|
+
baseURL: string;
|
|
121
|
+
/** Sent as `Authorization: Bearer …` (leave it out when your proxy adds it). */
|
|
122
|
+
apiKey?: string;
|
|
123
|
+
/** More request headers (an `Authorization` here replaces the apiKey's). */
|
|
124
|
+
headers?: Record<string, string>;
|
|
125
|
+
/** The catalogue: a fixed list, `"fetch"` for `GET /models` (ids, and limits where the endpoint lists them), or nothing. */
|
|
126
|
+
models?: ModelInfo[] | "fetch";
|
|
127
|
+
/** Asks for `usage` in the last streamed chunk (`stream_options.include_usage`, default true). */
|
|
128
|
+
streamUsage?: boolean;
|
|
129
|
+
fetch?: typeof fetch;
|
|
130
|
+
name?: string;
|
|
131
|
+
}
|
|
132
|
+
/** Any OpenAI-compatible Chat Completions endpoint, with plain fetch and SSE. */
|
|
133
|
+
export declare function openAIProvider(o: OpenAIProviderOptions): ModelProvider;
|
|
134
|
+
/** The `data:` payloads of a server-sent event stream. */
|
|
135
|
+
export declare function sseData(body: ReadableStream<Uint8Array>, signal?: AbortSignal): AsyncGenerator<string>;
|
package/dist/provider.js
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
// Where the agent's model calls go: a ModelProvider. One method is
|
|
2
|
+
// required — a streamed Chat Completions call; the rest are optional. Two
|
|
3
|
+
// come with the package: runappsProvider (the RunApps SDK client) and
|
|
4
|
+
// openAIProvider (any OpenAI-compatible endpoint, plain fetch). A host can
|
|
5
|
+
// write its own: its server, another SDK, a local model.
|
|
6
|
+
/**
|
|
7
|
+
* Whether `model` takes `kind` as input: from its `input_modalities`, or —
|
|
8
|
+
* for pictures — its `vision` capability. Undefined when the catalogue does
|
|
9
|
+
* not say (an OpenAI-style `/models`, a model it does not list).
|
|
10
|
+
*/
|
|
11
|
+
export function modelAccepts(model, kind) {
|
|
12
|
+
if (!model)
|
|
13
|
+
return undefined;
|
|
14
|
+
if (Array.isArray(model.input_modalities))
|
|
15
|
+
return model.input_modalities.includes(kind);
|
|
16
|
+
if (kind === "image" && model.capability === "vision")
|
|
17
|
+
return true;
|
|
18
|
+
return undefined;
|
|
19
|
+
}
|
|
20
|
+
/** A failed model call. `status` is the HTTP status (0: no answer at all). */
|
|
21
|
+
export class ProviderError extends Error {
|
|
22
|
+
status;
|
|
23
|
+
code;
|
|
24
|
+
/** Seconds to wait before trying again, when the server said. */
|
|
25
|
+
retryAfter;
|
|
26
|
+
constructor(status, message, opts = {}) {
|
|
27
|
+
super(message);
|
|
28
|
+
this.name = "ProviderError";
|
|
29
|
+
this.status = status;
|
|
30
|
+
this.code = opts.code;
|
|
31
|
+
this.retryAfter = opts.retryAfter;
|
|
32
|
+
}
|
|
33
|
+
/** The RunApps SDK's name for `status`. */
|
|
34
|
+
get statusCode() { return this.status; }
|
|
35
|
+
}
|
|
36
|
+
/** The status of any provider's error: ProviderError, the RunApps SDK's APIError, or anything with a `status`. */
|
|
37
|
+
export function errorStatus(err) {
|
|
38
|
+
if (!err || typeof err !== "object")
|
|
39
|
+
return undefined;
|
|
40
|
+
const e = err;
|
|
41
|
+
const s = typeof e.statusCode === "number" ? e.statusCode : typeof e.status === "number" ? e.status : undefined;
|
|
42
|
+
return s;
|
|
43
|
+
}
|
|
44
|
+
/** The RunApps SDK client as a provider: the gateway's models and catalogue, the user's RunApps storage for `files:` skills. */
|
|
45
|
+
export function runappsProvider(client) {
|
|
46
|
+
const files = client.files;
|
|
47
|
+
return {
|
|
48
|
+
name: client.projectName,
|
|
49
|
+
stream: (p, init) => client.chat.stream(p, init),
|
|
50
|
+
// Only what the client really has: a stand-in without create() or a catalogue is still a provider.
|
|
51
|
+
complete: client.chat.create ? (p, init) => client.chat.create(p, init) : undefined,
|
|
52
|
+
models: client.models?.list ? async (o) => (await client.models.list(o)) : undefined,
|
|
53
|
+
readFile: files
|
|
54
|
+
? async (path, o) => {
|
|
55
|
+
const st = await files.stat(path);
|
|
56
|
+
if (o?.etag && st.etag && o.etag === st.etag)
|
|
57
|
+
return null;
|
|
58
|
+
return { bytes: new Uint8Array(await (await files.get(path)).arrayBuffer()), etag: st.etag };
|
|
59
|
+
}
|
|
60
|
+
: undefined,
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
/** A provider, or a RunApps SDK client made into one. */
|
|
64
|
+
export function toProvider(p) {
|
|
65
|
+
if (typeof p.stream === "function")
|
|
66
|
+
return p;
|
|
67
|
+
if (typeof p.chat?.stream === "function")
|
|
68
|
+
return runappsProvider(p);
|
|
69
|
+
throw new Error("pass a ModelProvider (with stream()) or a RunApps client");
|
|
70
|
+
}
|
|
71
|
+
/** Any OpenAI-compatible Chat Completions endpoint, with plain fetch and SSE. */
|
|
72
|
+
export function openAIProvider(o) {
|
|
73
|
+
const base = o.baseURL.replace(/\/+$/, "");
|
|
74
|
+
const doFetch = o.fetch ?? ((...a) => fetch(...a));
|
|
75
|
+
const headers = () => ({
|
|
76
|
+
"Content-Type": "application/json",
|
|
77
|
+
...(o.apiKey ? { Authorization: `Bearer ${o.apiKey}` } : {}),
|
|
78
|
+
...(o.headers ?? {}),
|
|
79
|
+
});
|
|
80
|
+
const post = async (body, signal) => {
|
|
81
|
+
let res;
|
|
82
|
+
try {
|
|
83
|
+
res = await doFetch(`${base}/chat/completions`, { method: "POST", headers: headers(), body: JSON.stringify(body), signal });
|
|
84
|
+
}
|
|
85
|
+
catch (err) {
|
|
86
|
+
if (signal?.aborted)
|
|
87
|
+
throw err;
|
|
88
|
+
throw new ProviderError(0, `network error: ${err.message}`);
|
|
89
|
+
}
|
|
90
|
+
if (!res.ok)
|
|
91
|
+
throw await errorOf(res);
|
|
92
|
+
return res;
|
|
93
|
+
};
|
|
94
|
+
return {
|
|
95
|
+
name: o.name,
|
|
96
|
+
async *stream(p, init) {
|
|
97
|
+
const body = { ...p, stream: true, ...(o.streamUsage === false ? {} : { stream_options: { include_usage: true } }) };
|
|
98
|
+
const res = await post(body, init?.signal);
|
|
99
|
+
if (!res.body)
|
|
100
|
+
throw new ProviderError(0, "the response has no body to stream");
|
|
101
|
+
for await (const data of sseData(res.body, init?.signal)) {
|
|
102
|
+
if (data === "[DONE]")
|
|
103
|
+
return;
|
|
104
|
+
let chunk;
|
|
105
|
+
try {
|
|
106
|
+
chunk = JSON.parse(data);
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
if (chunk.error)
|
|
112
|
+
throw new ProviderError(500, chunk.error.message ?? "stream error", { code: chunk.error.code });
|
|
113
|
+
yield chunk;
|
|
114
|
+
}
|
|
115
|
+
},
|
|
116
|
+
async complete(p, init) {
|
|
117
|
+
const res = await post({ ...p, stream: false }, init?.signal);
|
|
118
|
+
return (await res.json());
|
|
119
|
+
},
|
|
120
|
+
models: o.models === undefined ? undefined : async () => {
|
|
121
|
+
if (Array.isArray(o.models))
|
|
122
|
+
return o.models;
|
|
123
|
+
const res = await doFetch(`${base}/models`, { headers: headers() });
|
|
124
|
+
if (!res.ok)
|
|
125
|
+
throw await errorOf(res);
|
|
126
|
+
// OpenAI lists ids only; a gateway that says more (limits, capability, default) is taken at its word.
|
|
127
|
+
const j = (await res.json());
|
|
128
|
+
return (j.data ?? []).map(({ id, is_default, capability, max_input_tokens, max_tokens, options }) => ({ id, is_default, capability: capability ?? "text", max_input_tokens, max_tokens, options }));
|
|
129
|
+
},
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
async function errorOf(res) {
|
|
133
|
+
let message = `HTTP ${res.status}`;
|
|
134
|
+
let code;
|
|
135
|
+
try {
|
|
136
|
+
const j = (await res.json());
|
|
137
|
+
if (typeof j.error === "string")
|
|
138
|
+
message = j.error;
|
|
139
|
+
else if (j.error?.message) {
|
|
140
|
+
message = j.error.message;
|
|
141
|
+
code = j.error.code ?? j.error.type;
|
|
142
|
+
}
|
|
143
|
+
else if (j.message)
|
|
144
|
+
message = j.message;
|
|
145
|
+
}
|
|
146
|
+
catch { /* not JSON */ }
|
|
147
|
+
const ra = Number(res.headers.get("Retry-After"));
|
|
148
|
+
return new ProviderError(res.status, message, { code, retryAfter: Number.isFinite(ra) && ra > 0 ? ra : undefined });
|
|
149
|
+
}
|
|
150
|
+
/** The `data:` payloads of a server-sent event stream. */
|
|
151
|
+
export async function* sseData(body, signal) {
|
|
152
|
+
const reader = body.getReader();
|
|
153
|
+
const decoder = new TextDecoder();
|
|
154
|
+
let buf = "";
|
|
155
|
+
const onAbort = () => { void reader.cancel().catch(() => undefined); };
|
|
156
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
157
|
+
try {
|
|
158
|
+
for (;;) {
|
|
159
|
+
const { done, value } = await reader.read();
|
|
160
|
+
if (done)
|
|
161
|
+
break;
|
|
162
|
+
buf += decoder.decode(value, { stream: true });
|
|
163
|
+
let nl;
|
|
164
|
+
while ((nl = buf.search(/\r?\n\r?\n/)) >= 0) {
|
|
165
|
+
const event = buf.slice(0, nl);
|
|
166
|
+
buf = buf.slice(nl).replace(/^\r?\n\r?\n/, "");
|
|
167
|
+
const data = event.split(/\r?\n/).filter((l) => l.startsWith("data:")).map((l) => l.slice(5).replace(/^ /, "")).join("\n");
|
|
168
|
+
if (data)
|
|
169
|
+
yield data;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
const rest = buf.split(/\r?\n/).filter((l) => l.startsWith("data:")).map((l) => l.slice(5).replace(/^ /, "")).join("\n");
|
|
173
|
+
if (rest)
|
|
174
|
+
yield rest;
|
|
175
|
+
}
|
|
176
|
+
finally {
|
|
177
|
+
signal?.removeEventListener("abort", onAbort);
|
|
178
|
+
reader.releaseLock();
|
|
179
|
+
}
|
|
180
|
+
signal?.throwIfAborted();
|
|
181
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { Tool } from "./types.js";
|
|
2
|
+
import { type Workspace } from "./workspace.js";
|
|
3
|
+
import type { FileGuard } from "./file-guard.js";
|
|
4
|
+
/**
|
|
5
|
+
* Isolation is best effort: the code runs in a Worker of the page's origin with network and storage
|
|
6
|
+
* globals removed. Code that can be trusted with nothing should run in a sandboxed iframe of its own.
|
|
7
|
+
*/
|
|
8
|
+
export interface SandboxOptions {
|
|
9
|
+
/** The agent's read-before-write guard: `fs.read` counts as reading, `fs.write` and `fs.remove` are checked like the file tools. */
|
|
10
|
+
guard?: FileGuard;
|
|
11
|
+
/** Kill the run after this long (default 10 s, max 60 s). */
|
|
12
|
+
timeoutMs?: number;
|
|
13
|
+
/** Leave fetch/WebSocket available inside the sandbox (default false). */
|
|
14
|
+
network?: boolean;
|
|
15
|
+
/** Longest console output kept (default 20 000 chars). */
|
|
16
|
+
maxLogChars?: number;
|
|
17
|
+
/** Asked before `fs.remove(path)` deletes a file (the tool asks like delete_file does); false refuses. */
|
|
18
|
+
confirmDelete?: (path: string) => boolean | Promise<boolean>;
|
|
19
|
+
}
|
|
20
|
+
export interface SandboxResult {
|
|
21
|
+
ok: boolean;
|
|
22
|
+
/** The value the code returned, JSON-serialised. */
|
|
23
|
+
result?: string;
|
|
24
|
+
logs: string;
|
|
25
|
+
error?: string;
|
|
26
|
+
durationMs: number;
|
|
27
|
+
}
|
|
28
|
+
/** Runs `code` once in a fresh sandbox bound to `ws` (null: no fs). */
|
|
29
|
+
export declare function runInSandbox(ws: Workspace | null, code: string, input: unknown, opts?: SandboxOptions & {
|
|
30
|
+
signal?: AbortSignal;
|
|
31
|
+
}): Promise<SandboxResult>;
|
|
32
|
+
/** The `run_js` tool. */
|
|
33
|
+
export declare function sandboxTool(ws: Workspace | null, opts?: SandboxOptions): Tool;
|
package/dist/sandbox.js
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
// A JavaScript sandbox for the model: its code runs in a Worker (browser)
|
|
2
|
+
// or a worker thread (Node) with no DOM and, by default, no network, a
|
|
3
|
+
// captured console, and an `fs` bridged to the workspace. The `run_js`
|
|
4
|
+
// tool wraps it so the model can compute, transform data and run a
|
|
5
|
+
// skill's scripts instead of guessing.
|
|
6
|
+
import { defineTool } from "./tool.js";
|
|
7
|
+
import { normalizePath } from "./workspace.js";
|
|
8
|
+
// The worker program. Plain JS, no imports, so it can run as a blob URL
|
|
9
|
+
// Worker and as a worker_threads eval script alike.
|
|
10
|
+
const WORKER_SOURCE = `
|
|
11
|
+
"use strict";
|
|
12
|
+
var isNode = typeof self === "undefined";
|
|
13
|
+
var port, send;
|
|
14
|
+
if (isNode) {
|
|
15
|
+
port = require("node:worker_threads").parentPort;
|
|
16
|
+
send = function (m) { port.postMessage(m); };
|
|
17
|
+
} else {
|
|
18
|
+
port = self;
|
|
19
|
+
send = function (m) { self.postMessage(m); };
|
|
20
|
+
}
|
|
21
|
+
var pending = new Map(), seq = 0;
|
|
22
|
+
function rpc(op, args) {
|
|
23
|
+
return new Promise(function (resolve, reject) {
|
|
24
|
+
var id = ++seq;
|
|
25
|
+
pending.set(id, { resolve: resolve, reject: reject });
|
|
26
|
+
send({ type: "fs", id: id, op: op, args: args });
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
var fs = {
|
|
30
|
+
read: function (p) { return rpc("read", [p]); },
|
|
31
|
+
write: function (p, c) { return rpc("write", [p, c]); },
|
|
32
|
+
list: function (p) { return rpc("list", [p || "/"]); },
|
|
33
|
+
exists: function (p) { return rpc("exists", [p]); },
|
|
34
|
+
remove: function (p) { return rpc("delete", [p]); },
|
|
35
|
+
};
|
|
36
|
+
var logs = [], logChars = 0, maxLog = 20000;
|
|
37
|
+
function fmt(a) {
|
|
38
|
+
if (typeof a === "string") return a;
|
|
39
|
+
try { return JSON.stringify(a, null, 0); } catch (e) { return String(a); }
|
|
40
|
+
}
|
|
41
|
+
function log() {
|
|
42
|
+
var line = Array.prototype.map.call(arguments, fmt).join(" ");
|
|
43
|
+
if (logChars < maxLog) { logs.push(line); logChars += line.length + 1; }
|
|
44
|
+
}
|
|
45
|
+
var sandboxConsole = { log: log, info: log, warn: log, error: log, debug: log, table: log, dir: log };
|
|
46
|
+
function serialize(v) {
|
|
47
|
+
if (v === undefined) return undefined;
|
|
48
|
+
try { return JSON.stringify(v); } catch (e) { return JSON.stringify(String(v)); }
|
|
49
|
+
}
|
|
50
|
+
async function run(msg) {
|
|
51
|
+
maxLog = msg.maxLogChars || maxLog;
|
|
52
|
+
var g = isNode ? globalThis : self;
|
|
53
|
+
// Shadow a global on the object and on every prototype that defines it (so a getter cannot be fetched from the prototype).
|
|
54
|
+
function hide(k) {
|
|
55
|
+
for (var o = g; o; o = Object.getPrototypeOf(o)) {
|
|
56
|
+
if (Object.prototype.hasOwnProperty.call(o, k)) { try { Object.defineProperty(o, k, { value: undefined, configurable: false, writable: false }); } catch (e) {} }
|
|
57
|
+
}
|
|
58
|
+
try { Object.defineProperty(g, k, { value: undefined, configurable: false, writable: false }); } catch (e) {}
|
|
59
|
+
}
|
|
60
|
+
// Always: no nested workers (they would get the network back), no direct access to the app's storage.
|
|
61
|
+
["Worker", "SharedWorker", "indexedDB", "caches", "BroadcastChannel"].forEach(hide);
|
|
62
|
+
if (!msg.network) {
|
|
63
|
+
["fetch", "XMLHttpRequest", "WebSocket", "WebSocketStream", "EventSource", "WebTransport", "importScripts", "navigator"].forEach(hide);
|
|
64
|
+
if (isNode) { try { globalThis.require = undefined; globalThis.process = undefined; } catch (e) {} }
|
|
65
|
+
}
|
|
66
|
+
var start = Date.now();
|
|
67
|
+
try {
|
|
68
|
+
var AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;
|
|
69
|
+
var fn = new AsyncFunction("fs", "input", "console", msg.code);
|
|
70
|
+
var value = await fn(fs, msg.input, sandboxConsole);
|
|
71
|
+
send({ type: "done", result: serialize(value), logs: logs.join("\\n"), durationMs: Date.now() - start });
|
|
72
|
+
} catch (e) {
|
|
73
|
+
send({ type: "error", error: (e && e.stack) || String(e), logs: logs.join("\\n"), durationMs: Date.now() - start });
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
function onMessage(m) {
|
|
77
|
+
if (m.type === "run") run(m);
|
|
78
|
+
else if (m.type === "fsResult") {
|
|
79
|
+
var p = pending.get(m.id);
|
|
80
|
+
if (!p) return;
|
|
81
|
+
pending.delete(m.id);
|
|
82
|
+
if (m.ok) p.resolve(m.value); else p.reject(new Error(m.error));
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
if (isNode) port.on("message", onMessage); else self.onmessage = function (ev) { onMessage(ev.data); };
|
|
86
|
+
`;
|
|
87
|
+
async function spawn() {
|
|
88
|
+
if (typeof Worker === "function" && typeof Blob === "function" && typeof URL?.createObjectURL === "function") {
|
|
89
|
+
const url = URL.createObjectURL(new Blob([WORKER_SOURCE], { type: "text/javascript" }));
|
|
90
|
+
const w = new Worker(url);
|
|
91
|
+
URL.revokeObjectURL(url);
|
|
92
|
+
return {
|
|
93
|
+
post: (m) => w.postMessage(m),
|
|
94
|
+
onMessage: (fn) => { w.onmessage = (ev) => fn(ev.data); },
|
|
95
|
+
terminate: () => w.terminate(),
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
// Node: worker_threads, imported in a way bundlers for the browser leave alone.
|
|
99
|
+
const dynamicImport = new Function("m", "return import(m)");
|
|
100
|
+
const { Worker: NodeWorker } = await dynamicImport("node:worker_threads");
|
|
101
|
+
const w = new NodeWorker(WORKER_SOURCE, { eval: true });
|
|
102
|
+
return {
|
|
103
|
+
post: (m) => w.postMessage(m),
|
|
104
|
+
onMessage: (fn) => w.on("message", (m) => fn(m)),
|
|
105
|
+
terminate: () => w.terminate(),
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
/** Runs `code` once in a fresh sandbox bound to `ws` (null: no fs). */
|
|
109
|
+
export async function runInSandbox(ws, code, input, opts = {}) {
|
|
110
|
+
const timeoutMs = Math.min(60_000, Math.max(100, opts.timeoutMs ?? 10_000));
|
|
111
|
+
const worker = await spawn();
|
|
112
|
+
const started = Date.now();
|
|
113
|
+
return new Promise((resolve) => {
|
|
114
|
+
let settled = false;
|
|
115
|
+
const finish = (r) => {
|
|
116
|
+
if (settled)
|
|
117
|
+
return;
|
|
118
|
+
settled = true;
|
|
119
|
+
clearTimeout(timer);
|
|
120
|
+
opts.signal?.removeEventListener("abort", onAbort);
|
|
121
|
+
worker.terminate();
|
|
122
|
+
resolve(r);
|
|
123
|
+
};
|
|
124
|
+
const timer = setTimeout(() => finish({ ok: false, logs: "", error: `Timed out after ${timeoutMs} ms`, durationMs: Date.now() - started }), timeoutMs);
|
|
125
|
+
const onAbort = () => finish({ ok: false, logs: "", error: "Aborted", durationMs: Date.now() - started });
|
|
126
|
+
opts.signal?.addEventListener("abort", onAbort, { once: true });
|
|
127
|
+
worker.onMessage(async (m) => {
|
|
128
|
+
if (m.type === "done") {
|
|
129
|
+
finish({ ok: true, result: m.result, logs: m.logs ?? "", durationMs: m.durationMs ?? Date.now() - started });
|
|
130
|
+
}
|
|
131
|
+
else if (m.type === "error") {
|
|
132
|
+
finish({ ok: false, error: String(m.error), logs: m.logs ?? "", durationMs: m.durationMs ?? Date.now() - started });
|
|
133
|
+
}
|
|
134
|
+
else if (m.type === "fs") {
|
|
135
|
+
const id = m.id;
|
|
136
|
+
const args = m.args ?? [];
|
|
137
|
+
try {
|
|
138
|
+
if (!ws)
|
|
139
|
+
throw new Error("no workspace");
|
|
140
|
+
let value;
|
|
141
|
+
switch (m.op) {
|
|
142
|
+
case "read": {
|
|
143
|
+
// Text files as they are; a PDF as the text of its pages.
|
|
144
|
+
const p = normalizePath(String(args[0]));
|
|
145
|
+
const doc = await ws.readAsText(p);
|
|
146
|
+
if (!doc)
|
|
147
|
+
throw new Error(`${p} is a binary file`);
|
|
148
|
+
await opts.guard?.saw(p, { text: doc.kind === "text" ? doc.text : undefined });
|
|
149
|
+
value = doc.text;
|
|
150
|
+
break;
|
|
151
|
+
}
|
|
152
|
+
case "write": {
|
|
153
|
+
const p = normalizePath(String(args[0]));
|
|
154
|
+
await opts.guard?.check(p, "overwrite");
|
|
155
|
+
await ws.write(p, String(args[1] ?? ""));
|
|
156
|
+
await opts.guard?.wrote(p);
|
|
157
|
+
value = true;
|
|
158
|
+
break;
|
|
159
|
+
}
|
|
160
|
+
case "list":
|
|
161
|
+
value = (await ws.list(String(args[0] ?? "/"))).map((f) => ({ path: f.path, size: f.size }));
|
|
162
|
+
break;
|
|
163
|
+
case "exists":
|
|
164
|
+
value = await ws.exists(String(args[0]));
|
|
165
|
+
break;
|
|
166
|
+
case "delete": {
|
|
167
|
+
const path = normalizePath(String(args[0]));
|
|
168
|
+
await opts.guard?.check(path, "delete");
|
|
169
|
+
if (opts.confirmDelete && !(await opts.confirmDelete(path)))
|
|
170
|
+
throw new Error(`the user declined deleting ${path}`);
|
|
171
|
+
await ws.delete(path);
|
|
172
|
+
opts.guard?.forget(path);
|
|
173
|
+
value = true;
|
|
174
|
+
break;
|
|
175
|
+
}
|
|
176
|
+
default: throw new Error(`unknown fs op ${String(m.op)}`);
|
|
177
|
+
}
|
|
178
|
+
worker.post({ type: "fsResult", id, ok: true, value });
|
|
179
|
+
}
|
|
180
|
+
catch (e) {
|
|
181
|
+
worker.post({ type: "fsResult", id, ok: false, error: e.message });
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
});
|
|
185
|
+
worker.post({ type: "run", code, input, network: !!opts.network, maxLogChars: opts.maxLogChars });
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
/** The `run_js` tool. */
|
|
189
|
+
export function sandboxTool(ws, opts = {}) {
|
|
190
|
+
return defineTool({
|
|
191
|
+
name: "run_js",
|
|
192
|
+
description: "Run JavaScript in a sandbox (no DOM, no network) and get back what it returns plus its console output. Use it for arithmetic, dates, parsing, data transformation, and to run a skill's scripts instead of working them out by hand. The code is the body of an async function: use `return` for the result (JSON), `console.log` for notes. Available: `input` (the input argument), and `fs` for the workspace — `await fs.read(path)` → text, `await fs.write(path, text)`, `await fs.list(folder)` → [{path, size}], `await fs.exists(path)`.",
|
|
193
|
+
parameters: {
|
|
194
|
+
type: "object",
|
|
195
|
+
properties: {
|
|
196
|
+
code: { type: "string", description: "JavaScript, the body of an async function" },
|
|
197
|
+
input: { description: "Any JSON value made available as `input`" },
|
|
198
|
+
timeout_ms: { type: "integer", minimum: 100, maximum: 60000 },
|
|
199
|
+
},
|
|
200
|
+
required: ["code"],
|
|
201
|
+
additionalProperties: false,
|
|
202
|
+
},
|
|
203
|
+
maxResultChars: 24_000,
|
|
204
|
+
async execute({ code, input, timeout_ms }, ctx) {
|
|
205
|
+
// fs.remove asks first, as delete_file does, unless the agent allows everything.
|
|
206
|
+
const confirmDelete = opts.confirmDelete ?? ((path) => ctx.agent?.settings.permissions === "auto" ? true : ctx.ui.confirm(`Allow run_js to delete ${path}?`, undefined, { danger: true, signal: ctx.signal }));
|
|
207
|
+
const r = await runInSandbox(ws, code, input, { ...opts, confirmDelete, timeoutMs: timeout_ms ?? opts.timeoutMs, signal: ctx.signal });
|
|
208
|
+
const parts = [];
|
|
209
|
+
if (r.logs)
|
|
210
|
+
parts.push(`console:\n${r.logs}`);
|
|
211
|
+
if (r.ok)
|
|
212
|
+
parts.push(r.result === undefined ? "Returned: undefined" : `Returned: ${r.result}`);
|
|
213
|
+
else
|
|
214
|
+
parts.push(`Error: ${r.error}`);
|
|
215
|
+
parts.push(`(${r.durationMs} ms)`);
|
|
216
|
+
return { content: parts.join("\n\n"), details: r };
|
|
217
|
+
},
|
|
218
|
+
});
|
|
219
|
+
}
|
package/dist/select.d.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export interface SelectOption {
|
|
2
|
+
value: string;
|
|
3
|
+
label: string;
|
|
4
|
+
/** Dimmer text at the right of the option (limits, a hint). */
|
|
5
|
+
note?: string;
|
|
6
|
+
}
|
|
7
|
+
export interface SelectBox {
|
|
8
|
+
readonly el: HTMLElement;
|
|
9
|
+
value: string;
|
|
10
|
+
disabled: boolean;
|
|
11
|
+
setOptions(options: SelectOption[]): void;
|
|
12
|
+
readonly options: readonly SelectOption[];
|
|
13
|
+
/** Closes the list if it is open (and lets go of the document listener it holds while open). */
|
|
14
|
+
close(): void;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* `host` is the element the list is positioned in (the chat's root: the
|
|
18
|
+
* list may leave the menu the box sits in, never the chat). It needs a
|
|
19
|
+
* position (relative is fine) and the chat's tokens: the chat's root, or
|
|
20
|
+
* any element with the class `ra-ui`.
|
|
21
|
+
*/
|
|
22
|
+
export declare function selectBox(host: HTMLElement, opts?: {
|
|
23
|
+
options?: SelectOption[];
|
|
24
|
+
value?: string;
|
|
25
|
+
filterAt?: number;
|
|
26
|
+
placeholder?: string;
|
|
27
|
+
filterLabel?: string;
|
|
28
|
+
}): SelectBox;
|
|
29
|
+
/** The dropdown's look, in the chat's tokens. */
|
|
30
|
+
export declare const SELECT_CSS = "\n:is(.ra-chat,.ra-ui) .ra-sel{display:flex;align-items:center;gap:8px;width:100%;min-width:0;min-height:34px;padding:6px 10px 6px 12px;box-sizing:border-box;font:inherit;font-size:13px;color:var(--ra-fg);background:var(--ra-bg);border:1px solid var(--ra-border);border-radius:8px;text-align:left;cursor:pointer}\n:is(.ra-chat,.ra-ui) .ra-sel:hover:not(:disabled){border-color:color-mix(in srgb,var(--ra-fg) 25%,var(--ra-border))}\n:is(.ra-chat,.ra-ui) .ra-sel:focus-visible,:is(.ra-chat,.ra-ui) .ra-sel[aria-expanded=true]{border-color:var(--ra-accent);outline:0;box-shadow:0 0 0 3px var(--ra-accent-subtle)}\n:is(.ra-chat,.ra-ui) .ra-sel:disabled{opacity:.55;cursor:not-allowed}\n:is(.ra-chat,.ra-ui) .ra-sel .ra-sell{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n:is(.ra-chat,.ra-ui) .ra-sel .ra-sell.ph{color:var(--ra-fg-muted)}\n:is(.ra-chat,.ra-ui) .ra-sel .ra-selc{flex:none;display:inline-flex;color:var(--ra-fg-muted);transition:transform .15s}\n:is(.ra-chat,.ra-ui) .ra-sel[aria-expanded=true] .ra-selc{transform:rotate(180deg)}\n:is(.ra-chat,.ra-ui) .ra-selp{position:absolute;z-index:30;display:flex;flex-direction:column;background:var(--ra-panel);border:1px solid var(--ra-border);border-radius:10px;box-shadow:var(--ra-shadow-md);padding:4px;box-sizing:border-box;overflow:hidden;font-size:13px}\n:is(.ra-chat,.ra-ui) .ra-selp .ra-self{flex:none;margin:2px 2px 4px;padding:6px 9px;font:inherit;font-size:13px;color:var(--ra-fg);background:var(--ra-bg);border:1px solid var(--ra-border);border-radius:6px;outline:0}\n:is(.ra-chat,.ra-ui) .ra-selp .ra-self:focus{border-color:var(--ra-accent)}\n:is(.ra-chat,.ra-ui) .ra-selp .ra-sellist{overflow-y:auto;min-height:0}\n:is(.ra-chat,.ra-ui) .ra-selo{display:flex;align-items:center;gap:6px;padding:6px 8px;border-radius:6px;cursor:pointer;color:var(--ra-fg)}\n:is(.ra-chat,.ra-ui) .ra-selo.act{background:var(--ra-muted)}\n:is(.ra-chat,.ra-ui) .ra-selo .ra-selt{flex:none;width:14px;display:inline-flex;color:var(--ra-accent-fg)}\n:is(.ra-chat,.ra-ui) .ra-selo .ra-selol{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n:is(.ra-chat,.ra-ui) .ra-selo.cur .ra-selol{font-weight:500}\n:is(.ra-chat,.ra-ui) .ra-selo .ra-selon{flex:none;font-size:11.5px;color:var(--ra-fg-muted);font-variant-numeric:tabular-nums}\n:is(.ra-chat,.ra-ui) .ra-selnone{padding:8px;color:var(--ra-fg-muted)}\n";
|