@runappsai/agent 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +162 -2
  3. package/dist/agent-core.umd.js +266 -0
  4. package/dist/agent.d.ts +222 -0
  5. package/dist/agent.js +1331 -0
  6. package/dist/agent.umd.js +732 -0
  7. package/dist/browser.d.ts +2 -0
  8. package/dist/browser.js +4 -0
  9. package/dist/chat-theme.d.ts +24 -0
  10. package/dist/chat-theme.js +101 -0
  11. package/dist/chat.d.ts +271 -0
  12. package/dist/chat.js +4097 -0
  13. package/dist/compaction.d.ts +48 -0
  14. package/dist/compaction.js +208 -0
  15. package/dist/completion.d.ts +29 -0
  16. package/dist/completion.js +88 -0
  17. package/dist/context.d.ts +44 -0
  18. package/dist/context.js +177 -0
  19. package/dist/debug-panel.d.ts +40 -0
  20. package/dist/debug-panel.js +262 -0
  21. package/dist/dialogs.d.ts +7 -0
  22. package/dist/dialogs.js +231 -0
  23. package/dist/directory-fs.d.ts +5 -0
  24. package/dist/directory-fs.js +118 -0
  25. package/dist/dom.d.ts +83 -0
  26. package/dist/dom.js +163 -0
  27. package/dist/edit.d.ts +22 -0
  28. package/dist/edit.js +133 -0
  29. package/dist/file-guard.d.ts +46 -0
  30. package/dist/file-guard.js +153 -0
  31. package/dist/file-tools.d.ts +16 -0
  32. package/dist/file-tools.js +339 -0
  33. package/dist/files-panel.d.ts +60 -0
  34. package/dist/files-panel.js +613 -0
  35. package/dist/index.cjs +4848 -0
  36. package/dist/index.d.ts +37 -0
  37. package/dist/index.js +44 -0
  38. package/dist/json-schema.d.ts +3 -0
  39. package/dist/json-schema.js +141 -0
  40. package/dist/llm.d.ts +95 -0
  41. package/dist/llm.js +5 -0
  42. package/dist/markdown.d.ts +4 -0
  43. package/dist/markdown.js +265 -0
  44. package/dist/mcp.d.ts +82 -0
  45. package/dist/mcp.js +325 -0
  46. package/dist/node.cjs +402 -0
  47. package/dist/node.d.ts +78 -0
  48. package/dist/node.js +432 -0
  49. package/dist/pdf.d.ts +52 -0
  50. package/dist/pdf.js +77 -0
  51. package/dist/provider.d.ts +135 -0
  52. package/dist/provider.js +181 -0
  53. package/dist/sandbox.d.ts +33 -0
  54. package/dist/sandbox.js +219 -0
  55. package/dist/select.d.ts +30 -0
  56. package/dist/select.js +185 -0
  57. package/dist/skill-zips.d.ts +28 -0
  58. package/dist/skill-zips.js +123 -0
  59. package/dist/skills.d.ts +20 -0
  60. package/dist/skills.js +111 -0
  61. package/dist/templates.d.ts +24 -0
  62. package/dist/templates.js +136 -0
  63. package/dist/tool.d.ts +28 -0
  64. package/dist/tool.js +102 -0
  65. package/dist/types.d.ts +571 -0
  66. package/dist/types.js +7 -0
  67. package/dist/ui.cjs +6246 -0
  68. package/dist/ui.d.ts +6 -0
  69. package/dist/ui.js +11 -0
  70. package/dist/vlist.d.ts +80 -0
  71. package/dist/vlist.js +277 -0
  72. package/dist/workspace.d.ts +343 -0
  73. package/dist/workspace.js +1203 -0
  74. package/dist/zip.d.ts +26 -0
  75. package/dist/zip.js +204 -0
  76. package/docs/agent.md +228 -0
  77. package/docs/chat-ui.md +307 -0
  78. package/docs/node.md +135 -0
  79. package/docs/providers.md +176 -0
  80. package/docs/reference.md +143 -0
  81. package/docs/skills.md +131 -0
  82. package/docs/tools.md +254 -0
  83. package/docs/workspace.md +198 -0
  84. package/package.json +59 -4
