@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,1203 @@
1
+ // Workspace: the directory the agent works in — a POSIX-style tree kept
2
+ // in IndexedDB (one database per app; `id` names a directory in it, so a
3
+ // chat can give every session its own), or a directory the app
4
+ // provides (`dir`: a local folder through the File System Access API,
5
+ // any `AgentFS`), plus mount points an app fills with its own files (its
6
+ // document, a cloud folder). Skills: `<skillsDir>` (default
7
+ // `/.agent/skills`) is virtual and read-only, generated in memory when the
8
+ // workspace opens and whenever the user's skills change — one folder per
9
+ // skill, from the app's zips (`skills` option: URLs or Blobs, never
10
+ // stored) and from `<userSkillsDir>` (default `/skills`), the user's own
11
+ // skills shared by every directory of the app: zips (uploaded, read in
12
+ // place, never unpacked) and folders (written by the user or the agent).
13
+ // The file tools in file-tools.ts and the sandbox's `fs` work on it.
14
+ import { toProvider } from "./provider.js";
15
+ import { readZipEntry, MAX_ZIP_BYTES } from "./zip.js";
16
+ import { parseSkill } from "./skills.js";
17
+ import { applyEdits } from "./edit.js";
18
+ import { summaryOf } from "./compaction.js";
19
+ import { cachedSkillZip, parseSkillZip, skillFoldersOf, skillZipFS, subFS, zipFiles } from "./skill-zips.js";
20
+ import { extractPdfText, formatPdfText, isPdf } from "./pdf.js";
21
+ /** Where a workspace keeps its skills unless `skillsDir` says otherwise. */
22
+ export const DEFAULT_SKILLS_DIR = "/.agent/skills";
23
+ /** @deprecated use DEFAULT_SKILLS_DIR / `workspace.skillsDir` */
24
+ export const SKILLS_ROOT = DEFAULT_SKILLS_DIR;
25
+ const DB_PREFIX = "__runapps_agent_ws";
26
+ /** Where the user's skills live unless `userSkillsDir` says otherwise. */
27
+ export const DEFAULT_USER_SKILLS_DIR = "/skills";
28
+ /** The app's shared skills (the user's skills folder): a space no directory id can be. */
29
+ const LIB_SPACE = "\u0000skills";
30
+ const isLazy = (s) => typeof s === "object" && !(s instanceof Uint8Array) && typeof s.load === "function";
31
+ /** A LazySkill's zip, once asked for (per page: every workspace shares it). */
32
+ const lazyLoads = new WeakMap();
33
+ /** The app's zips, per page: a URL is fetched once (the browser's HTTP cache does the rest). */
34
+ const builtinFetches = new Map();
35
+ const objectIds = new WeakMap();
36
+ let nextObjectId = 1;
37
+ const idOf = (o) => { let id = objectIds.get(o); if (!id) {
38
+ id = nextObjectId++;
39
+ objectIds.set(o, id);
40
+ } return id; };
41
+ /** A store's files or one file, without their content when the store can. */
42
+ const statsOf = async (store, prefix) => (store.listStats ? store.listStats(prefix) : (await store.list(prefix)).map(statOf));
43
+ const statIn = async (store, p) => {
44
+ if (store.stat)
45
+ return store.stat(p);
46
+ const rec = await store.get(p);
47
+ return rec ? statOf(rec) : null;
48
+ };
49
+ export class Workspace {
50
+ /** The directory's id. */
51
+ id;
52
+ /** The app's database (shared by every id of the app). */
53
+ dbName;
54
+ /** The generated, read-only skills folder (`<skillsDir>/<name>/SKILL.md`). */
55
+ skillsDir;
56
+ /** The user's skills folder, shared by the app's directories (null: none). */
57
+ userSkillsDir;
58
+ /** The folder the directory lives in when opened with `dir` (null: IndexedDB). */
59
+ root;
60
+ store;
61
+ /** The user's skills folder (one tree for the whole app). */
62
+ lib;
63
+ mounts = new Map();
64
+ /** The skills in `skillsDir`, by folder name. */
65
+ skillViews = new Map();
66
+ /** The app's zips, loaded at open. */
67
+ builtins = [];
68
+ /** The app's skills that load on first use. */
69
+ lazySkills = [];
70
+ /** The `skills` option resolved (a function called): what loadBuiltins worked from. */
71
+ resolvedSources = [];
72
+ changeListeners = new Set();
73
+ channel;
74
+ sources;
75
+ /** Reads `files:` skills sources (the provider's own storage). */
76
+ provider;
77
+ inflate;
78
+ fetchFn;
79
+ /** Part of the page cache key for the app's zips: a host's own fetch is its own cache. */
80
+ fetchKey;
81
+ idb;
82
+ storeFactory;
83
+ skillCache = null;
84
+ opened = null;
85
+ /**
86
+ * The agent sessions saved in the app's database — every directory's,
87
+ * each summary naming its `workspace` (the directory id it was saved
88
+ * from), so a chat that gives each session its own directory can list
89
+ * them all from any one.
90
+ */
91
+ sessions = {
92
+ list: async () => {
93
+ await this.ready();
94
+ return (await this.store.listSessions())
95
+ .map((d) => ({ id: d.id ?? "", title: d.title && !isMachineTitle(d.title) ? d.title : titleOf(d), model: d.model, messages: d.messages.length, createdAt: d.createdAt ?? d.savedAt, savedAt: d.savedAt, workspace: d.space }))
96
+ .sort((a, b) => b.savedAt - a.savedAt);
97
+ },
98
+ // This directory's session of that id, else the session in the directory named after it (the chat
99
+ // gives each session one); never another directory's session that merely shares the id.
100
+ get: async (id) => {
101
+ await this.ready();
102
+ return (await this.store.getSession(this.id, id)) ?? (id !== this.id ? await this.store.getSession(id, id) : undefined) ?? null;
103
+ },
104
+ save: async (data) => {
105
+ await this.ready();
106
+ if (!data.id)
107
+ throw new Error("a session needs an id to be saved");
108
+ await this.store.putSession({ ...data, space: this.id });
109
+ },
110
+ delete: async (id, space) => {
111
+ await this.ready();
112
+ const where = space
113
+ ?? ((await this.store.getSession(this.id, id)) ? this.id
114
+ : (await this.store.getSession(id, id)) ? id
115
+ : (await this.store.listSessions()).find((d) => d.id === id)?.space ?? this.id);
116
+ await this.store.deleteSession(where, id);
117
+ // A session saved from a directory of its own id (the chat gives each session one) takes the directory with it.
118
+ if (where === id && id !== this.id)
119
+ await this.store.clear(id);
120
+ },
121
+ clear: async () => {
122
+ await this.ready();
123
+ for (const d of await this.store.listSessions())
124
+ if (d.id)
125
+ await this.sessions.delete(d.id, d.space ?? this.id);
126
+ },
127
+ };
128
+ constructor(provider, opts = {}) {
129
+ this.provider = provider ? toProvider(provider) : null;
130
+ this.id = opts.id || "default";
131
+ this.dbName = `${DB_PREFIX}:${opts.project || this.provider?.name || "app"}`;
132
+ this.sources = typeof opts.skills === "function" ? opts.skills : opts.skills ? [].concat(opts.skills) : [];
133
+ this.skillsDir = normalizePath(opts.skillsDir || DEFAULT_SKILLS_DIR);
134
+ if (this.skillsDir === "/")
135
+ throw new Error("skillsDir cannot be /");
136
+ this.userSkillsDir = opts.userSkills === false || opts.userSkillsDir === false ? null : normalizePath(opts.userSkillsDir || DEFAULT_USER_SKILLS_DIR);
137
+ const nested = (a, b) => a === b || a.startsWith(b + "/") || b.startsWith(a + "/");
138
+ if (this.userSkillsDir === "/" || (this.userSkillsDir && nested(this.userSkillsDir, this.skillsDir)))
139
+ throw new Error("userSkillsDir must be its own folder, apart from skillsDir");
140
+ this.root = opts.dir ?? null;
141
+ this.inflate = opts.inflate;
142
+ this.fetchFn = opts.fetch ?? ((...a) => fetch(...a));
143
+ this.fetchKey = opts.fetch ? `f${idOf(opts.fetch)}` : "";
144
+ this.idb = opts.indexedDB !== undefined ? opts.indexedDB : (typeof indexedDB !== "undefined" ? indexedDB : null);
145
+ this.storeFactory = opts.store ?? null;
146
+ }
147
+ /** Opens the database and brings the skills layer up to date. */
148
+ static async open(provider, opts = {}) {
149
+ const ws = new Workspace(provider, opts);
150
+ await ws.ready();
151
+ return ws;
152
+ }
153
+ /** Resolves once the database is open and skills are unpacked (idempotent). */
154
+ ready() {
155
+ if (!this.opened) {
156
+ const opening = (async () => {
157
+ const open = (space) => this.storeFactory ? this.storeFactory.open(this.dbName, space) : this.idb ? openIDBStore(this.idb, this.dbName, space) : Promise.resolve(memoryStore(this.dbName, space));
158
+ this.store = await open(this.id);
159
+ this.lib = await open(LIB_SPACE);
160
+ this.openChannel();
161
+ await withLock(`${this.dbName}:skills-migrate`, () => this.migrateSkills());
162
+ this.builtins = await this.loadBuiltins();
163
+ this.mounts.set(this.skillsDir, this.skillsFS());
164
+ if (this.userSkillsDir)
165
+ this.mounts.set(this.userSkillsDir, this.userFS());
166
+ await this.rebuildSkills();
167
+ })();
168
+ this.opened = opening;
169
+ // A failed open (blocked, quota, a skills fetch) is tried again next time instead of failing for good.
170
+ opening.catch(() => { if (this.opened === opening)
171
+ this.opened = null; });
172
+ }
173
+ return this.opened;
174
+ }
175
+ /**
176
+ * Releases the database connection and the change channel. The
177
+ * workspace stays usable: the next call opens them again. A host that
178
+ * makes a workspace per session closes the ones it no longer shows.
179
+ */
180
+ close() {
181
+ try {
182
+ this.channel?.close();
183
+ }
184
+ catch { /* closed */ }
185
+ this.channel = undefined;
186
+ if (this.opened) {
187
+ const o = this.opened;
188
+ this.opened = null;
189
+ void o.then(() => { this.store.close(); this.lib.close(); }, () => undefined);
190
+ }
191
+ }
192
+ /* ---------------- mounts ---------------- */
193
+ /** Exposes `fs` under `prefix` (e.g. `/doc`); its paths are relative to the prefix. */
194
+ mount(prefix, fs) {
195
+ const p = normalizePath(prefix);
196
+ if (p === "/")
197
+ throw new Error("cannot mount at / (open the workspace with `dir` instead)");
198
+ this.mounts.set(p, fs);
199
+ }
200
+ unmount(prefix) {
201
+ this.mounts.delete(normalizePath(prefix));
202
+ }
203
+ /**
204
+ * Called for every write and delete in this directory, from any code in
205
+ * this page and from other tabs of the app (`remote: true`, relayed over
206
+ * a BroadcastChannel). Returns the unsubscribe function. A files view
207
+ * refreshes on this instead of guessing when the agent wrote something.
208
+ */
209
+ onChange(fn) {
210
+ this.changeListeners.add(fn);
211
+ this.openChannel();
212
+ return () => { this.changeListeners.delete(fn); };
213
+ }
214
+ openChannel() {
215
+ if (this.channel !== undefined)
216
+ return;
217
+ if (typeof BroadcastChannel === "undefined") {
218
+ this.channel = null;
219
+ return;
220
+ }
221
+ try {
222
+ const ch = new BroadcastChannel(`${this.dbName}:changes`);
223
+ ch.onmessage = (ev) => {
224
+ const m = ev.data;
225
+ // The user's skills changed (any tab, any directory): regenerate the skills folder.
226
+ if (m?.userSkills) {
227
+ if (this.lib && this.userSkillsDir && typeof m.path === "string" && (m.kind === "write" || m.kind === "delete")) {
228
+ const path = this.userSkillsDir + m.path, kind = m.kind;
229
+ void this.rebuildSkills().then(() => { this.emitChange(path, kind, true); this.emitChange(this.skillsDir, "write", true); }).catch(() => undefined);
230
+ }
231
+ return;
232
+ }
233
+ if (m && m.space === this.id && typeof m.path === "string" && (m.kind === "write" || m.kind === "delete"))
234
+ this.emitChange(m.path, m.kind, true);
235
+ };
236
+ ch.unref?.();
237
+ this.channel = ch;
238
+ }
239
+ catch {
240
+ this.channel = null;
241
+ }
242
+ }
243
+ emitChange(path, kind, remote = false) {
244
+ if (remote && (path === "/" || this.inSkills(path)))
245
+ this.skillCache = null;
246
+ if (!remote) {
247
+ this.openChannel();
248
+ try {
249
+ this.channel?.postMessage({ space: this.id, path, kind });
250
+ }
251
+ catch { /* channel closed */ }
252
+ }
253
+ if (!this.changeListeners.size)
254
+ return;
255
+ const c = { path, kind, remote };
256
+ for (const fn of this.changeListeners) {
257
+ try {
258
+ fn(c);
259
+ }
260
+ catch (err) {
261
+ console.warn("agent: onChange listener failed", err);
262
+ }
263
+ }
264
+ }
265
+ /** What the system prompt says about the tree. */
266
+ describe() {
267
+ const lines = [
268
+ this.root
269
+ ? `/ — ${this.root.description || "the working directory"}${this.root.write ? "" : " (read-only)"}.`
270
+ : "/ — the working directory; it persists between conversations.",
271
+ `${this.skillsDir}/ — skills, one folder per skill with a SKILL.md (read-only, generated from the app's skills${this.userSkillsDir ? ` and ${this.userSkillsDir}` : ""}).`,
272
+ ];
273
+ if (this.userSkillsDir)
274
+ lines.push(`${this.userSkillsDir}/ — the user's skills, shared by every conversation: skill zips and skill folders. To add a skill, write ${this.userSkillsDir}/<name>/SKILL.md (frontmatter with name and description); it appears under ${this.skillsDir}/ at once.`);
275
+ for (const [p, fs] of this.mounts)
276
+ if (p !== this.skillsDir && p !== this.userSkillsDir)
277
+ lines.push(`${p}/ — ${fs.description || "app files"}${fs.write ? "" : " (read-only)"}.`);
278
+ return lines.join("\n");
279
+ }
280
+ /** The mount (or the root directory) that serves `path`; null means the IndexedDB tree. */
281
+ route(path) {
282
+ // The longest mount point that holds the path.
283
+ let best = null;
284
+ for (const prefix of this.mounts.keys()) {
285
+ if ((path === prefix || path.startsWith(prefix + "/")) && (!best || prefix.length > best.length))
286
+ best = prefix;
287
+ }
288
+ if (best)
289
+ return { fs: this.mounts.get(best), rel: path.slice(best.length) || "/", prefix: best };
290
+ return this.root ? { fs: this.root, rel: path, prefix: "" } : null;
291
+ }
292
+ inSkills(path) {
293
+ return path === this.skillsDir || path.startsWith(this.skillsDir + "/");
294
+ }
295
+ /* ---------------- raw access to the tree (root dir or IndexedDB) ---------------- */
296
+ async putFile(path, data, contentType, layer, source) {
297
+ if (this.inSkills(path))
298
+ this.skillCache = null;
299
+ if (this.root) {
300
+ if (!this.root.write)
301
+ throw new Error("/ is read-only");
302
+ await this.root.write(path, data, contentType ?? guessType(path, data));
303
+ this.emitChange(path, "write");
304
+ return;
305
+ }
306
+ await this.store.put({ path, data, contentType: contentType ?? guessType(path, data), mtime: Date.now(), layer, source });
307
+ this.emitChange(path, "write");
308
+ }
309
+ async rmFile(path) {
310
+ if (this.inSkills(path))
311
+ this.skillCache = null;
312
+ if (this.root) {
313
+ if (!this.root.delete)
314
+ throw new Error("/ is read-only");
315
+ await this.root.delete(path);
316
+ this.emitChange(path, "delete");
317
+ return;
318
+ }
319
+ await this.store.delete(path);
320
+ this.emitChange(path, "delete");
321
+ }
322
+ /* ---------------- files ---------------- */
323
+ async list(prefix = "/") {
324
+ await this.ready();
325
+ const p = normalizePath(prefix);
326
+ const out = [];
327
+ const r = this.route(p);
328
+ if (r && r.prefix) {
329
+ for (const f of await r.fs.list(r.rel))
330
+ out.push({ ...f, path: r.prefix + normalizePath(f.path) });
331
+ return out.sort((a, b) => a.path.localeCompare(b.path));
332
+ }
333
+ const own = this.root
334
+ ? (await this.root.list(p)).map((f) => ({ ...f, path: normalizePath(f.path) }))
335
+ : await statsOf(this.store, p === "/" ? "/" : p + "/");
336
+ for (const f of own) {
337
+ if (this.route(f.path)?.prefix)
338
+ continue; // shadowed by a mount
339
+ out.push(f);
340
+ }
341
+ for (const [mp, fs] of this.mounts) {
342
+ if (p === "/" || mp.startsWith(p + "/")) {
343
+ for (const f of await fs.list("/"))
344
+ out.push({ ...f, path: mp + normalizePath(f.path) });
345
+ }
346
+ }
347
+ return out.sort((a, b) => a.path.localeCompare(b.path));
348
+ }
349
+ async stat(path) {
350
+ await this.ready();
351
+ const p = normalizePath(path);
352
+ const r = this.route(p);
353
+ if (r) {
354
+ if (r.fs.stat) {
355
+ const s = await r.fs.stat(r.rel);
356
+ return s ? { ...s, path: p } : null;
357
+ }
358
+ const f = (await r.fs.list(r.rel)).find((x) => normalizePath(x.path) === normalizePath(r.rel));
359
+ return f ? { ...f, path: p } : null;
360
+ }
361
+ return statIn(this.store, p);
362
+ }
363
+ async exists(path) {
364
+ return (await this.stat(path)) !== null;
365
+ }
366
+ async read(path) {
367
+ await this.ready();
368
+ const p = normalizePath(path);
369
+ const r = this.route(p);
370
+ if (r) {
371
+ try {
372
+ const data = await r.fs.read(r.rel);
373
+ return { data, size: sizeOf(data), contentType: guessType(p, data) };
374
+ }
375
+ catch (err) {
376
+ throw new Error(await this.missing(p, err));
377
+ }
378
+ }
379
+ const rec = await this.store.get(p);
380
+ if (!rec)
381
+ throw new Error(await this.missing(p));
382
+ return { data: rec.data, size: sizeOf(rec.data), contentType: rec.contentType };
383
+ }
384
+ /** Whether `path` has files under it (a folder, in a tree that stores only files). */
385
+ async isFolder(path) {
386
+ const p = normalizePath(path);
387
+ if (p === "/")
388
+ return true;
389
+ if (this.mounts.has(p))
390
+ return true;
391
+ return (await this.list(p)).some((f) => f.path !== p);
392
+ }
393
+ async missing(p, cause) {
394
+ if (await this.isFolder(p))
395
+ return `${p} is a folder, not a file; use list_files to see what it holds`;
396
+ const msg = cause instanceof Error ? cause.message : "";
397
+ return /no such file/i.test(msg) || !msg ? `No such file: ${p}` : `${p}: ${msg}`;
398
+ }
399
+ /** The file as text; throws for binary files. */
400
+ async readText(path) {
401
+ const { data } = await this.read(path);
402
+ if (typeof data === "string")
403
+ return data;
404
+ const text = decodeText(data);
405
+ if (text === null)
406
+ throw new Error(`${normalizePath(path)} is a binary file (${data.byteLength} bytes)`);
407
+ return text;
408
+ }
409
+ /**
410
+ * A file as text for reading: text files as they are, a PDF as the text
411
+ * of its pages (pdf.js, loaded on first use; the result is cached with
412
+ * the directory and redone when the file changes); null for other
413
+ * binary files.
414
+ */
415
+ async readAsText(path) {
416
+ const p = normalizePath(path);
417
+ const { data, size, contentType } = await this.read(p);
418
+ if (typeof data === "string")
419
+ return { text: data, kind: "text" };
420
+ if (isPdf(p, contentType, data)) {
421
+ const st = await this.stat(p);
422
+ const key = `pdftext:${p}`;
423
+ const cached = await this.getData(key).catch(() => undefined);
424
+ if (cached && cached.size === size && cached.mtime === st?.mtime)
425
+ return { text: cached.text, kind: "pdf" };
426
+ const text = formatPdfText(p, await extractPdfText(data));
427
+ await this.putData(key, { size, mtime: st?.mtime, text }).catch(() => undefined);
428
+ return { text, kind: "pdf" };
429
+ }
430
+ const text = decodeText(data);
431
+ return text === null ? null : { text, kind: "text" };
432
+ }
433
+ async write(path, content, contentType) {
434
+ await this.ready();
435
+ const p = normalizePath(path);
436
+ if (p === "/")
437
+ throw new Error("Cannot write to /");
438
+ const r = this.route(p);
439
+ if (r && r.prefix) {
440
+ if (!r.fs.write)
441
+ throw new Error(`${r.prefix} is read-only`);
442
+ await r.fs.write(r.rel, content, contentType);
443
+ this.emitChange(p, "write");
444
+ return;
445
+ }
446
+ await this.putFile(p, content, contentType, "work");
447
+ }
448
+ /**
449
+ * Replaces each `oldText` (found once, in the original) by its `newText`.
450
+ * A mount (or `dir`) that implements `edit` gets the edits as they are;
451
+ * otherwise the file is read, edited (`applyEdits`: exact, then tolerant
452
+ * of quotes, dashes and trailing spaces) and written back whole.
453
+ */
454
+ async edit(path, edits) {
455
+ await this.ready();
456
+ const p = normalizePath(path);
457
+ const r = this.route(p);
458
+ if (r?.fs.edit) {
459
+ await r.fs.edit(r.rel, edits);
460
+ this.emitChange(p, "write");
461
+ return;
462
+ }
463
+ if (r && !r.fs.write)
464
+ throw new Error(`${r.prefix || "/"} is read-only`);
465
+ await this.write(p, applyEdits(p, await this.readText(p), edits));
466
+ }
467
+ async delete(path) {
468
+ await this.ready();
469
+ const p = normalizePath(path);
470
+ const r = this.route(p);
471
+ if (r && r.prefix) {
472
+ if (!r.fs.delete)
473
+ throw new Error(`${r.prefix} is read-only`);
474
+ await r.fs.delete(r.rel);
475
+ this.emitChange(p, "delete");
476
+ return;
477
+ }
478
+ if (!(await this.stat(p)))
479
+ throw new Error(`No such file: ${p}`);
480
+ await this.rmFile(p);
481
+ }
482
+ /** The mount a path falls under, or null for the directory itself. */
483
+ mountOf(path) {
484
+ return this.route(normalizePath(path))?.prefix || null;
485
+ }
486
+ /** Whether writes to a path are refused (a read-only mount, or a `dir` root without write). */
487
+ isReadOnly(path) {
488
+ const r = this.route(normalizePath(path));
489
+ if (r)
490
+ return !r.fs.write;
491
+ return false;
492
+ }
493
+ /** Whether a path is under the skills folder or the user's skills folder. */
494
+ isSkillPath(path) {
495
+ const p = normalizePath(path);
496
+ return this.inSkills(p) || (!!this.userSkillsDir && (p === this.userSkillsDir || p.startsWith(this.userSkillsDir + "/")));
497
+ }
498
+ /** A value of the host's kept with this directory (checkpoints, settings); `null` deletes it. */
499
+ async getData(key) {
500
+ await this.ready();
501
+ const v = await this.store.getMeta("data:" + key);
502
+ return v === null ? undefined : v;
503
+ }
504
+ async putData(key, value) {
505
+ await this.ready();
506
+ if (value === null || value === undefined)
507
+ await this.store.deleteMeta("data:" + key);
508
+ else
509
+ await this.store.putMeta("data:" + key, value);
510
+ }
511
+ async deleteData(key) {
512
+ await this.ready();
513
+ await this.store.deleteMeta("data:" + key);
514
+ }
515
+ /** Removes every file outside the skills folder (mounts and skills stay). */
516
+ async clearWork() {
517
+ await this.ready();
518
+ for (const f of await this.list("/")) {
519
+ if (this.inSkills(f.path) || this.route(f.path)?.prefix)
520
+ continue;
521
+ await this.rmFile(f.path);
522
+ }
523
+ }
524
+ /* ---------------- skills ---------------- */
525
+ /** The skills: every `<skillsDir>/<name>/SKILL.md` (parsed once, until a skill changes). */
526
+ async skills() {
527
+ await this.ready();
528
+ if (this.skillCache)
529
+ return this.skillCache;
530
+ const out = [];
531
+ const seen = new Set();
532
+ for (const [folder, v] of this.skillViews) {
533
+ // Known by what the app said: nothing is loaded to list it.
534
+ if (v.lazy) {
535
+ if (seen.has(v.lazy.name))
536
+ continue;
537
+ seen.add(v.lazy.name);
538
+ const dir = `${this.skillsDir}/${folder}`;
539
+ out.push({ name: v.lazy.name, description: v.lazy.description, path: `${dir}/SKILL.md`, dir, builtin: true, lazy: true, ...(v.lazy.disableModelInvocation ? { disableModelInvocation: true } : {}) });
540
+ continue;
541
+ }
542
+ let text;
543
+ try {
544
+ const d = await v.fs.read("/SKILL.md");
545
+ text = typeof d === "string" ? d : decodeText(d);
546
+ }
547
+ catch {
548
+ continue;
549
+ }
550
+ if (text === null)
551
+ continue;
552
+ const parsed = parseSkill(text, `${this.skillsDir}/${folder}/SKILL.md`);
553
+ if (!parsed || seen.has(parsed.skill.name))
554
+ continue;
555
+ seen.add(parsed.skill.name);
556
+ out.push({ ...parsed.skill, ...(v.builtin ? { builtin: true } : {}), ...(v.from ? { from: v.from } : {}) });
557
+ }
558
+ this.skillCache = out.sort((a, b) => a.name.localeCompare(b.name));
559
+ return this.skillCache;
560
+ }
561
+ /**
562
+ * Adds a skill (or a pack of skills) from a zip — a URL / bundle path /
563
+ * `files:<path>` string, or the bytes (a `File` from an
564
+ * `<input type=file>`, a Blob, a Uint8Array) — to the user's skills:
565
+ * the zip is saved as `<userSkillsDir>/<name>.zip` (the same name
566
+ * replaces it) and read in place; `unpack: true` writes its skill
567
+ * folders there instead, as files that can be edited. A zip with
568
+ * SKILL.md at its root is one skill named `name` (else after the file);
569
+ * otherwise each folder with a SKILL.md is one. Returns what was added.
570
+ */
571
+ async installSkill(source, opts = {}) {
572
+ await this.ready();
573
+ if (!this.userSkillsDir)
574
+ throw new Error("this workspace has no userSkillsDir to install skills into");
575
+ let bytes;
576
+ let base;
577
+ if (typeof source === "string") {
578
+ const fetched = await this.fetchSource(source);
579
+ if (!fetched)
580
+ throw new Error("nothing fetched");
581
+ bytes = fetched.bytes;
582
+ base = opts.name ?? source;
583
+ }
584
+ else {
585
+ bytes = source instanceof Uint8Array ? source : new Uint8Array(await source.arrayBuffer());
586
+ base = opts.name ?? (source.name || "skill");
587
+ }
588
+ if (bytes.byteLength > MAX_ZIP_BYTES)
589
+ throw new Error("skills zip too large");
590
+ const name = zipBaseName(base);
591
+ const files = zipFiles(bytes);
592
+ const folders = skillFoldersOf(files.keys(), name);
593
+ if (!folders.size)
594
+ throw new Error(`${name}.zip has no SKILL.md (at its root, or one per folder)`);
595
+ const now = Date.now();
596
+ if (opts.unpack) {
597
+ for (const [folder, prefix] of folders) {
598
+ for (const old of await statsOf(this.lib, `/${folder}/`))
599
+ await this.lib.delete(old.path);
600
+ for (const [p, e] of files) {
601
+ if (!p.startsWith(prefix))
602
+ continue;
603
+ const data = await readZipEntry(bytes, e, this.inflate);
604
+ const text = decodeText(data);
605
+ const path = normalizePath(`/${folder}/${p.slice(prefix.length)}`);
606
+ await this.lib.put({ path, data: text ?? data, contentType: guessType(path, text ?? data), mtime: now, layer: "work" });
607
+ }
608
+ }
609
+ await this.userSkillsChanged(`/${[...folders.keys()][0]}`, "write");
610
+ }
611
+ else {
612
+ await this.lib.put({ path: `/${name}.zip`, data: bytes, contentType: "application/zip", mtime: now, layer: "work" });
613
+ await this.userSkillsChanged(`/${name}.zip`, "write");
614
+ }
615
+ const dirs = new Set([...folders.keys()].map((f) => `${this.skillsDir}/${f}`));
616
+ return (await this.skills()).filter((s) => dirs.has(s.dir));
617
+ }
618
+ /**
619
+ * Removes one of the user's skills: its zip in `userSkillsDir` (with
620
+ * every skill the zip holds) or its folder there. The app's skills
621
+ * cannot be removed. Returns false when there is no such skill.
622
+ */
623
+ async removeSkill(name) {
624
+ const skill = (await this.skills()).find((s) => s.name === name);
625
+ if (!skill)
626
+ return false;
627
+ if (skill.builtin)
628
+ throw new Error(`"${name}" comes with the app and cannot be removed`);
629
+ if (!skill.from || !this.userSkillsDir || !skill.from.startsWith(this.userSkillsDir + "/"))
630
+ return false;
631
+ const rel = skill.from.slice(this.userSkillsDir.length);
632
+ if (/\.zip$/i.test(rel))
633
+ await this.lib.delete(rel);
634
+ else
635
+ for (const f of await statsOf(this.lib, rel + "/"))
636
+ await this.lib.delete(f.path);
637
+ await this.userSkillsChanged(rel, "delete");
638
+ return true;
639
+ }
640
+ /** The body (instructions) of a skill, by name. */
641
+ async skillBody(name) {
642
+ const skill = (await this.skills()).find((s) => s.name === name);
643
+ if (!skill)
644
+ throw new Error(`No skill named "${name}"`);
645
+ const parsed = parseSkill(await this.readText(skill.path), skill.path);
646
+ return { skill, body: parsed?.body ?? "" };
647
+ }
648
+ /** Fetches the app's skills zips again (bypassing the page's copy; lazy ones load again when next used) and regenerates the skills folder. */
649
+ async refreshSkills() {
650
+ await this.ready();
651
+ for (const src of this.resolvedSources) {
652
+ if (isLazy(src)) {
653
+ lazyLoads.delete(src);
654
+ continue;
655
+ }
656
+ const url = typeof src === "string" ? src : !(src instanceof Uint8Array) && !isBlob(src) && typeof src.data === "string" ? src.data : null;
657
+ if (url)
658
+ builtinFetches.delete(`${this.dbName}|${this.fetchKey}|${url}`);
659
+ }
660
+ this.builtins = await this.loadBuiltins();
661
+ await this.rebuildSkills();
662
+ this.emitChange(this.skillsDir, "write");
663
+ }
664
+ /** The app's zips, from the `skills` option (a failed one is left out and logged); lazy ones are only noted. */
665
+ async loadBuiltins() {
666
+ const out = [];
667
+ let list = [];
668
+ try {
669
+ list = typeof this.sources === "function" ? [].concat(await this.sources()) : this.sources;
670
+ }
671
+ catch (err) {
672
+ console.warn("[agent] the skills list failed:", err);
673
+ }
674
+ this.resolvedSources = list;
675
+ this.lazySkills = list.filter(isLazy);
676
+ for (const src of list) {
677
+ if (isLazy(src))
678
+ continue;
679
+ try {
680
+ const named = typeof src === "object" && !(src instanceof Uint8Array) && !isBlob(src) ? src : null;
681
+ const data = named ? named.data : src;
682
+ let bytes, key, at = 0;
683
+ if (typeof data === "string") {
684
+ const k = `${this.dbName}|${this.fetchKey}|${data}`;
685
+ let f = builtinFetches.get(k);
686
+ if (!f) {
687
+ f = this.fetchSource(data).then((r) => { if (!r)
688
+ throw new Error("nothing fetched"); return { bytes: r.bytes, at: Date.now() }; });
689
+ builtinFetches.set(k, f);
690
+ f.catch(() => builtinFetches.delete(k));
691
+ }
692
+ ({ bytes, at } = await f);
693
+ key = `app:${k}@${at}`;
694
+ }
695
+ else {
696
+ bytes = data instanceof Uint8Array ? data : new Uint8Array(await data.arrayBuffer());
697
+ key = `app:${this.dbName}|obj${idOf(data)}`;
698
+ }
699
+ if (bytes.byteLength > MAX_ZIP_BYTES)
700
+ throw new Error("skills zip too large");
701
+ const name = zipBaseName(named?.name ?? (typeof data === "string" ? data : data.name || "skills"));
702
+ out.push({ name, bytes, key, at });
703
+ }
704
+ catch (err) {
705
+ // A skills pack that cannot be fetched (offline, 404) is left out; surface it for developers.
706
+ // eslint-disable-next-line no-console
707
+ console.warn("[agent] skills source failed:", err);
708
+ }
709
+ }
710
+ return out;
711
+ }
712
+ /** Regenerates `skillsDir`: the app's zips, then the user's zips and folders (a user's skill of the same name wins). */
713
+ async rebuildSkills() {
714
+ const views = new Map();
715
+ for (const b of this.builtins) {
716
+ try {
717
+ const parsed = parseSkillZip(b.name, b.bytes, b.key);
718
+ for (const [folder, prefix] of parsed.folders)
719
+ if (!views.has(folder))
720
+ views.set(folder, { fs: skillZipFS(parsed, prefix, b.at, this.inflate), builtin: true });
721
+ }
722
+ catch (err) {
723
+ console.warn(`[agent] skills zip "${b.name}":`, err);
724
+ }
725
+ }
726
+ for (const l of this.lazySkills) {
727
+ const folder = /^[A-Za-z0-9][\w.-]*$/.test(l.name) ? l.name : zipBaseName(l.name);
728
+ if (!views.has(folder))
729
+ views.set(folder, { fs: this.lazyFS(l, folder), builtin: true, lazy: l });
730
+ }
731
+ // A project folder opened with `dir` may bring skill folders of its own.
732
+ if (this.root) {
733
+ for (const f of await this.root.list(this.skillsDir).catch(() => [])) {
734
+ const m = new RegExp("^" + escapeRe(this.skillsDir) + "/([^/]+)/SKILL\\.md$").exec(normalizePath(f.path));
735
+ if (m)
736
+ views.set(m[1], { fs: subFS(this.root, `${this.skillsDir}/${m[1]}`), builtin: false, from: `${this.skillsDir}/${m[1]}` });
737
+ }
738
+ }
739
+ if (this.userSkillsDir) {
740
+ const files = await statsOf(this.lib, "/");
741
+ for (const f of files) {
742
+ const m = /^\/([^/]+)\.zip$/i.exec(f.path);
743
+ if (!m)
744
+ continue;
745
+ try {
746
+ // Only the zips are read (names are enough for the folders), and one parsed at this version already is not read again.
747
+ const key = `user:${this.dbName}|${f.path}@${f.mtime}:${f.size}`;
748
+ let parsed = f.mtime !== undefined ? cachedSkillZip(key) : undefined;
749
+ if (!parsed) {
750
+ const rec = await this.lib.get(f.path);
751
+ if (!rec || !(rec.data instanceof Uint8Array))
752
+ continue;
753
+ parsed = parseSkillZip(zipBaseName(m[1]), rec.data, key);
754
+ }
755
+ for (const [folder, prefix] of parsed.folders)
756
+ views.set(folder, { fs: skillZipFS(parsed, prefix, f.mtime ?? 0, this.inflate), builtin: false, from: this.userSkillsDir + f.path });
757
+ }
758
+ catch (err) {
759
+ console.warn(`[agent] skills zip "${f.path}":`, err);
760
+ }
761
+ }
762
+ const user = this.userFS();
763
+ for (const f of files) {
764
+ const m = /^\/([^/]+)\/SKILL\.md$/.exec(f.path);
765
+ if (m)
766
+ views.set(m[1], { fs: subFS(user, `/${m[1]}`), builtin: false, from: `${this.userSkillsDir}/${m[1]}` });
767
+ }
768
+ }
769
+ this.skillViews = views;
770
+ this.skillCache = null;
771
+ }
772
+ /**
773
+ * A lazy skill's files: its SKILL.md is listed before anything is loaded; the first read (or a
774
+ * look at any other file) loads the zip — once per page — and from then on it is the zip's tree.
775
+ */
776
+ lazyFS(l, folder) {
777
+ let fs = null;
778
+ const ensure = async () => {
779
+ if (fs)
780
+ return fs;
781
+ let p = lazyLoads.get(l);
782
+ if (!p) {
783
+ p = (async () => {
784
+ const d = await l.load();
785
+ if (typeof d === "string") {
786
+ const r = await this.fetchSource(d);
787
+ if (!r)
788
+ throw new Error("nothing fetched");
789
+ return r.bytes;
790
+ }
791
+ return d instanceof Uint8Array ? d : d instanceof ArrayBuffer ? new Uint8Array(d) : new Uint8Array(await d.arrayBuffer());
792
+ })();
793
+ lazyLoads.set(l, p);
794
+ p.catch(() => { if (lazyLoads.get(l) === p)
795
+ lazyLoads.delete(l); }); // tried again next time
796
+ }
797
+ let bytes;
798
+ try {
799
+ bytes = await p;
800
+ }
801
+ catch (err) {
802
+ throw new Error(`the skill "${l.name}" could not be loaded: ${err.message}`);
803
+ }
804
+ if (bytes.byteLength > MAX_ZIP_BYTES)
805
+ throw new Error(`the skill "${l.name}": zip too large`);
806
+ const parsed = parseSkillZip(folder, bytes, `lazy:${idOf(l)}:${bytes.byteLength}`);
807
+ const prefix = parsed.folders.get(folder) ?? [...parsed.folders.values()][0];
808
+ if (prefix === undefined)
809
+ throw new Error(`the skill "${l.name}": its zip has no SKILL.md`);
810
+ fs = skillZipFS(parsed, prefix, Date.now(), this.inflate);
811
+ // Its real files replace the placeholder in listings (the files panel redraws).
812
+ this.emitChange(`${this.skillsDir}/${folder}`, "write");
813
+ return fs;
814
+ };
815
+ const placeholder = (at) => (at === "/" || at === "/SKILL.md" ? [{ path: "/SKILL.md", size: 0 }] : []);
816
+ return {
817
+ list: async (at) => (fs ? fs.list(at) : placeholder(at)),
818
+ stat: async (rel) => {
819
+ if (!fs && rel === "/SKILL.md")
820
+ return { path: rel, size: 0 };
821
+ const f = await ensure();
822
+ return f.stat ? f.stat(rel) : null;
823
+ },
824
+ read: async (rel) => (await ensure()).read(rel),
825
+ };
826
+ }
827
+ /** The generated skills folder: read-only, one subtree per skill. */
828
+ skillsFS() {
829
+ const split = (rel) => { const m = /^\/([^/]+)(\/.*)?$/.exec(rel); return m ? { name: m[1], rest: m[2] || "/" } : null; };
830
+ return {
831
+ description: "skills (generated, read-only)",
832
+ list: async (prefix) => {
833
+ const out = [];
834
+ const sp = split(prefix);
835
+ for (const [name, v] of this.skillViews) {
836
+ if (sp && sp.name !== name)
837
+ continue;
838
+ for (const f of await v.fs.list(sp ? sp.rest : "/"))
839
+ out.push({ ...f, path: `/${name}${normalizePath(f.path)}` });
840
+ }
841
+ return out;
842
+ },
843
+ stat: async (rel) => {
844
+ const sp = split(rel);
845
+ const v = sp && this.skillViews.get(sp.name);
846
+ if (!v || !sp)
847
+ return null;
848
+ const st = v.fs.stat ? await v.fs.stat(sp.rest) : (await v.fs.list(sp.rest)).find((f) => normalizePath(f.path) === sp.rest) ?? null;
849
+ return st ? { ...st, path: rel } : null;
850
+ },
851
+ read: async (rel) => {
852
+ const sp = split(rel);
853
+ const v = sp && this.skillViews.get(sp.name);
854
+ if (!v || !sp)
855
+ throw new Error(`No such file: ${rel}`);
856
+ return v.fs.read(sp.rest);
857
+ },
858
+ };
859
+ }
860
+ /** The user's skills folder: one tree in the app's database, shared by every directory. */
861
+ userFS() {
862
+ return {
863
+ description: "the user's skills, shared by every conversation",
864
+ list: async (prefix) => statsOf(this.lib, prefix === "/" ? "/" : prefix.replace(/\/+$/, "") + "/"),
865
+ stat: async (p) => statIn(this.lib, p),
866
+ read: async (p) => { const r = await this.lib.get(p); if (!r)
867
+ throw new Error(`No such file: ${p}`); return r.data; },
868
+ write: async (p, data, type) => {
869
+ await this.lib.put({ path: p, data, contentType: type ?? guessType(p, data), mtime: Date.now(), layer: "work" });
870
+ await this.userSkillsChanged(p, "write");
871
+ },
872
+ delete: async (p) => { await this.lib.delete(p); await this.userSkillsChanged(p, "delete"); },
873
+ };
874
+ }
875
+ /** A file of the user's skills changed here: regenerate, tell the app's other workspaces and this one's listeners. */
876
+ async userSkillsChanged(rel, kind) {
877
+ await this.rebuildSkills();
878
+ this.openChannel();
879
+ try {
880
+ this.channel?.postMessage({ userSkills: true, path: rel, kind });
881
+ }
882
+ catch { /* closed */ }
883
+ this.emitChange(this.skillsDir, "write");
884
+ }
885
+ /**
886
+ * Moves skills from before the generated folder: once per app, the
887
+ * user's uploads kept in the old library become zips in the user's
888
+ * skills; once per directory, skill files stored in its `skillsDir`
889
+ * (hand-written, written by the agent, unpacked uploads) move to the
890
+ * user's skills and copies unpacked from the app's zips are dropped.
891
+ */
892
+ async migrateSkills() {
893
+ if (!(await this.lib.getMeta("migrated:2"))) {
894
+ for (const r of await this.lib.listMeta("zip:")) {
895
+ if (r.source === "upload" && !(await this.lib.get(`/${r.name}.zip`)))
896
+ await this.lib.put({ path: `/${r.name}.zip`, data: r.bytes, contentType: "application/zip", mtime: r.at || Date.now(), layer: "work" });
897
+ }
898
+ for (const prefix of ["zip:", "removed:"])
899
+ for (const k of await this.lib.listMetaKeys(prefix))
900
+ await this.lib.deleteMeta(k);
901
+ await this.lib.putMeta("migrated:2", true);
902
+ }
903
+ if (this.root || (await this.store.getMeta("skills-migrated:2")))
904
+ return;
905
+ const own = await this.store.list(this.skillsDir + "/");
906
+ if (own.length) {
907
+ const fromApp = new Set();
908
+ for (const k of await this.store.listMetaKeys("skills:")) {
909
+ const m = await this.store.getMeta(k);
910
+ if (!k.startsWith("skills:upload:"))
911
+ for (const f of m?.files ?? [])
912
+ fromApp.add(f);
913
+ await this.store.deleteMeta(k);
914
+ }
915
+ for (const rec of own) {
916
+ const rel = rec.path.slice(this.skillsDir.length);
917
+ if (!fromApp.has(rec.path) && this.userSkillsDir && !(await this.lib.get(rel)))
918
+ await this.lib.put({ ...rec, path: rel, layer: "work" });
919
+ await this.store.delete(rec.path);
920
+ }
921
+ }
922
+ await this.store.putMeta("skills-migrated:2", true);
923
+ }
924
+ async fetchSource(source, prev) {
925
+ if (source.startsWith("files:")) {
926
+ if (!this.provider?.readFile)
927
+ throw new Error("a files: skills source needs a provider that reads files (RunApps)");
928
+ const got = await this.provider.readFile(source.slice(6), { etag: prev?.etag });
929
+ if (!got)
930
+ return null;
931
+ if (got.bytes.byteLength > MAX_ZIP_BYTES)
932
+ throw new Error("skills zip too large");
933
+ return got;
934
+ }
935
+ const headers = {};
936
+ if (prev?.etag)
937
+ headers["If-None-Match"] = prev.etag;
938
+ else if (prev?.lastModified)
939
+ headers["If-Modified-Since"] = prev.lastModified;
940
+ const res = await this.fetchFn(source, { headers, cache: "no-cache" });
941
+ if (res.status === 304)
942
+ return null;
943
+ if (!res.ok)
944
+ throw new Error(`HTTP ${res.status}`);
945
+ const buf = await res.arrayBuffer();
946
+ if (buf.byteLength > MAX_ZIP_BYTES)
947
+ throw new Error("skills zip too large");
948
+ return {
949
+ bytes: new Uint8Array(buf),
950
+ etag: res.headers.get("ETag") ?? undefined,
951
+ lastModified: res.headers.get("Last-Modified") ?? undefined,
952
+ };
953
+ }
954
+ /** Deletes this directory: its files, its skills bookkeeping and the sessions saved from it. Other ids of the app stay. */
955
+ async destroy() {
956
+ await this.ready();
957
+ await this.store.clear();
958
+ this.emitChange("/", "delete");
959
+ this.close();
960
+ this.skillCache = null;
961
+ }
962
+ }
963
+ /* ------------------------------------------------------------------ */
964
+ /* Paths and content */
965
+ /* ------------------------------------------------------------------ */
966
+ /** Absolute, `/`-separated, no `.`/`..`/doubled slashes, no trailing slash. */
967
+ export function normalizePath(path) {
968
+ const parts = [];
969
+ for (const seg of String(path ?? "").replace(/\\/g, "/").split("/")) {
970
+ if (!seg || seg === ".")
971
+ continue;
972
+ if (seg === "..") {
973
+ parts.pop();
974
+ continue;
975
+ }
976
+ parts.push(seg);
977
+ }
978
+ return "/" + parts.join("/");
979
+ }
980
+ function statOf(rec) {
981
+ return { path: rec.path, size: sizeOf(rec.data), contentType: rec.contentType, mtime: rec.mtime };
982
+ }
983
+ function sizeOf(data) {
984
+ return typeof data === "string" ? new TextEncoder().encode(data).byteLength : data.byteLength;
985
+ }
986
+ const TEXT_EXT = new Set(["md", "txt", "json", "js", "mjs", "cjs", "ts", "tsx", "jsx", "css", "html", "htm", "xml", "svg", "yaml", "yml", "toml", "csv", "tsv", "py", "sh", "sql", "ini", "cfg", "conf", "log", "drawio", "env", "gitignore"]);
987
+ const TYPES = {
988
+ md: "text/markdown", txt: "text/plain", json: "application/json", js: "text/javascript", mjs: "text/javascript",
989
+ ts: "text/typescript", css: "text/css", html: "text/html", xml: "application/xml", svg: "image/svg+xml",
990
+ yaml: "application/yaml", yml: "application/yaml", csv: "text/csv", png: "image/png", jpg: "image/jpeg",
991
+ jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp", pdf: "application/pdf", zip: "application/zip",
992
+ mp3: "audio/mpeg", wav: "audio/wav", mp4: "video/mp4", py: "text/x-python", sh: "text/x-shellscript",
993
+ };
994
+ export function guessType(path, data) {
995
+ const ext = path.split(".").pop()?.toLowerCase() ?? "";
996
+ if (TYPES[ext])
997
+ return TYPES[ext];
998
+ if (typeof data === "string" || TEXT_EXT.has(ext))
999
+ return "text/plain";
1000
+ return "application/octet-stream";
1001
+ }
1002
+ /** UTF-8 text of `bytes`, or null when it is not text. */
1003
+ export function decodeText(bytes) {
1004
+ const head = bytes.subarray(0, 8192);
1005
+ for (let i = 0; i < head.length; i++)
1006
+ if (head[i] === 0)
1007
+ return null;
1008
+ try {
1009
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
1010
+ }
1011
+ catch {
1012
+ return null;
1013
+ }
1014
+ }
1015
+ const isBlob = (v) => typeof Blob !== "undefined" && v instanceof Blob;
1016
+ const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1017
+ function zipBaseName(source) {
1018
+ const last = source.split(/[?#]/)[0].split("/").pop() || "skill";
1019
+ return last.replace(/\.zip$/i, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "skill";
1020
+ }
1021
+ /* ------------------------------------------------------------------ */
1022
+ /* Stores */
1023
+ /* ------------------------------------------------------------------ */
1024
+ const DB_VERSION = 4;
1025
+ /**
1026
+ * The app's database: `files` and `meta` keyed by [space, key] so every
1027
+ * directory (space) is its own tree; `sessions` keyed by [space, id].
1028
+ * Version 3 (2026-10-31) was the first with spaces (sessions keyed by id
1029
+ * alone); version 4 keys sessions per space too and keeps what version 3
1030
+ * stored. An upgrade never drops files or sessions.
1031
+ */
1032
+ function openIDBStore(idb, name, space) {
1033
+ return new Promise((resolve, reject) => {
1034
+ const req = idb.open(name, DB_VERSION);
1035
+ req.onupgradeneeded = (ev) => {
1036
+ const db = req.result;
1037
+ const tx = req.transaction;
1038
+ const old = ev.oldVersion;
1039
+ const makeSessions = () => db.createObjectStore("sessions", { keyPath: ["space", "id"] }).createIndex("space", "space");
1040
+ if (old < 3) {
1041
+ // Nothing of ours yet (or a layout from before spaces): start clean.
1042
+ for (const n of ["files", "meta", "sessions"])
1043
+ if (db.objectStoreNames.contains(n))
1044
+ db.deleteObjectStore(n);
1045
+ db.createObjectStore("files", { keyPath: ["space", "path"] });
1046
+ db.createObjectStore("meta", { keyPath: ["space", "key"] });
1047
+ makeSessions();
1048
+ return;
1049
+ }
1050
+ if (old < 4) {
1051
+ // Sessions were keyed by id alone: move them under [space, id].
1052
+ const all = tx.objectStore("sessions").getAll();
1053
+ all.onsuccess = () => {
1054
+ const rows = all.result;
1055
+ db.deleteObjectStore("sessions");
1056
+ makeSessions();
1057
+ const ns = tx.objectStore("sessions");
1058
+ for (const r of rows)
1059
+ if (r.id)
1060
+ ns.put({ ...r, space: r.space ?? "default" });
1061
+ };
1062
+ }
1063
+ };
1064
+ req.onerror = () => reject(req.error ?? new Error("indexedDB open failed"));
1065
+ // Another tab still has the old version open: wait for it (it closes on versionchange) rather than fail.
1066
+ req.onblocked = () => console.warn(`agent: ${name} is waiting for another tab to release the database`);
1067
+ req.onsuccess = () => {
1068
+ const db = req.result;
1069
+ db.onversionchange = () => db.close();
1070
+ // A result counts once its transaction has committed: a quota error aborts after onsuccess.
1071
+ const run = (store, mode, fn) => new Promise((res, rej) => {
1072
+ const tx = db.transaction(store, mode);
1073
+ const r = fn(tx.objectStore(store));
1074
+ let value;
1075
+ r.onsuccess = () => { value = r.result; if (mode === "readonly")
1076
+ res(value); };
1077
+ r.onerror = () => rej(r.error ?? new Error("indexedDB request failed"));
1078
+ tx.oncomplete = () => res(value);
1079
+ tx.onabort = () => rej(tx.error ?? new Error("indexedDB transaction aborted"));
1080
+ });
1081
+ const range = (which, prefix) => IDBKeyRange.bound([which, prefix], [which, prefix + "\uffff"], false, false);
1082
+ resolve({
1083
+ get: (path) => run("files", "readonly", (s) => s.get([space, path])),
1084
+ put: async (rec) => { await run("files", "readwrite", (s) => s.put({ ...rec, space })); },
1085
+ delete: async (path) => { await run("files", "readwrite", (s) => s.delete([space, path])); },
1086
+ list: (prefix) => run("files", "readonly", (s) => s.getAll(range(space, prefix))),
1087
+ getMeta: async (key) => (await run("meta", "readonly", (s) => s.get([space, key])))?.value,
1088
+ putMeta: async (key, value) => { await run("meta", "readwrite", (s) => s.put({ space, key, value })); },
1089
+ deleteMeta: async (key) => { await run("meta", "readwrite", (s) => s.delete([space, key])); },
1090
+ listMeta: async (prefix) => (await run("meta", "readonly", (s) => s.getAll(range(space, prefix)))).map((r) => r.value),
1091
+ listMetaKeys: async (prefix) => (await run("meta", "readonly", (s) => s.getAll(range(space, prefix)))).map((r) => r.key),
1092
+ getSession: (which, id) => run("sessions", "readonly", (s) => s.get([which, id])),
1093
+ putSession: async (data) => { await run("sessions", "readwrite", (s) => s.put(data)); },
1094
+ deleteSession: async (which, id) => { await run("sessions", "readwrite", (s) => s.delete([which, id])); },
1095
+ listSessions: () => run("sessions", "readonly", (s) => s.getAll()),
1096
+ clear: async (which = space) => {
1097
+ await run("files", "readwrite", (s) => s.delete(range(which, "/")));
1098
+ await run("meta", "readwrite", (s) => s.delete(range(which, "")));
1099
+ await run("sessions", "readwrite", (s) => s.delete(range(which, "")));
1100
+ },
1101
+ close: () => db.close(),
1102
+ });
1103
+ };
1104
+ });
1105
+ }
1106
+ const memoryStores = new Map();
1107
+ function memoryStore(name, space) {
1108
+ let m = memoryStores.get(name);
1109
+ if (!m) {
1110
+ m = { files: new Map(), meta: new Map(), sessions: new Map() };
1111
+ memoryStores.set(name, m);
1112
+ }
1113
+ const mem = m;
1114
+ const files = () => { let f = mem.files.get(space); if (!f) {
1115
+ f = new Map();
1116
+ mem.files.set(space, f);
1117
+ } return f; };
1118
+ const meta = () => { let f = mem.meta.get(space); if (!f) {
1119
+ f = new Map();
1120
+ mem.meta.set(space, f);
1121
+ } return f; };
1122
+ return {
1123
+ get: async (path) => files().get(path),
1124
+ put: async (rec) => { files().set(rec.path, { ...rec, space }); },
1125
+ delete: async (path) => { files().delete(path); },
1126
+ list: async (prefix) => [...files().values()].filter((r) => prefix === "/" || r.path.startsWith(prefix)),
1127
+ getMeta: async (key) => meta().get(key),
1128
+ putMeta: async (key, value) => { meta().set(key, value); },
1129
+ deleteMeta: async (key) => { meta().delete(key); },
1130
+ listMeta: async (prefix) => [...meta()].filter(([k]) => k.startsWith(prefix)).map(([, v]) => v),
1131
+ listMetaKeys: async (prefix) => [...meta().keys()].filter((k) => k.startsWith(prefix)),
1132
+ getSession: async (which, id) => mem.sessions.get(`${which}\u0000${id}`),
1133
+ putSession: async (data) => { mem.sessions.set(`${data.space ?? space}\u0000${data.id}`, data); },
1134
+ deleteSession: async (which, id) => { mem.sessions.delete(`${which}\u0000${id}`); },
1135
+ listSessions: async () => [...mem.sessions.values()],
1136
+ clear: async (which = space) => {
1137
+ mem.files.delete(which);
1138
+ mem.meta.delete(which);
1139
+ for (const [id, d] of mem.sessions)
1140
+ if (d.space === which)
1141
+ mem.sessions.delete(id);
1142
+ },
1143
+ close: () => { },
1144
+ };
1145
+ }
1146
+ /** A title for a session without one: its first user message, shortened. */
1147
+ export const UNTITLED = "Untitled";
1148
+ /** The first thing the user wrote: what they typed for an expanded command, never a compaction summary, an agent note or an attachment list. */
1149
+ export function titleOf(d) {
1150
+ for (const m of d.messages) {
1151
+ if (m.role !== "user" || summaryOf(m) !== null)
1152
+ continue;
1153
+ const typed = m.typed;
1154
+ const text = typeof typed === "string" ? typed : typeof m.content === "string" ? m.content : (m.content ?? []).find((p) => p.type === "text")?.text ?? "";
1155
+ // An attachment list or context the chat put after the typed words is not part of the title.
1156
+ const line = text.replace(/\s*\[attachments\][\s\S]*$/, "").replace(/(^|\n)\[context\] [\s\S]*$/, "").replace(/\s+/g, " ").trim();
1157
+ if (!line || isMachineTitle(line))
1158
+ continue;
1159
+ return line.length > 80 ? line.slice(0, 77) + "…" : line;
1160
+ }
1161
+ return UNTITLED;
1162
+ }
1163
+ /** A title that is not the user's words: a compaction summary, an expanded skill, an agent note, an attachment list, the host's context. */
1164
+ export function isMachineTitle(title) {
1165
+ return /^(The conversation history before this point|<skill[\s>]|\[environment\]|\[attachments\]|\[context\] )|\[attachments\]/.test(title);
1166
+ }
1167
+ /** Runs fn holding the origin-wide Web Lock `name`; without Web Locks it just runs fn. */
1168
+ export function withLock(name, fn) {
1169
+ const locks = typeof navigator !== "undefined"
1170
+ ? navigator.locks
1171
+ : undefined;
1172
+ return locks && typeof locks.request === "function" ? locks.request(name, fn) : fn();
1173
+ }
1174
+ /** An in-memory AgentFS, for tests and for documents an app builds on the fly. */
1175
+ export function memoryFS(initial = {}, opts = {}) {
1176
+ const files = new Map();
1177
+ for (const [k, v] of Object.entries(initial))
1178
+ files.set(normalizePath(k), v);
1179
+ const fs = {
1180
+ files,
1181
+ description: opts.description,
1182
+ async list(prefix) {
1183
+ const p = normalizePath(prefix);
1184
+ return [...files.entries()]
1185
+ .filter(([k]) => p === "/" || k === p || k.startsWith(p + "/"))
1186
+ .map(([path, data]) => ({ path, size: sizeOf(data) }));
1187
+ },
1188
+ async read(path) {
1189
+ const v = files.get(normalizePath(path));
1190
+ if (v === undefined)
1191
+ throw new Error(`No such file: ${normalizePath(path)}`);
1192
+ return v;
1193
+ },
1194
+ };
1195
+ if (!opts.readonly) {
1196
+ fs.write = async (path, content) => { files.set(normalizePath(path), content); };
1197
+ fs.delete = async (path) => {
1198
+ if (!files.delete(normalizePath(path)))
1199
+ throw new Error(`No such file: ${normalizePath(path)}`);
1200
+ };
1201
+ }
1202
+ return fs;
1203
+ }