@dudko.dev/agent-web 0.0.37 → 0.0.38

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.
@@ -0,0 +1,573 @@
1
+ import {
2
+ FILES_STORE,
3
+ openAgentWebDB
4
+ } from "./chunk-CTXDKSDD.js";
5
+
6
+ // src/limits.ts
7
+ var over = (value, cap) => typeof cap === "number" && cap > 0 && (value ?? 0) >= cap;
8
+ var checkLimits = (usage, limits) => {
9
+ if (!limits) return void 0;
10
+ if (over(usage.totalTokens, limits.maxTotalTokens)) {
11
+ return { kind: "total", tokens: usage.totalTokens, cap: limits.maxTotalTokens };
12
+ }
13
+ if (over(usage.inputTokens, limits.maxInputTokens)) {
14
+ return { kind: "input", tokens: usage.inputTokens, cap: limits.maxInputTokens };
15
+ }
16
+ if (over(usage.outputTokens, limits.maxOutputTokens)) {
17
+ return { kind: "output", tokens: usage.outputTokens, cap: limits.maxOutputTokens };
18
+ }
19
+ if (over(usage.reasoningTokens, limits.maxReasoningTokens)) {
20
+ return {
21
+ kind: "reasoning",
22
+ tokens: usage.reasoningTokens ?? 0,
23
+ cap: limits.maxReasoningTokens
24
+ };
25
+ }
26
+ return void 0;
27
+ };
28
+ var ToolBudgetError = class extends Error {
29
+ constructor(cap) {
30
+ super(
31
+ `Tool-call budget exhausted (${cap} per run). Do not call more tools; report what you have.`
32
+ );
33
+ this.name = "ToolBudgetError";
34
+ }
35
+ toJSON() {
36
+ return this.message;
37
+ }
38
+ };
39
+
40
+ // src/tools/approval.ts
41
+ var TOOL_APPROVAL_MODES = [
42
+ "autopilot",
43
+ "ask-writes",
44
+ "ask-all",
45
+ "read-only"
46
+ ];
47
+ var ToolDeniedError = class extends Error {
48
+ constructor(reason) {
49
+ super(
50
+ `Tool call denied by the user${reason ? `: ${reason}` : ""}. Do not retry it; continue without it, or report what is blocked.`
51
+ );
52
+ this.name = "ToolDeniedError";
53
+ }
54
+ toJSON() {
55
+ return this.message;
56
+ }
57
+ };
58
+ var markReadOnly = (tool2, readOnly = true) => {
59
+ ;
60
+ tool2.readOnly = readOnly;
61
+ return tool2;
62
+ };
63
+ var isReadOnlyTool = (tool2) => tool2?.readOnly === true;
64
+ var globToRegExp = (glob) => new RegExp(
65
+ `^${glob.split("*").map((s) => s.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*")}$`
66
+ );
67
+ var matchRule = (rules, toolName) => {
68
+ if (!rules) return void 0;
69
+ if (Object.hasOwn(rules, toolName)) return rules[toolName];
70
+ let best;
71
+ for (const [pattern, perm] of Object.entries(rules)) {
72
+ if (!pattern.includes("*")) continue;
73
+ if (!globToRegExp(pattern).test(toolName)) continue;
74
+ const len = pattern.replace(/\*/g, "").length;
75
+ if (!best || len > best.len) best = { len, perm };
76
+ }
77
+ return best?.perm;
78
+ };
79
+ var decideToolPermission = (opts) => {
80
+ if (opts.remembered?.has(opts.toolName)) return "allow";
81
+ const rule = matchRule(opts.rules, opts.toolName);
82
+ if (rule) return rule;
83
+ switch (opts.mode) {
84
+ case "autopilot":
85
+ return "allow";
86
+ case "read-only":
87
+ return opts.readOnly ? "allow" : "deny";
88
+ case "ask-writes":
89
+ return opts.readOnly ? "allow" : "ask";
90
+ case "ask-all":
91
+ return "ask";
92
+ }
93
+ };
94
+ var normalizeDecision = (d) => typeof d === "boolean" ? { approved: d } : { approved: Boolean(d?.approved), reason: d?.reason, remember: d?.remember };
95
+ var createApprovalState = (config) => ({
96
+ mode: config?.mode ?? "autopilot",
97
+ config: config ?? {},
98
+ remembered: /* @__PURE__ */ new Set()
99
+ });
100
+ var seq = 0;
101
+ var gateToolCall = async (state, call, events, signal) => {
102
+ const permission = decideToolPermission({
103
+ toolName: call.toolName,
104
+ readOnly: call.readOnly,
105
+ mode: state.mode,
106
+ rules: state.config.rules,
107
+ remembered: state.remembered
108
+ });
109
+ if (permission === "allow") return;
110
+ const id = `approval-${Date.now().toString(36)}-${seq += 1}`;
111
+ if (permission === "deny") {
112
+ const reason = state.mode === "read-only" && !matchRule(state.config.rules, call.toolName) ? "the agent is in read-only mode" : "blocked by policy";
113
+ events.resolved({ id, name: call.toolName, approved: false, reason, automatic: true });
114
+ throw new ToolDeniedError(reason);
115
+ }
116
+ const onRequest = state.config.onRequest;
117
+ if (!onRequest) {
118
+ const reason = "no approval handler configured";
119
+ events.resolved({ id, name: call.toolName, approved: false, reason, automatic: true });
120
+ throw new ToolDeniedError(reason);
121
+ }
122
+ const req = { id, ...call };
123
+ events.requested(req);
124
+ let decision;
125
+ try {
126
+ decision = normalizeDecision(
127
+ await withDeadline(Promise.resolve(onRequest(req)), state.config.timeoutMs, signal)
128
+ );
129
+ } catch (err) {
130
+ const reason = err instanceof Error ? err.message : String(err);
131
+ events.resolved({ id, name: call.toolName, approved: false, reason, automatic: true });
132
+ throw new ToolDeniedError(reason);
133
+ }
134
+ if (decision.approved && decision.remember) state.remembered.add(call.toolName);
135
+ events.resolved({
136
+ id,
137
+ name: call.toolName,
138
+ approved: decision.approved,
139
+ reason: decision.reason,
140
+ automatic: false
141
+ });
142
+ if (!decision.approved) throw new ToolDeniedError(decision.reason);
143
+ };
144
+ var withDeadline = (p, timeoutMs, signal) => {
145
+ if ((!timeoutMs || timeoutMs <= 0) && !signal) return p;
146
+ return new Promise((resolve, reject) => {
147
+ let timer;
148
+ const done = () => {
149
+ if (timer !== void 0) clearTimeout(timer);
150
+ signal?.removeEventListener("abort", onAbort);
151
+ };
152
+ const onAbort = () => {
153
+ done();
154
+ reject(new Error("the run was stopped while waiting for approval"));
155
+ };
156
+ if (signal?.aborted) return onAbort();
157
+ signal?.addEventListener("abort", onAbort, { once: true });
158
+ if (timeoutMs && timeoutMs > 0) {
159
+ timer = setTimeout(() => {
160
+ done();
161
+ reject(new Error(`no approval decision within ${timeoutMs} ms`));
162
+ }, timeoutMs);
163
+ }
164
+ p.then(
165
+ (v) => {
166
+ done();
167
+ resolve(v);
168
+ },
169
+ (e) => {
170
+ done();
171
+ reject(e);
172
+ }
173
+ );
174
+ });
175
+ };
176
+
177
+ // src/tools/types.ts
178
+ var promptHintOf = (tool2) => typeof tool2.promptHint === "string" ? tool2.promptHint : void 0;
179
+
180
+ // src/tools/wrap.ts
181
+ import { asSchema } from "ai";
182
+ var toolRunContextOf = (options) => options?.agentRun;
183
+ var truncated = (s, max) => s.length > max ? `${s.slice(0, max)}\u2026 [truncated ${s.length - max} chars]` : s;
184
+ var toText = (v) => {
185
+ if (typeof v === "string") return v;
186
+ try {
187
+ return JSON.stringify(v) ?? String(v);
188
+ } catch {
189
+ return String(v);
190
+ }
191
+ };
192
+ var limitModelOutput = (original, maxChars) => (async (opts) => {
193
+ const base = original ? await original(opts) : typeof opts.output === "string" ? { type: "text", value: opts.output } : { type: "json", value: opts.output ?? null };
194
+ if (base.type === "text" || base.type === "error-text") {
195
+ return { ...base, value: truncated(base.value, maxChars) };
196
+ }
197
+ if (base.type === "json" || base.type === "error-json") {
198
+ const text = toText(base.value);
199
+ if (text.length <= maxChars) return base;
200
+ return {
201
+ type: base.type === "json" ? "text" : "error-text",
202
+ value: truncated(text, maxChars)
203
+ };
204
+ }
205
+ return base;
206
+ });
207
+ var wrapToolsForRun = (tools, o) => {
208
+ const out = {};
209
+ const gate = (toolName, input, readOnly, signal) => gateToolCall(
210
+ o.approval,
211
+ { toolName, input, readOnly, step: o.step() },
212
+ {
213
+ requested: (req) => o.emit({
214
+ type: "tool.approval-requested",
215
+ id: req.id,
216
+ name: req.toolName,
217
+ input: req.input,
218
+ readOnly: req.readOnly,
219
+ step: req.step
220
+ }),
221
+ resolved: (r) => o.emit({ type: "tool.approval-resolved", ...r })
222
+ },
223
+ signal ?? o.signal
224
+ );
225
+ for (const [name, t] of Object.entries(tools)) {
226
+ const execute = t.execute;
227
+ const builtin = o.builtins.has(name);
228
+ const readOnly = builtin || isReadOnlyTool(t);
229
+ const wrapped = { ...t };
230
+ if (o.maxToolOutputChars > 0) {
231
+ wrapped.toModelOutput = limitModelOutput(t.toModelOutput, o.maxToolOutputChars);
232
+ }
233
+ if (typeof execute === "function") {
234
+ wrapped.execute = (input, options) => {
235
+ const run = () => {
236
+ if (!builtin) o.countCall();
237
+ const agentRun = {
238
+ emit: o.emit,
239
+ step: o.step(),
240
+ signal: o.signal,
241
+ addUsage: o.addUsage,
242
+ approve: (toolName, toolInput, ro) => gate(toolName, toolInput, ro),
243
+ ...o.control ? { control: o.control } : {},
244
+ ...o.runId ? { runId: o.runId } : {},
245
+ ...o.fetched ? { fetched: o.fetched } : {}
246
+ };
247
+ return execute.call(t, input, { ...options, agentRun });
248
+ };
249
+ if (builtin) return run();
250
+ const permission = decideToolPermission({
251
+ toolName: name,
252
+ readOnly,
253
+ mode: o.approval.mode,
254
+ rules: o.approval.config.rules,
255
+ remembered: o.approval.remembered
256
+ });
257
+ if (permission === "allow") return run();
258
+ return gate(
259
+ name,
260
+ input,
261
+ readOnly,
262
+ options?.abortSignal
263
+ ).then(run);
264
+ };
265
+ }
266
+ out[name] = wrapped;
267
+ }
268
+ return out;
269
+ };
270
+ var createCallCounter = (cap, initial = 0) => {
271
+ let calls = Math.max(0, Math.floor(initial));
272
+ return {
273
+ count: () => {
274
+ if (cap && cap > 0 && calls >= cap) throw new ToolBudgetError(cap);
275
+ calls += 1;
276
+ },
277
+ get calls() {
278
+ return calls;
279
+ },
280
+ get exhausted() {
281
+ return Boolean(cap && cap > 0 && calls >= cap);
282
+ }
283
+ };
284
+ };
285
+ var typeHint = (s, depth) => {
286
+ if (!s) return "any";
287
+ if (Array.isArray(s.enum) && s.enum.length > 0 && s.enum.length <= 8) {
288
+ return s.enum.map((v) => JSON.stringify(v)).join(" | ");
289
+ }
290
+ const type = Array.isArray(s.type) ? s.type.find((x) => x !== "null") : s.type;
291
+ if (type === "array") return `${typeHint(s.items, depth)}[]`;
292
+ if (type === "object" || s.properties) {
293
+ if (depth > 1 || !s.properties) return "object";
294
+ return objectHint(s, depth + 1);
295
+ }
296
+ return type ?? "any";
297
+ };
298
+ var objectHint = (s, depth = 0) => {
299
+ const required = new Set(s.required ?? []);
300
+ const props = Object.entries(s.properties ?? {});
301
+ if (props.length === 0) return "{}";
302
+ return `{ ${props.slice(0, 12).map(([k, v]) => `${k}${required.has(k) ? "" : "?"}: ${typeHint(v, depth)}`).join(", ")}${props.length > 12 ? ", \u2026" : ""} }`;
303
+ };
304
+ var schemaHintOf = async (t) => {
305
+ const own = promptHintOf(t);
306
+ if (own) return own;
307
+ try {
308
+ const schema = await asSchema(t.inputSchema).jsonSchema;
309
+ return schema && typeof schema === "object" ? objectHint(schema) : void 0;
310
+ } catch {
311
+ return void 0;
312
+ }
313
+ };
314
+
315
+ // src/files/vfs.ts
316
+ var MIME = {
317
+ txt: "text/plain",
318
+ md: "text/markdown",
319
+ json: "application/json",
320
+ csv: "text/csv",
321
+ html: "text/html",
322
+ css: "text/css",
323
+ js: "text/javascript",
324
+ ts: "text/typescript",
325
+ svg: "image/svg+xml",
326
+ png: "image/png",
327
+ jpg: "image/jpeg",
328
+ jpeg: "image/jpeg",
329
+ gif: "image/gif",
330
+ webp: "image/webp",
331
+ pdf: "application/pdf",
332
+ xml: "application/xml",
333
+ yaml: "text/yaml",
334
+ yml: "text/yaml"
335
+ };
336
+ var mimeFromPath = (path) => MIME[path.split(".").pop()?.toLowerCase() ?? ""] ?? "application/octet-stream";
337
+ var isTextMime = (mime) => /^text\/|json|xml|yaml|javascript|typescript|svg/.test(mime);
338
+ var normalizePath = (input) => {
339
+ const parts = [];
340
+ for (const seg of String(input ?? "").replace(/\\/g, "/").split("/")) {
341
+ if (!seg || seg === ".") continue;
342
+ if (seg === "..") {
343
+ if (parts.length === 0) throw new Error(`path "${input}" escapes the root`);
344
+ parts.pop();
345
+ continue;
346
+ }
347
+ parts.push(seg);
348
+ }
349
+ if (parts.length === 0) throw new Error("a file path is required");
350
+ return `/${parts.join("/")}`;
351
+ };
352
+ var byteLength = (content, encoding) => encoding === "base64" ? Math.floor(content.replace(/=+$/, "").length * 3 / 4) : new TextEncoder().encode(content).length;
353
+ var bytesToBase64 = (bytes) => {
354
+ let bin = "";
355
+ for (let i = 0; i < bytes.length; i += 32768) {
356
+ bin += String.fromCharCode(...bytes.subarray(i, i + 32768));
357
+ }
358
+ return btoa(bin);
359
+ };
360
+ var VirtualFileSystem = class {
361
+ memory;
362
+ dbName;
363
+ ns;
364
+ maxFileBytes;
365
+ listeners = /* @__PURE__ */ new Set();
366
+ constructor(opts = {}) {
367
+ if (opts.memory) this.memory = /* @__PURE__ */ new Map();
368
+ this.dbName = opts.dbName;
369
+ this.ns = opts.namespace ?? "default";
370
+ this.maxFileBytes = opts.maxFileBytes ?? 10 * 1024 * 1024;
371
+ }
372
+ key(path) {
373
+ return `${this.ns}:${path}`;
374
+ }
375
+ /** Subscribe to writes and deletes (e.g. to refresh a file list). Returns an unsubscribe. */
376
+ onChange(listener) {
377
+ this.listeners.add(listener);
378
+ return () => this.listeners.delete(listener);
379
+ }
380
+ notify(type, path) {
381
+ for (const l of this.listeners) {
382
+ try {
383
+ l({ type, path });
384
+ } catch {
385
+ }
386
+ }
387
+ }
388
+ async write(path, content, opts = {}) {
389
+ const p = normalizePath(path);
390
+ const binary = content instanceof Uint8Array;
391
+ const encoding = binary ? "base64" : opts.encoding ?? "utf8";
392
+ const text = binary ? bytesToBase64(content) : content;
393
+ const size = binary ? content.length : byteLength(text, encoding);
394
+ if (size > this.maxFileBytes) {
395
+ throw new Error(`"${p}" is ${size} bytes; the limit is ${this.maxFileBytes}`);
396
+ }
397
+ const file = {
398
+ path: p,
399
+ content: text,
400
+ encoding,
401
+ mimeType: opts.mimeType ?? mimeFromPath(p),
402
+ size,
403
+ updatedAt: Date.now()
404
+ };
405
+ if (this.memory) this.memory.set(p, file);
406
+ else {
407
+ const db = await openAgentWebDB({ dbName: this.dbName });
408
+ await db.put(FILES_STORE, file, this.key(p));
409
+ }
410
+ this.notify("write", p);
411
+ const { content: _drop, ...info } = file;
412
+ return info;
413
+ }
414
+ /** Store a data URL ("data:image/png;base64,…") as a file. */
415
+ async writeDataUrl(path, dataUrl) {
416
+ const m = /^data:([^;,]+)?(;base64)?,(.*)$/s.exec(dataUrl);
417
+ if (!m) throw new Error("not a data URL");
418
+ const mimeType = m[1] ?? "application/octet-stream";
419
+ return m[2] ? this.write(path, m[3], { mimeType, encoding: "base64" }) : this.write(path, decodeURIComponent(m[3]), { mimeType });
420
+ }
421
+ async read(path) {
422
+ const p = normalizePath(path);
423
+ if (this.memory) return this.memory.get(p);
424
+ const db = await openAgentWebDB({ dbName: this.dbName });
425
+ return await db.get(FILES_STORE, this.key(p));
426
+ }
427
+ /** The file as a data URL (for <img src>, downloads). */
428
+ async readDataUrl(path) {
429
+ const f = await this.read(path);
430
+ if (!f) return void 0;
431
+ return f.encoding === "base64" ? `data:${f.mimeType};base64,${f.content}` : `data:${f.mimeType};charset=utf-8,${encodeURIComponent(f.content)}`;
432
+ }
433
+ async delete(path) {
434
+ const p = normalizePath(path);
435
+ let existed;
436
+ if (this.memory) existed = this.memory.delete(p);
437
+ else {
438
+ const db = await openAgentWebDB({ dbName: this.dbName });
439
+ existed = await db.get(FILES_STORE, this.key(p)) !== void 0;
440
+ await db.delete(FILES_STORE, this.key(p));
441
+ }
442
+ if (existed) this.notify("delete", p);
443
+ return existed;
444
+ }
445
+ /** Files under a prefix ("/" = all), sorted by path. */
446
+ async list(prefix = "/") {
447
+ const dir = prefix === "/" ? "/" : `${normalizePath(prefix)}/`;
448
+ let files;
449
+ if (this.memory) files = [...this.memory.values()];
450
+ else {
451
+ const db = await openAgentWebDB({ dbName: this.dbName });
452
+ const range = IDBKeyRange.bound(`${this.ns}:`, `${this.ns}:\uFFFF`);
453
+ files = await db.getAll(FILES_STORE, range);
454
+ }
455
+ return files.filter((f) => dir === "/" || f.path.startsWith(dir)).map(({ content: _drop, ...info }) => info).sort((a, b) => a.path.localeCompare(b.path));
456
+ }
457
+ /** Remove every file (of this namespace). */
458
+ async clear() {
459
+ for (const f of await this.list()) await this.delete(f.path);
460
+ }
461
+ };
462
+
463
+ // src/files/tools.ts
464
+ import { jsonSchema, tool } from "ai";
465
+ var FILE_TOOL = /* @__PURE__ */ Symbol.for("@dudko.dev/agent-web:file-tool");
466
+ var bind = (t, binding) => {
467
+ Object.defineProperty(t, FILE_TOOL, { value: binding, enumerable: false });
468
+ return t;
469
+ };
470
+ var fileToolBindingOf = (t) => t && typeof t === "object" ? t[FILE_TOOL] : void 0;
471
+ var createFileTools = (vfs, opts = {}) => {
472
+ const p = opts.prefix ?? "fs_";
473
+ const maxRead = opts.maxReadChars ?? 5e4;
474
+ const tools = {
475
+ [`${p}list`]: markReadOnly(
476
+ tool({
477
+ description: "List the files in the workspace (attachments the user added, files you wrote). Optionally only under a directory prefix.",
478
+ inputSchema: jsonSchema({
479
+ type: "object",
480
+ properties: { prefix: { type: "string", description: 'Directory prefix, e.g. "/docs"' } },
481
+ additionalProperties: false
482
+ }),
483
+ execute: async ({ prefix }) => (await vfs.list(prefix || "/")).map((f) => ({
484
+ path: f.path,
485
+ mimeType: f.mimeType,
486
+ size: f.size
487
+ }))
488
+ })
489
+ ),
490
+ [`${p}read`]: markReadOnly(
491
+ tool({
492
+ description: "Read a text file from the workspace by its path.",
493
+ inputSchema: jsonSchema({
494
+ type: "object",
495
+ properties: { path: { type: "string", description: 'Absolute path, e.g. "/notes.md"' } },
496
+ required: ["path"],
497
+ additionalProperties: false
498
+ }),
499
+ execute: async ({ path }) => {
500
+ const f = await vfs.read(path);
501
+ if (!f) {
502
+ const known = (await vfs.list()).map((x) => x.path).slice(0, 30);
503
+ throw new Error(`no file "${path}"; files: ${known.join(", ") || "none"}`);
504
+ }
505
+ if (f.encoding === "base64" && !isTextMime(f.mimeType)) {
506
+ return `"${f.path}" is a binary file (${f.mimeType}, ${f.size} bytes) and cannot be read as text.`;
507
+ }
508
+ const text = f.encoding === "base64" ? atob(f.content) : f.content;
509
+ return text.length > maxRead ? `${text.slice(0, maxRead)}\u2026 [truncated ${text.length - maxRead} chars]` : text;
510
+ }
511
+ })
512
+ )
513
+ };
514
+ bind(tools[`${p}list`], { vfs, op: "list" });
515
+ bind(tools[`${p}read`], { vfs, op: "read" });
516
+ if (opts.readOnly) return tools;
517
+ tools[`${p}write`] = tool({
518
+ description: "Write a text file to the workspace (creates or replaces it). Use it for reports, drafts, data the user should be able to open.",
519
+ inputSchema: jsonSchema({
520
+ type: "object",
521
+ properties: {
522
+ path: { type: "string", description: 'Absolute path, e.g. "/reports/summary.md"' },
523
+ content: { type: "string", description: "The full file content" },
524
+ mimeType: { type: "string", description: "Optional MIME type (guessed from the name)" }
525
+ },
526
+ required: ["path", "content"],
527
+ additionalProperties: false
528
+ }),
529
+ execute: async ({ path, content, mimeType }) => {
530
+ const info = await vfs.write(path, content, mimeType ? { mimeType } : {});
531
+ return { written: info.path, size: info.size };
532
+ }
533
+ });
534
+ tools[`${p}delete`] = tool({
535
+ description: "Delete a file from the workspace.",
536
+ inputSchema: jsonSchema({
537
+ type: "object",
538
+ properties: { path: { type: "string" } },
539
+ required: ["path"],
540
+ additionalProperties: false
541
+ }),
542
+ execute: async ({ path }) => ({ deleted: await vfs.delete(path) })
543
+ });
544
+ bind(tools[`${p}write`], { vfs, op: "write" });
545
+ bind(tools[`${p}delete`], { vfs, op: "delete" });
546
+ return tools;
547
+ };
548
+
549
+ export {
550
+ checkLimits,
551
+ ToolBudgetError,
552
+ TOOL_APPROVAL_MODES,
553
+ ToolDeniedError,
554
+ markReadOnly,
555
+ isReadOnlyTool,
556
+ matchRule,
557
+ decideToolPermission,
558
+ createApprovalState,
559
+ promptHintOf,
560
+ toolRunContextOf,
561
+ limitModelOutput,
562
+ wrapToolsForRun,
563
+ createCallCounter,
564
+ schemaHintOf,
565
+ mimeFromPath,
566
+ isTextMime,
567
+ normalizePath,
568
+ bytesToBase64,
569
+ VirtualFileSystem,
570
+ fileToolBindingOf,
571
+ createFileTools
572
+ };
573
+ //# sourceMappingURL=chunk-AY2BZYZY.js.map