@@ -0,0 +1,262 @@
1
+ // The chat's debug panel (renderChat `debug: true`): what the agent did,
2
+ // as the harness app's DebugPanel shows it — the call chain (runs, turns,
3
+ // tool calls with arguments and results), the requests sent to the model
4
+ // with their responses, the raw event log, the context (system prompt,
5
+ // messages, limits, usage) and the tools declared to the model. It
6
+ // records from the moment the chat opens a session, background runs too.
7
+ import { h, I } from "./dom.js";
8
+ const MAX = { spans: 400, requests: 120, events: 600 };
9
+ const NOISY = new Set(["text_delta", "reasoning_delta", "tool_update"]);
10
+ function clock(ms) {
11
+ const d = new Date(ms);
12
+ return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}:${String(d.getSeconds()).padStart(2, "0")}`;
13
+ }
14
+ function json(v) {
15
+ try {
16
+ return JSON.stringify(v, null, 2) ?? "undefined";
17
+ }
18
+ catch {
19
+ return String(v);
20
+ }
21
+ }
22
+ const cap = (a, n) => { if (a.length > n)
23
+ a.splice(0, a.length - n); };
24
+ export function debugPanel(opts) {
25
+ const { t, root } = opts;
26
+ const traces = new WeakMap();
27
+ // One subscription per recorded agent, so a session the chat lets go of is not kept alive by its trace.
28
+ const subs = new Map();
29
+ let agent = null;
30
+ let visible = false;
31
+ let tab = "calls";
32
+ let filter = "";
33
+ let frame = null;
34
+ const el = h("div", "ra-fp ra-dp");
35
+ el.setAttribute("role", "complementary");
36
+ el.style.display = "none";
37
+ const head = h("div", "ra-fph");
38
+ const tabs = h("div", "ra-dtabs");
39
+ const closeBtn = h("button", "ra-ib");
40
+ closeBtn.type = "button";
41
+ closeBtn.innerHTML = I.x(14);
42
+ closeBtn.title = t.close;
43
+ closeBtn.setAttribute("aria-label", t.close);
44
+ closeBtn.addEventListener("click", () => close());
45
+ head.append(tabs, h("span", "ra-sp"), closeBtn);
46
+ const body = h("div", "ra-dbody");
47
+ el.append(head, body);
48
+ const TABS = [["calls", t.dCalls], ["requests", t.dRequests], ["events", t.dEvents], ["context", t.dContext], ["tools", t.dTools]];
49
+ const drawTabs = () => {
50
+ const tr = agent ? traces.get(agent) : undefined;
51
+ const count = { calls: tr?.spans.length ?? 0, requests: tr?.requests.length ?? 0 };
52
+ tabs.replaceChildren(...TABS.map(([k, label]) => {
53
+ const b = h("button", "ra-dtab" + (k === tab ? " on" : ""));
54
+ b.type = "button";
55
+ b.append(label);
56
+ if (count[k])
57
+ b.append(h("span", "ra-dcount", String(count[k])));
58
+ b.addEventListener("click", () => { tab = k; draw(); });
59
+ return b;
60
+ }));
61
+ };
62
+ /** A folded row: a head line, and a body built only when opened. */
63
+ const fold = (headEls, build) => {
64
+ const d = h("details", "ra-dfold");
65
+ const s = h("summary");
66
+ const chev = h("span", "ra-chev");
67
+ chev.innerHTML = I.chev(12);
68
+ s.append(chev, ...headEls);
69
+ d.append(s);
70
+ let built = false;
71
+ d.addEventListener("toggle", () => { if (d.open && !built) {
72
+ built = true;
73
+ const inner = h("div", "ra-dfb");
74
+ inner.append(...build());
75
+ d.append(inner);
76
+ } });
77
+ return d;
78
+ };
79
+ const pre = (v, cls = "") => { const p = h("pre", "ra-dpre " + cls); p.textContent = typeof v === "string" ? v : json(v); return p; };
80
+ const label = (text) => h("div", "ra-dlabel", text);
81
+ const muted = (text) => h("span", "ra-dmuted", text);
82
+ const mono = (text) => h("span", "ra-dmono", text);
83
+ const empty = (text) => h("div", "ra-fpe", text);
84
+ const status = (s) => {
85
+ const e = h("span", "ra-dst " + (s === "running" ? "run" : s === "ok" ? "ok" : "fail"));
86
+ if (s === "running")
87
+ e.append(h("span", "ra-spin"));
88
+ else
89
+ e.innerHTML = s === "ok" ? I.check(13) : I.xcircle(13);
90
+ return e;
91
+ };
92
+ const drawCalls = (tr) => {
93
+ if (!tr.spans.length)
94
+ return [empty(t.dNoCalls)];
95
+ // The chain: newest run first; within a run, its turns in order, each with its tool calls.
96
+ const out = [];
97
+ for (const runId of [...tr.runs].reverse()) {
98
+ const spans = tr.spans.filter((s) => s.runId === runId);
99
+ const reqs = tr.requests.filter((r) => r.runId === runId);
100
+ if (!spans.length && !reqs.length)
101
+ continue;
102
+ const run = h("div", "ra-drun");
103
+ run.append(h("div", "ra-drh", `${t.dRun} ${clock(reqs[0]?.at ?? spans[0]?.startedAt ?? Date.now())} · ${runId.slice(-4)}`));
104
+ const turns = [...new Set([...reqs.map((r) => r.turn), ...spans.map((s) => s.turn)])].sort((a, b) => a - b);
105
+ for (const turn of turns) {
106
+ const req = reqs.find((r) => r.turn === turn);
107
+ const line = h("div", "ra-dturn");
108
+ line.append(muted(t.dTurn.replace("{n}", String(turn))));
109
+ if (req)
110
+ line.append(mono(` · ${req.params.model || "default"}`), muted(req.durationMs !== undefined ? ` · ${Math.round(req.durationMs)}ms` : " · …"), req.error ? h("span", "ra-dst fail", ` ${req.error}`) : muted(req.finishReason ? ` · ${req.finishReason}` : ""));
111
+ run.append(line);
112
+ for (const s of spans.filter((x) => x.turn === turn)) {
113
+ run.append(fold([status(s.status), mono(s.name), muted(s.durationMs !== undefined ? `${Math.round(s.durationMs)}ms · ${clock(s.startedAt)}` : clock(s.startedAt))], () => [
114
+ h("div", "ra-dmuted", s.id), label(t.args), pre(s.args), ...(s.result !== undefined ? [label(t.result), pre(s.result)] : []),
115
+ ]));
116
+ }
117
+ }
118
+ out.push(run);
119
+ }
120
+ return out;
121
+ };
122
+ const drawRequests = (tr) => {
123
+ if (!tr.requests.length)
124
+ return [empty(t.dNoRequests)];
125
+ return [...tr.requests].reverse().map((r) => {
126
+ const p = r.params;
127
+ const u = r.usage;
128
+ const badge = h("span", "ra-dbadge " + (r.error ? "fail" : r.durationMs === undefined ? "" : "ok"), r.error ? "error" : r.durationMs === undefined ? "…" : (r.finishReason ?? "ok"));
129
+ return fold([badge, mono(p.model || "default"), muted(`${p.messages?.length ?? 0} msgs · ${p.tools?.length ?? 0} tools${u ? ` · ${u.prompt_tokens ?? 0}→${u.completion_tokens ?? 0} tok` : ""}${u?.total_cost ? ` · $${u.total_cost.toFixed(4)}` : ""}`), muted(` ${r.durationMs !== undefined ? `${Math.round(r.durationMs)}ms · ` : ""}${clock(r.at)}`)], () => [
130
+ label(t.dPayload), pre(r.params, "tall"), ...(r.message !== undefined || r.error ? [label(t.dResponse), pre(r.error ?? r.message)] : []), ...(u ? [pre(u)] : []),
131
+ ]);
132
+ });
133
+ };
134
+ const drawEvents = (tr) => {
135
+ const bar = h("div", "ra-dbar");
136
+ const input = h("input", "ra-field");
137
+ input.type = "text";
138
+ input.placeholder = t.dFilter;
139
+ input.value = filter;
140
+ input.addEventListener("input", () => { filter = input.value; schedule(); });
141
+ const clear = h("button", "ra-ib");
142
+ clear.type = "button";
143
+ clear.innerHTML = I.trash(13);
144
+ clear.title = t.dClear;
145
+ clear.setAttribute("aria-label", t.dClear);
146
+ clear.addEventListener("click", () => { tr.events.length = 0; tr.spans.length = 0; tr.requests.length = 0; tr.runs.length = 0; draw(); });
147
+ bar.append(input, clear);
148
+ const list = tr.events.filter((e) => !filter || e.name.includes(filter) || e.detail.includes(filter));
149
+ if (!list.length)
150
+ return [bar, empty(t.dNoEvents)];
151
+ return [bar, ...[...list].reverse().slice(0, 300).map((e) => fold([muted(clock(e.at)), mono(e.name), muted(e.detail)], () => [pre(e.data)]))];
152
+ };
153
+ const drawContext = (a) => {
154
+ const box = h("div", "ra-dctx");
155
+ const rows = h("div", "ra-dkv");
156
+ const add = (k, v) => { rows.append(h("span", "ra-dmuted", k), h("span", "ra-dmono", v)); };
157
+ const u = a.usage, msgs = a.messages;
158
+ add("session", a.id);
159
+ add("directory", a.workspace?.id ?? "—");
160
+ add("model", a.settings.model ?? "(default)");
161
+ add("messages", `${msgs.filter((m) => m.role === "user").length} user · ${msgs.filter((m) => m.role === "assistant").length} assistant · ${msgs.filter((m) => m.role === "tool").length} tool`);
162
+ add("usage", `${u.prompt_tokens} in · ${u.completion_tokens} out · ${u.calls} calls · $${u.total_cost.toFixed(4)}`);
163
+ const ctx = h("span", "ra-dmono", "…");
164
+ rows.append(h("span", "ra-dmuted", "context"), ctx);
165
+ void a.context().then((c) => { ctx.textContent = `${c.used} / ${c.window} (${((c.used / c.window) * 100).toFixed(2)}%)`; }).catch(() => { ctx.textContent = "—"; });
166
+ const sys = pre("…", "tall");
167
+ void a.systemPrompt().then((p) => { sys.textContent = p; }).catch((err) => { sys.textContent = String(err); });
168
+ box.append(rows, label(t.dSystem), sys, label(`${t.dMessages} (${msgs.length})`), pre(msgs, "tall"));
169
+ return [box];
170
+ };
171
+ const drawTools = (a) => a.tools.map((tool) => fold([mono(tool.name), muted(tool.destructive ? " destructive" : "")], () => [h("div", "ra-ddesc", tool.description ?? ""), pre(tool.parameters)]));
172
+ function draw() {
173
+ frame = null;
174
+ if (!visible)
175
+ return;
176
+ drawTabs();
177
+ if (!agent) {
178
+ body.replaceChildren();
179
+ return;
180
+ }
181
+ const tr = traces.get(agent);
182
+ // Keep the open folds and the scroll position across redraws: only the events and calls lists change.
183
+ const scroll = body.scrollTop;
184
+ const focusFilter = document.activeElement?.classList.contains("ra-field") && body.contains(document.activeElement);
185
+ const nodes = tab === "calls" ? drawCalls(tr) : tab === "requests" ? drawRequests(tr) : tab === "events" ? drawEvents(tr) : tab === "context" ? drawContext(agent) : drawTools(agent);
186
+ body.replaceChildren(...nodes);
187
+ body.scrollTop = scroll;
188
+ if (focusFilter) {
189
+ const f = body.querySelector(".ra-field");
190
+ f?.focus();
191
+ f?.setSelectionRange(f.value.length, f.value.length);
192
+ }
193
+ }
194
+ /** Redraw at most every 300 ms, and not the context/tools tabs (they redraw on demand) or a tab with a fold open. */
195
+ const schedule = () => {
196
+ if (!visible || frame)
197
+ return;
198
+ if ((tab === "context" || tab === "tools") || body.querySelector("details[open]")) {
199
+ drawTabs();
200
+ return;
201
+ }
202
+ frame = setTimeout(draw, 300);
203
+ };
204
+ const record = (a) => {
205
+ if (traces.has(a))
206
+ return;
207
+ const tr = { spans: [], requests: [], events: [], turn: new Map(), runs: [] };
208
+ traces.set(a, tr);
209
+ subs.set(a, a.on("*", (name, ev) => {
210
+ const e = (ev ?? {});
211
+ const runId = String(e.runId ?? "");
212
+ if (name === "run_start") {
213
+ tr.runs.push(runId);
214
+ cap(tr.runs, 60);
215
+ }
216
+ if (name === "turn_start")
217
+ tr.turn.set(runId, Number(e.turn) || 1);
218
+ if (name === "request") {
219
+ tr.requests.push({ runId, turn: Number(e.turn), at: Date.now(), params: e.params });
220
+ cap(tr.requests, MAX.requests);
221
+ }
222
+ if (name === "response") {
223
+ const r = [...tr.requests].reverse().find((x) => x.runId === runId && x.turn === Number(e.turn) && x.durationMs === undefined);
224
+ if (r)
225
+ Object.assign(r, { durationMs: e.durationMs, finishReason: e.finishReason, usage: e.usage, message: e.message, error: e.error });
226
+ }
227
+ if (name === "tool_start") {
228
+ tr.spans.push({ id: String(e.id), name: String(e.name), args: e.args, status: "running", startedAt: Date.now(), runId, turn: tr.turn.get(runId) ?? 1 });
229
+ cap(tr.spans, MAX.spans);
230
+ }
231
+ if (name === "tool_end") {
232
+ const s = [...tr.spans].reverse().find((x) => x.id === String(e.id));
233
+ if (s)
234
+ Object.assign(s, { status: String(e.status), result: e.result, durationMs: e.durationMs });
235
+ }
236
+ if (!NOISY.has(name)) {
237
+ const detail = name === "tool_start" || name === "tool_end" ? String(e.name ?? "") : name === "run_end" ? String(e.reason ?? "") : name === "response" ? String(e.error ?? e.finishReason ?? "") : "";
238
+ tr.events.push({ at: Date.now(), name, detail, data: name === "request" ? { runId, turn: e.turn, model: e.params?.model } : ev });
239
+ cap(tr.events, MAX.events);
240
+ }
241
+ if (a === agent)
242
+ schedule();
243
+ }));
244
+ };
245
+ const open = () => { visible = true; el.style.display = ""; root.classList.add("ra-files-open"); opts.onShow?.(true); draw(); };
246
+ function close() { if (!visible)
247
+ return; visible = false; el.style.display = "none"; root.classList.remove("ra-files-open"); opts.onShow?.(false); }
248
+ return {
249
+ el,
250
+ get visible() { return visible; },
251
+ open,
252
+ close,
253
+ toggle: () => (visible ? close() : open()),
254
+ setAgent(a) { record(a); agent = a; if (visible)
255
+ draw(); },
256
+ forget(a) { subs.get(a)?.(); subs.delete(a); traces.delete(a); if (agent === a)
257
+ agent = null; },
258
+ dispose() { for (const u of subs.values())
259
+ u(); subs.clear(); if (frame)
260
+ clearTimeout(frame); el.remove(); },
261
+ };
262
+ }
@@ -0,0 +1,7 @@
1
+ import type { AgentUI, Tool } from "./types.js";
2
+ /** `AgentUI` on plain `<dialog>` elements; outside a document it refuses everything. */
3
+ export declare function domUI(): AgentUI;
4
+ /** An `AgentUI` with no user: every question is declined. */
5
+ export declare function nullUI(): AgentUI;
6
+ /** The `ask_user` tool: up to three questions, each with options or free text. */
7
+ export declare function askUserTool(): Tool;
@@ -0,0 +1,231 @@
1
+ // The default dialogs (plain <dialog>s, light/dark, zh/en) and the
2
+ // `ask_user` tool. An app with its own design implements `AgentUI`
3
+ // itself and passes it to the agent.
4
+ import { defineTool } from "./tool.js";
5
+ function isZh() {
6
+ if (typeof document === "undefined")
7
+ return false;
8
+ return /^zh/i.test(document.documentElement.lang || (typeof navigator !== "undefined" ? navigator.language : "") || "");
9
+ }
10
+ const DIALOG_STYLE = [
11
+ "border:1px solid rgba(127,127,127,.3)", "border-radius:12px", "padding:18px 18px 14px", "width:min(420px,calc(100vw - 32px))",
12
+ "font:14px/1.45 -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif", "color-scheme:light dark",
13
+ "color:CanvasText", "background:Canvas", "box-shadow:0 12px 40px rgba(0,0,0,.25)",
14
+ ].join(";");
15
+ function el(tag, style, text) {
16
+ const e = document.createElement(tag);
17
+ if (style)
18
+ e.setAttribute("style", style);
19
+ if (text !== undefined)
20
+ e.textContent = text;
21
+ return e;
22
+ }
23
+ function button(label, primary, danger, onClick) {
24
+ const b = el("button");
25
+ b.type = "button";
26
+ b.textContent = label;
27
+ b.setAttribute("style", "font:inherit;padding:6px 14px;border-radius:8px;cursor:pointer;" + (primary
28
+ ? `border:0;background:${danger ? "#dc2626" : "#2563eb"};color:#fff`
29
+ : "border:1px solid rgba(127,127,127,.35);background:transparent;color:inherit"));
30
+ b.addEventListener("click", onClick);
31
+ return b;
32
+ }
33
+ function openDialog(build, signal, cancelValue = null) {
34
+ const d = el("dialog", DIALOG_STYLE);
35
+ let value = cancelValue;
36
+ const done = (v) => { value = v; d.close(); };
37
+ build(d, done);
38
+ if (signal?.aborted)
39
+ return Promise.resolve(cancelValue);
40
+ document.body.append(d);
41
+ return new Promise((resolve) => {
42
+ // A stopped run closes its question as if dismissed.
43
+ const onAbort = () => done(cancelValue);
44
+ signal?.addEventListener("abort", onAbort, { once: true });
45
+ d.addEventListener("close", () => { signal?.removeEventListener("abort", onAbort); d.remove(); resolve(value); }, { once: true });
46
+ d.showModal();
47
+ });
48
+ }
49
+ /** `AgentUI` on plain `<dialog>` elements; outside a document it refuses everything. */
50
+ export function domUI() {
51
+ if (typeof document === "undefined" || typeof HTMLDialogElement === "undefined")
52
+ return nullUI();
53
+ return {
54
+ async confirm(title, message, opts = {}) {
55
+ const zh = isZh();
56
+ const v = await openDialog((d, done) => {
57
+ d.append(el("div", "font-weight:600;font-size:15px;margin-bottom:6px", title));
58
+ if (message)
59
+ d.append(el("div", "white-space:pre-wrap;opacity:.8;font-size:13px;margin-bottom:14px;word-break:break-word", message));
60
+ if (opts.body) {
61
+ try {
62
+ d.append(opts.body());
63
+ }
64
+ catch (err) {
65
+ console.warn("agent: confirm body failed", err);
66
+ }
67
+ }
68
+ const row = el("div", "display:flex;justify-content:flex-end;gap:8px;margin-top:10px");
69
+ row.append(button(opts.cancel ?? (zh ? "取消" : "Cancel"), false, false, () => done(false)), button(opts.ok ?? (zh ? "确定" : "OK"), true, !!opts.danger, () => done(true)));
70
+ d.append(row);
71
+ queueMicrotask(() => row.lastElementChild.focus());
72
+ }, opts.signal, false);
73
+ return v === true;
74
+ },
75
+ async select(title, options, opts = {}) {
76
+ const zh = isZh();
77
+ const v = await openDialog((d, done) => {
78
+ d.append(el("div", "font-weight:600;font-size:15px;margin-bottom:6px", title));
79
+ if (opts.message)
80
+ d.append(el("div", "white-space:pre-wrap;opacity:.8;font-size:13px;margin-bottom:10px", opts.message));
81
+ const list = el("div", "display:flex;flex-direction:column;gap:6px;margin:8px 0 12px");
82
+ const name = "ra_sel_" + Math.random().toString(36).slice(2, 8);
83
+ const inputs = [];
84
+ const addOption = (o) => {
85
+ const label = el("label", "display:flex;gap:8px;align-items:flex-start;padding:8px 10px;border:1px solid rgba(127,127,127,.3);border-radius:8px;cursor:pointer");
86
+ const input = el("input");
87
+ input.type = opts.multi ? "checkbox" : "radio";
88
+ input.name = name;
89
+ input.value = o.value;
90
+ input.setAttribute("style", "margin-top:3px");
91
+ inputs.push(input);
92
+ const text = el("div");
93
+ text.append(el("div", "", o.label ?? o.value));
94
+ if (o.description)
95
+ text.append(el("div", "opacity:.7;font-size:12px", o.description));
96
+ label.append(input, text);
97
+ list.append(label);
98
+ };
99
+ options.forEach(addOption);
100
+ let other = null;
101
+ if (opts.allowOther) {
102
+ addOption({ value: "__other__", label: zh ? "其他…" : "Other…" });
103
+ other = el("input", "font:inherit;padding:6px 8px;border:1px solid rgba(127,127,127,.35);border-radius:8px;background:transparent;color:inherit;width:100%;box-sizing:border-box;margin-top:-4px");
104
+ other.placeholder = zh ? "请输入" : "Type your answer";
105
+ other.addEventListener("focus", () => { const o = inputs.find((i) => i.value === "__other__"); if (o)
106
+ o.checked = true; });
107
+ list.append(other);
108
+ }
109
+ d.append(list);
110
+ const row = el("div", "display:flex;justify-content:flex-end;gap:8px");
111
+ row.append(button(zh ? "取消" : "Cancel", false, false, () => done(null)), button(zh ? "确定" : "OK", true, false, () => {
112
+ const picked = inputs.filter((i) => i.checked).map((i) => (i.value === "__other__" ? (other?.value.trim() || "") : i.value)).filter(Boolean);
113
+ if (!picked.length)
114
+ return;
115
+ done(picked);
116
+ }));
117
+ d.append(row);
118
+ queueMicrotask(() => inputs[0]?.focus());
119
+ }, opts.signal, null);
120
+ return Array.isArray(v) ? v : null;
121
+ },
122
+ async input(title, opts = {}) {
123
+ const zh = isZh();
124
+ const v = await openDialog((d, done) => {
125
+ d.append(el("div", "font-weight:600;font-size:15px;margin-bottom:6px", title));
126
+ if (opts.message)
127
+ d.append(el("div", "white-space:pre-wrap;opacity:.8;font-size:13px;margin-bottom:10px", opts.message));
128
+ const field = el(opts.multiline ? "textarea" : "input", "font:inherit;padding:8px 10px;border:1px solid rgba(127,127,127,.35);border-radius:8px;background:transparent;color:inherit;width:100%;box-sizing:border-box;margin:6px 0 12px" + (opts.multiline ? ";min-height:96px;resize:vertical" : ""));
129
+ if (opts.placeholder)
130
+ field.placeholder = opts.placeholder;
131
+ if (opts.initial)
132
+ field.value = opts.initial;
133
+ if (!opts.multiline)
134
+ field.addEventListener("keydown", (e) => { const k = e; if (k.key === "Enter" && !k.isComposing && k.keyCode !== 229)
135
+ done(field.value); });
136
+ d.append(field);
137
+ const row = el("div", "display:flex;justify-content:flex-end;gap:8px");
138
+ row.append(button(zh ? "取消" : "Cancel", false, false, () => done(null)), button(zh ? "确定" : "OK", true, false, () => done(field.value)));
139
+ d.append(row);
140
+ queueMicrotask(() => field.focus());
141
+ }, opts.signal, null);
142
+ return typeof v === "string" ? v : null;
143
+ },
144
+ notify(message, level = "info") {
145
+ const host = el("div", [
146
+ "position:fixed", "right:16px", "bottom:16px", "z-index:2147483647", "max-width:min(360px,calc(100vw - 32px))",
147
+ "padding:10px 14px", "border-radius:10px", "font:13px/1.45 -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif",
148
+ "color:#fff", `background:${level === "error" ? "#dc2626" : level === "warning" ? "#d97706" : "#111827"}`,
149
+ "box-shadow:0 8px 24px rgba(0,0,0,.25)", "white-space:pre-wrap", "word-break:break-word",
150
+ ].join(";"), message);
151
+ document.body.append(host);
152
+ setTimeout(() => host.remove(), level === "error" ? 8000 : 4000);
153
+ },
154
+ };
155
+ }
156
+ /** An `AgentUI` with no user: every question is declined. */
157
+ export function nullUI() {
158
+ return {
159
+ confirm: async () => false,
160
+ select: async () => null,
161
+ input: async () => null,
162
+ notify: (message, level = "info") => {
163
+ // eslint-disable-next-line no-console
164
+ (level === "error" ? console.error : console.log)(`[agent] ${message}`);
165
+ },
166
+ };
167
+ }
168
+ /** The `ask_user` tool: up to three questions, each with options or free text. */
169
+ export function askUserTool() {
170
+ return defineTool({
171
+ name: "ask_user",
172
+ description: "Ask the user one to three questions when the request is genuinely ambiguous and the answer changes what you would do. Give 2–5 short options when there are natural choices (allow_other adds a free-text choice); leave options out for a free-text answer. Do not ask what you can reasonably decide yourself.",
173
+ parameters: {
174
+ type: "object",
175
+ properties: {
176
+ questions: {
177
+ type: "array",
178
+ minItems: 1,
179
+ maxItems: 3,
180
+ items: {
181
+ type: "object",
182
+ properties: {
183
+ question: { type: "string", minLength: 1 },
184
+ options: {
185
+ type: "array",
186
+ minItems: 2,
187
+ maxItems: 5,
188
+ items: {
189
+ type: "object",
190
+ properties: { label: { type: "string", minLength: 1 }, description: { type: "string" } },
191
+ required: ["label"],
192
+ additionalProperties: false,
193
+ },
194
+ },
195
+ allow_other: { type: "boolean" },
196
+ multi: { type: "boolean" },
197
+ },
198
+ required: ["question"],
199
+ additionalProperties: false,
200
+ },
201
+ },
202
+ },
203
+ required: ["questions"],
204
+ additionalProperties: false,
205
+ },
206
+ async execute({ questions }, ctx) {
207
+ const answers = [];
208
+ for (const q of questions) {
209
+ ctx.signal.throwIfAborted();
210
+ let answer;
211
+ if (q.options && q.options.length) {
212
+ const picked = await ctx.ui.select(q.question, q.options.map((o) => ({ value: o.label, label: o.label, description: o.description })), { multi: !!q.multi, allowOther: q.allow_other !== false, signal: ctx.signal });
213
+ answer = picked === null ? null : q.multi ? picked : (picked[0] ?? null);
214
+ }
215
+ else {
216
+ answer = await ctx.ui.input(q.question, { multiline: true, signal: ctx.signal });
217
+ }
218
+ answers.push({ question: q.question, answer });
219
+ if (answer === null)
220
+ break;
221
+ }
222
+ const unanswered = answers.some((a) => a.answer === null) || answers.length < questions.length;
223
+ return {
224
+ content: unanswered
225
+ ? "The user dismissed the question without answering. Proceed with a reasonable default and say which you chose, or stop if you cannot."
226
+ : answers.map((a) => `Q: ${a.question}\nA: ${Array.isArray(a.answer) ? a.answer.join(", ") : a.answer}`).join("\n\n"),
227
+ details: { answers },
228
+ };
229
+ },
230
+ });
231
+ }
@@ -0,0 +1,5 @@
1
+ import { type AgentFS } from "./index.js";
2
+ export declare function directoryFS(handle: FileSystemDirectoryHandle, opts?: {
3
+ description?: string;
4
+ readonly?: boolean;
5
+ }): AgentFS;
@@ -0,0 +1,118 @@
1
+ // `directoryFS(handle)`: an `AgentFS` over a browser directory handle —
2
+ // a local folder the user picked with `showDirectoryPicker()` (Chromium),
3
+ // or the origin private file system (`navigator.storage.getDirectory()`).
4
+ // Used as a workspace's `dir`, the agent works directly in that folder.
5
+ import { decodeText, guessType, normalizePath } from "./index.js";
6
+ const TEXT_TYPES = /^(text\/|application\/(json|xml|yaml|javascript|x-sh))/;
7
+ function segments(path) {
8
+ const p = normalizePath(path);
9
+ return p === "/" ? [] : p.slice(1).split("/");
10
+ }
11
+ function notFound(path) {
12
+ return new Error(`No such file: ${normalizePath(path)}`);
13
+ }
14
+ export function directoryFS(handle, opts = {}) {
15
+ const dir = async (segs, create = false) => {
16
+ let cur = handle;
17
+ for (const s of segs)
18
+ cur = await cur.getDirectoryHandle(s, { create });
19
+ return cur;
20
+ };
21
+ const fileHandle = async (path, create = false) => {
22
+ const segs = segments(path);
23
+ if (!segs.length)
24
+ throw new Error(`${normalizePath(path)} is a folder, not a file`);
25
+ const parent = await dir(segs.slice(0, -1), create);
26
+ return parent.getFileHandle(segs[segs.length - 1], { create });
27
+ };
28
+ const statOf = async (path, h) => {
29
+ const f = await h.getFile();
30
+ return { path: normalizePath(path), size: f.size, contentType: f.type || guessType(path, new Uint8Array()), mtime: f.lastModified };
31
+ };
32
+ const walk = async (d, prefix, out) => {
33
+ for await (const [name, entry] of d) {
34
+ const path = `${prefix}/${name}`;
35
+ if (entry.kind === "directory")
36
+ await walk(entry, path, out);
37
+ else
38
+ out.push(await statOf(path, entry));
39
+ }
40
+ };
41
+ const fs = {
42
+ description: opts.description ?? `the local folder "${handle.name}"`,
43
+ async list(prefix) {
44
+ const out = [];
45
+ const segs = segments(prefix);
46
+ let d;
47
+ try {
48
+ d = await dir(segs);
49
+ }
50
+ catch {
51
+ // A file path lists itself; anything else is empty.
52
+ try {
53
+ const h = await fileHandle(prefix);
54
+ return [await statOf(prefix, h)];
55
+ }
56
+ catch {
57
+ return out;
58
+ }
59
+ }
60
+ await walk(d, segs.length ? "/" + segs.join("/") : "", out);
61
+ return out;
62
+ },
63
+ async stat(path) {
64
+ try {
65
+ return await statOf(path, await fileHandle(path));
66
+ }
67
+ catch {
68
+ return null;
69
+ }
70
+ },
71
+ async read(path) {
72
+ let h;
73
+ try {
74
+ h = await fileHandle(path);
75
+ }
76
+ catch {
77
+ throw notFound(path);
78
+ }
79
+ const f = await h.getFile();
80
+ const bytes = new Uint8Array(await f.arrayBuffer());
81
+ const type = f.type || guessType(path, bytes);
82
+ if (TEXT_TYPES.test(type)) {
83
+ const text = decodeText(bytes);
84
+ if (text !== null)
85
+ return text;
86
+ }
87
+ return bytes;
88
+ },
89
+ };
90
+ if (!opts.readonly) {
91
+ fs.write = async (path, content) => {
92
+ const h = await fileHandle(path, true);
93
+ const w = await h.createWritable();
94
+ try {
95
+ await w.write(typeof content === "string" ? content : content);
96
+ }
97
+ finally {
98
+ await w.close();
99
+ }
100
+ };
101
+ fs.delete = async (path) => {
102
+ const segs = segments(path);
103
+ if (!segs.length)
104
+ throw new Error("Cannot delete /");
105
+ const parent = await dir(segs.slice(0, -1));
106
+ try {
107
+ await parent.removeEntry(segs[segs.length - 1], { recursive: true });
108
+ }
109
+ catch (err) {
110
+ // Only a missing entry is "no such file"; a permission or lock error says what it is.
111
+ if (err?.name === "NotFoundError")
112
+ throw notFound(path);
113
+ throw new Error(`${path}: ${err?.message ?? String(err)}`);
114
+ }
115
+ };
116
+ }
117
+ return fs;
118
+ }