@dudko.dev/agent-web 0.0.37 → 0.0.39
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +179 -7
- package/dist/agent-web.js +315 -125
- package/dist/agent-web.js.map +1 -1
- package/dist/{chunk-Y7OGKYE5.js → chunk-3V27UZT6.js} +35 -9
- package/dist/chunk-3V27UZT6.js.map +1 -0
- package/dist/chunk-A6ZJALLU.js +254 -0
- package/dist/chunk-A6ZJALLU.js.map +1 -0
- package/dist/chunk-CTXDKSDD.js +39 -0
- package/dist/chunk-CTXDKSDD.js.map +1 -0
- package/dist/chunk-TZITKUFW.js +800 -0
- package/dist/chunk-TZITKUFW.js.map +1 -0
- package/dist/chunk-V3JOK7EW.js +929 -0
- package/dist/chunk-V3JOK7EW.js.map +1 -0
- package/dist/index.cjs +7253 -2159
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1714 -324
- package/dist/index.d.ts +1714 -324
- package/dist/index.js +3832 -862
- package/dist/index.js.map +1 -1
- package/dist/mcp.cjs +1031 -24
- package/dist/mcp.cjs.map +1 -1
- package/dist/mcp.d.cts +409 -13
- package/dist/mcp.d.ts +409 -13
- package/dist/mcp.js +918 -26
- package/dist/mcp.js.map +1 -1
- package/dist/sandbox-KG6OUG24.js +269 -0
- package/dist/sandbox-KG6OUG24.js.map +1 -0
- package/dist/sandbox-worker.cjs +745 -0
- package/dist/sandbox-worker.cjs.map +1 -0
- package/dist/sandbox-worker.d.cts +37 -0
- package/dist/sandbox-worker.d.ts +37 -0
- package/dist/sandbox-worker.js +27 -0
- package/dist/sandbox-worker.js.map +1 -0
- package/dist/{webllm-PCPDLDQA.js → webllm-BEL5A4OF.js} +2 -2
- package/package.json +23 -4
- package/dist/chunk-CPSDKXO6.js +0 -132
- package/dist/chunk-CPSDKXO6.js.map +0 -1
- package/dist/chunk-Y7OGKYE5.js.map +0 -1
- /package/dist/{webllm-PCPDLDQA.js.map → webllm-BEL5A4OF.js.map} +0 -0
|
@@ -0,0 +1,800 @@
|
|
|
1
|
+
import {
|
|
2
|
+
FILES_STORE,
|
|
3
|
+
openAgentWebDB
|
|
4
|
+
} from "./chunk-CTXDKSDD.js";
|
|
5
|
+
|
|
6
|
+
// src/limits.ts
|
|
7
|
+
var over = (value, cap2) => typeof cap2 === "number" && cap2 > 0 && (value ?? 0) >= cap2;
|
|
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(cap2) {
|
|
30
|
+
super(
|
|
31
|
+
`Tool-call budget exhausted (${cap2} 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/tiers.ts
|
|
178
|
+
var MODEL_TIERS = ["light", "standard", "strong"];
|
|
179
|
+
var TIER_OF = {
|
|
180
|
+
low: "light",
|
|
181
|
+
medium: "standard",
|
|
182
|
+
high: "strong"
|
|
183
|
+
};
|
|
184
|
+
var pickTier = (complexity, configured) => {
|
|
185
|
+
const wanted = complexity ? TIER_OF[complexity] : "standard";
|
|
186
|
+
if (configured.has(wanted)) {
|
|
187
|
+
return { tier: wanted, reason: complexity ? "planned" : "default" };
|
|
188
|
+
}
|
|
189
|
+
const at = MODEL_TIERS.indexOf(wanted);
|
|
190
|
+
let best;
|
|
191
|
+
let bestDistance = Infinity;
|
|
192
|
+
for (const tier of MODEL_TIERS) {
|
|
193
|
+
if (!configured.has(tier)) {
|
|
194
|
+
continue;
|
|
195
|
+
}
|
|
196
|
+
const distance = Math.abs(MODEL_TIERS.indexOf(tier) - at);
|
|
197
|
+
if (distance <= bestDistance) {
|
|
198
|
+
best = tier;
|
|
199
|
+
bestDistance = distance;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
if (!best) {
|
|
203
|
+
throw new Error("no executor tier is configured");
|
|
204
|
+
}
|
|
205
|
+
return { tier: best, reason: "fallback" };
|
|
206
|
+
};
|
|
207
|
+
var nextStrongerTier = (tier, configured) => MODEL_TIERS.slice(MODEL_TIERS.indexOf(tier) + 1).find((t) => configured.has(t));
|
|
208
|
+
var DEFAULT_ESCALATIONS_PER_STEP = 1;
|
|
209
|
+
var DEFAULT_ESCALATIONS_PER_RUN = 3;
|
|
210
|
+
var cap = (v, fallback) => typeof v === "number" && Number.isFinite(v) && v >= 0 ? Math.floor(v) : fallback;
|
|
211
|
+
var resolveEscalation = (setting, tiersActive) => {
|
|
212
|
+
const cfg = typeof setting === "object" && setting !== null ? setting : {};
|
|
213
|
+
const maxPerStep = cap(cfg.maxPerStep, DEFAULT_ESCALATIONS_PER_STEP);
|
|
214
|
+
const maxPerRun = cap(cfg.maxPerRun, DEFAULT_ESCALATIONS_PER_RUN);
|
|
215
|
+
return {
|
|
216
|
+
enabled: tiersActive && setting !== false && maxPerStep > 0 && maxPerRun > 0,
|
|
217
|
+
maxPerStep,
|
|
218
|
+
maxPerRun
|
|
219
|
+
};
|
|
220
|
+
};
|
|
221
|
+
var nameOf = (v) => v && typeof v === "object" && typeof v.name === "string" ? v.name : "";
|
|
222
|
+
var textOf = (v) => {
|
|
223
|
+
if (typeof v === "string") {
|
|
224
|
+
return v;
|
|
225
|
+
}
|
|
226
|
+
if (v && typeof v === "object" && typeof v.message === "string") {
|
|
227
|
+
return v.message;
|
|
228
|
+
}
|
|
229
|
+
return "";
|
|
230
|
+
};
|
|
231
|
+
var isDeniedOutput = (output) => nameOf(output) === "ToolDeniedError" || /Tool call denied by the user/.test(textOf(output));
|
|
232
|
+
var isBudgetOutput = (output) => nameOf(output) === "ToolBudgetError" || /tool-call budget exhausted/i.test(textOf(output));
|
|
233
|
+
var isInvalidArgumentsOutput = (output) => /InvalidToolInput|InvalidToolArguments|ToolCallRepair/.test(nameOf(output)) || /InvalidToolInputError|Invalid input for tool |^invalid args for "/i.test(textOf(output));
|
|
234
|
+
var argumentsKeptFailing = (calls) => {
|
|
235
|
+
const bad = /* @__PURE__ */ new Map();
|
|
236
|
+
calls.forEach((c, i) => {
|
|
237
|
+
if (!c.ok && isInvalidArgumentsOutput(c.output)) {
|
|
238
|
+
bad.set(c.name, [...bad.get(c.name) ?? [], i]);
|
|
239
|
+
}
|
|
240
|
+
});
|
|
241
|
+
return [...bad].some(
|
|
242
|
+
([name, at]) => at.length >= 2 && !calls.slice(at[at.length - 1] + 1).some((c) => c.ok && c.name === name)
|
|
243
|
+
);
|
|
244
|
+
};
|
|
245
|
+
var escalationReasonOf = (o) => {
|
|
246
|
+
if (o.stopped || o.toolCalls.some((c) => !c.ok && isBudgetOutput(c.output))) {
|
|
247
|
+
return void 0;
|
|
248
|
+
}
|
|
249
|
+
if (o.toolCalls.some((c) => !c.ok && isDeniedOutput(c.output))) {
|
|
250
|
+
return void 0;
|
|
251
|
+
}
|
|
252
|
+
if (o.cut) {
|
|
253
|
+
return "output-cut";
|
|
254
|
+
}
|
|
255
|
+
if (o.blocked) {
|
|
256
|
+
return "blocked";
|
|
257
|
+
}
|
|
258
|
+
if (argumentsKeptFailing(o.toolCalls)) {
|
|
259
|
+
return "tool-arguments";
|
|
260
|
+
}
|
|
261
|
+
if (o.empty && !o.toolCalls.some((c) => c.ok)) {
|
|
262
|
+
return "empty-result";
|
|
263
|
+
}
|
|
264
|
+
return void 0;
|
|
265
|
+
};
|
|
266
|
+
var statusIn = (err, match, seen = /* @__PURE__ */ new Set()) => {
|
|
267
|
+
if (!err || typeof err !== "object" || seen.has(err)) {
|
|
268
|
+
return false;
|
|
269
|
+
}
|
|
270
|
+
seen.add(err);
|
|
271
|
+
const e = err;
|
|
272
|
+
const status = e.statusCode ?? e.status;
|
|
273
|
+
if (typeof status === "number" && match(status)) {
|
|
274
|
+
return true;
|
|
275
|
+
}
|
|
276
|
+
return statusIn(e.cause, match, seen) || statusIn(e.lastError, match, seen);
|
|
277
|
+
};
|
|
278
|
+
var isEscalatableError = (err) => {
|
|
279
|
+
const name = nameOf(err);
|
|
280
|
+
if (name === "AbortError" || name === "TimeoutError") {
|
|
281
|
+
return false;
|
|
282
|
+
}
|
|
283
|
+
if (isDeniedOutput(err) || isBudgetOutput(err)) {
|
|
284
|
+
return false;
|
|
285
|
+
}
|
|
286
|
+
return !statusIn(err, (s) => s === 401 || s === 403 || s === 429);
|
|
287
|
+
};
|
|
288
|
+
var INPUT_CHARS = 400;
|
|
289
|
+
var OUTPUT_CHARS = 1500;
|
|
290
|
+
var asText = (v, max) => {
|
|
291
|
+
let s;
|
|
292
|
+
try {
|
|
293
|
+
s = typeof v === "string" ? v : JSON.stringify(v) ?? String(v);
|
|
294
|
+
} catch {
|
|
295
|
+
s = String(v);
|
|
296
|
+
}
|
|
297
|
+
return s.length > max ? `${s.slice(0, max)}... [truncated, ${s.length - max} chars]` : s;
|
|
298
|
+
};
|
|
299
|
+
var WHY = {
|
|
300
|
+
blocked: "it reported that it was blocked",
|
|
301
|
+
"empty-result": "it produced no result",
|
|
302
|
+
"tool-arguments": "it kept calling a tool with arguments that did not parse",
|
|
303
|
+
"output-cut": "its output was cut off by the output cap",
|
|
304
|
+
error: "its model call failed"
|
|
305
|
+
};
|
|
306
|
+
var renderEarlierAttempts = (attempts) => {
|
|
307
|
+
if (attempts.length === 0) {
|
|
308
|
+
return "";
|
|
309
|
+
}
|
|
310
|
+
const blocks = attempts.map((a, i) => {
|
|
311
|
+
const calls = a.toolCalls.length ? a.toolCalls.map(
|
|
312
|
+
(c) => ` - ${c.name} ${asText(c.input, INPUT_CHARS)} -> ${c.ok ? "ok" : "FAILED"}: ${asText(c.output, OUTPUT_CHARS)}`
|
|
313
|
+
).join("\n") : " (no tool calls)";
|
|
314
|
+
return [
|
|
315
|
+
`Attempt ${i + 1} (${a.tier} model) stopped because ${WHY[a.reason]}.`,
|
|
316
|
+
` It said: ${asText(a.summary, OUTPUT_CHARS) || "(nothing)"}`,
|
|
317
|
+
" Tool calls it made:",
|
|
318
|
+
calls
|
|
319
|
+
].join("\n");
|
|
320
|
+
});
|
|
321
|
+
return [
|
|
322
|
+
"EARLIER ATTEMPT AT THIS STEP - a smaller model started this step and did not finish it. You are continuing it, not starting over.",
|
|
323
|
+
"Every tool call below marked ok was REALLY executed and its effect is already in place: do not make it again, use its result. Redo only what FAILED or is still missing.",
|
|
324
|
+
...blocks
|
|
325
|
+
].join("\n");
|
|
326
|
+
};
|
|
327
|
+
var stable = (v) => {
|
|
328
|
+
if (Array.isArray(v)) {
|
|
329
|
+
return v.map(stable);
|
|
330
|
+
}
|
|
331
|
+
if (v && typeof v === "object") {
|
|
332
|
+
return Object.fromEntries(
|
|
333
|
+
Object.keys(v).sort().map((k) => [k, stable(v[k])])
|
|
334
|
+
);
|
|
335
|
+
}
|
|
336
|
+
return v;
|
|
337
|
+
};
|
|
338
|
+
var toolCallKey = (name, input) => {
|
|
339
|
+
try {
|
|
340
|
+
return `${name}\0${JSON.stringify(stable(input)) ?? ""}`;
|
|
341
|
+
} catch {
|
|
342
|
+
return `${name}\0${String(input)}`;
|
|
343
|
+
}
|
|
344
|
+
};
|
|
345
|
+
var createStepWrites = () => ({ attempt: 0, done: /* @__PURE__ */ new Map() });
|
|
346
|
+
var replayedWrite = (writes, name, input) => {
|
|
347
|
+
const hit = writes?.done.get(toolCallKey(name, input));
|
|
348
|
+
return hit && hit.attempt < writes.attempt ? { output: hit.output } : void 0;
|
|
349
|
+
};
|
|
350
|
+
var recordWrite = (writes, name, input, output) => {
|
|
351
|
+
writes?.done.set(toolCallKey(name, input), { attempt: writes.attempt, output });
|
|
352
|
+
};
|
|
353
|
+
var REPLAY_NOTE = "[not run again: this exact call already succeeded in an earlier attempt at this step, and its effect is in place. Its result then:]";
|
|
354
|
+
var replayOutput = (output) => `${REPLAY_NOTE} ${asText(output, 2e4)}`;
|
|
355
|
+
var isReplayedToolOutput = (output) => typeof output === "string" && output.startsWith(REPLAY_NOTE);
|
|
356
|
+
|
|
357
|
+
// src/tools/types.ts
|
|
358
|
+
var promptHintOf = (tool2) => typeof tool2.promptHint === "string" ? tool2.promptHint : void 0;
|
|
359
|
+
|
|
360
|
+
// src/tools/wrap.ts
|
|
361
|
+
import { asSchema } from "ai";
|
|
362
|
+
var toolRunContextOf = (options) => options?.agentRun;
|
|
363
|
+
var truncated = (s, max) => s.length > max ? `${s.slice(0, max)}\u2026 [truncated ${s.length - max} chars]` : s;
|
|
364
|
+
var toText = (v) => {
|
|
365
|
+
if (typeof v === "string") return v;
|
|
366
|
+
try {
|
|
367
|
+
return JSON.stringify(v) ?? String(v);
|
|
368
|
+
} catch {
|
|
369
|
+
return String(v);
|
|
370
|
+
}
|
|
371
|
+
};
|
|
372
|
+
var limitModelOutput = (original, maxChars) => (async (opts) => {
|
|
373
|
+
const base = original ? await original(opts) : typeof opts.output === "string" ? { type: "text", value: opts.output } : { type: "json", value: opts.output ?? null };
|
|
374
|
+
if (base.type === "text" || base.type === "error-text") {
|
|
375
|
+
return { ...base, value: truncated(base.value, maxChars) };
|
|
376
|
+
}
|
|
377
|
+
if (base.type === "json" || base.type === "error-json") {
|
|
378
|
+
const text = toText(base.value);
|
|
379
|
+
if (text.length <= maxChars) return base;
|
|
380
|
+
return {
|
|
381
|
+
type: base.type === "json" ? "text" : "error-text",
|
|
382
|
+
value: truncated(text, maxChars)
|
|
383
|
+
};
|
|
384
|
+
}
|
|
385
|
+
return base;
|
|
386
|
+
});
|
|
387
|
+
var isAsyncIterable = (v) => typeof v === "object" && v !== null && Symbol.asyncIterator in v;
|
|
388
|
+
var recording = (out, record) => {
|
|
389
|
+
if (isAsyncIterable(out)) {
|
|
390
|
+
return (async function* () {
|
|
391
|
+
let last;
|
|
392
|
+
for await (const value of out) {
|
|
393
|
+
last = value;
|
|
394
|
+
yield value;
|
|
395
|
+
}
|
|
396
|
+
record(last);
|
|
397
|
+
})();
|
|
398
|
+
}
|
|
399
|
+
if (out && typeof out.then === "function") {
|
|
400
|
+
return out.then((value) => {
|
|
401
|
+
record(value);
|
|
402
|
+
return value;
|
|
403
|
+
});
|
|
404
|
+
}
|
|
405
|
+
record(out);
|
|
406
|
+
return out;
|
|
407
|
+
};
|
|
408
|
+
var wrapToolsForRun = (tools, o) => {
|
|
409
|
+
const out = {};
|
|
410
|
+
const gate = (toolName, input, readOnly, signal) => gateToolCall(
|
|
411
|
+
o.approval,
|
|
412
|
+
{
|
|
413
|
+
toolName,
|
|
414
|
+
input,
|
|
415
|
+
readOnly,
|
|
416
|
+
step: o.step(),
|
|
417
|
+
...o.subagent ? { subagent: o.subagent } : {}
|
|
418
|
+
},
|
|
419
|
+
{
|
|
420
|
+
requested: (req) => o.emit({
|
|
421
|
+
type: "tool.approval-requested",
|
|
422
|
+
id: req.id,
|
|
423
|
+
name: req.toolName,
|
|
424
|
+
input: req.input,
|
|
425
|
+
readOnly: req.readOnly,
|
|
426
|
+
step: req.step,
|
|
427
|
+
...req.subagent ? { subagent: req.subagent } : {}
|
|
428
|
+
}),
|
|
429
|
+
resolved: (r) => o.emit({ type: "tool.approval-resolved", ...r })
|
|
430
|
+
},
|
|
431
|
+
signal ?? o.signal
|
|
432
|
+
);
|
|
433
|
+
for (const [name, t] of Object.entries(tools)) {
|
|
434
|
+
const execute = t.execute;
|
|
435
|
+
const builtin = o.builtins.has(name);
|
|
436
|
+
const readOnly = builtin || isReadOnlyTool(t);
|
|
437
|
+
const wrapped = { ...t };
|
|
438
|
+
if (o.maxToolOutputChars > 0) {
|
|
439
|
+
wrapped.toModelOutput = limitModelOutput(t.toModelOutput, o.maxToolOutputChars);
|
|
440
|
+
}
|
|
441
|
+
if (typeof execute === "function") {
|
|
442
|
+
wrapped.execute = (input, options) => {
|
|
443
|
+
const writes = readOnly ? void 0 : o.stepWrites?.();
|
|
444
|
+
const earlier = replayedWrite(writes, name, input);
|
|
445
|
+
if (earlier) return replayOutput(earlier.output);
|
|
446
|
+
const call = () => {
|
|
447
|
+
if (!builtin) o.countCall();
|
|
448
|
+
const agentRun = {
|
|
449
|
+
emit: o.emit,
|
|
450
|
+
step: o.step(),
|
|
451
|
+
signal: o.signal,
|
|
452
|
+
addUsage: o.addUsage,
|
|
453
|
+
...o.usage ? { usage: o.usage } : {},
|
|
454
|
+
approve: (toolName, toolInput, ro) => gate(toolName, toolInput, ro),
|
|
455
|
+
...o.control ? { control: o.control } : {},
|
|
456
|
+
...o.runId ? { runId: o.runId } : {},
|
|
457
|
+
...o.fetched ? { fetched: o.fetched } : {},
|
|
458
|
+
...o.spawn ? { spawn: o.spawn } : {}
|
|
459
|
+
};
|
|
460
|
+
return execute.call(t, input, { ...options, agentRun });
|
|
461
|
+
};
|
|
462
|
+
const run = () => writes ? recording(call(), (value) => recordWrite(writes, name, input, value)) : call();
|
|
463
|
+
if (builtin) return run();
|
|
464
|
+
const permission = decideToolPermission({
|
|
465
|
+
toolName: name,
|
|
466
|
+
readOnly,
|
|
467
|
+
mode: o.approval.mode,
|
|
468
|
+
rules: o.approval.config.rules,
|
|
469
|
+
remembered: o.approval.remembered
|
|
470
|
+
});
|
|
471
|
+
if (permission === "allow") return run();
|
|
472
|
+
return gate(
|
|
473
|
+
name,
|
|
474
|
+
input,
|
|
475
|
+
readOnly,
|
|
476
|
+
options?.abortSignal
|
|
477
|
+
).then(run);
|
|
478
|
+
};
|
|
479
|
+
}
|
|
480
|
+
out[name] = wrapped;
|
|
481
|
+
}
|
|
482
|
+
return out;
|
|
483
|
+
};
|
|
484
|
+
var createCallCounter = (cap2, initial = 0) => {
|
|
485
|
+
let calls = Math.max(0, Math.floor(initial));
|
|
486
|
+
return {
|
|
487
|
+
count: () => {
|
|
488
|
+
if (cap2 && cap2 > 0 && calls >= cap2) throw new ToolBudgetError(cap2);
|
|
489
|
+
calls += 1;
|
|
490
|
+
},
|
|
491
|
+
get calls() {
|
|
492
|
+
return calls;
|
|
493
|
+
},
|
|
494
|
+
get exhausted() {
|
|
495
|
+
return Boolean(cap2 && cap2 > 0 && calls >= cap2);
|
|
496
|
+
}
|
|
497
|
+
};
|
|
498
|
+
};
|
|
499
|
+
var typeHint = (s, depth) => {
|
|
500
|
+
if (!s) return "any";
|
|
501
|
+
if (Array.isArray(s.enum) && s.enum.length > 0 && s.enum.length <= 8) {
|
|
502
|
+
return s.enum.map((v) => JSON.stringify(v)).join(" | ");
|
|
503
|
+
}
|
|
504
|
+
const type = Array.isArray(s.type) ? s.type.find((x) => x !== "null") : s.type;
|
|
505
|
+
if (type === "array") return `${typeHint(s.items, depth)}[]`;
|
|
506
|
+
if (type === "object" || s.properties) {
|
|
507
|
+
if (depth > 1 || !s.properties) return "object";
|
|
508
|
+
return objectHint(s, depth + 1);
|
|
509
|
+
}
|
|
510
|
+
return type ?? "any";
|
|
511
|
+
};
|
|
512
|
+
var objectHint = (s, depth = 0) => {
|
|
513
|
+
const required = new Set(s.required ?? []);
|
|
514
|
+
const props = Object.entries(s.properties ?? {});
|
|
515
|
+
if (props.length === 0) return "{}";
|
|
516
|
+
return `{ ${props.slice(0, 12).map(([k, v]) => `${k}${required.has(k) ? "" : "?"}: ${typeHint(v, depth)}`).join(", ")}${props.length > 12 ? ", \u2026" : ""} }`;
|
|
517
|
+
};
|
|
518
|
+
var schemaHintOf = async (t) => {
|
|
519
|
+
const own = promptHintOf(t);
|
|
520
|
+
if (own) return own;
|
|
521
|
+
try {
|
|
522
|
+
const schema = await asSchema(t.inputSchema).jsonSchema;
|
|
523
|
+
return schema && typeof schema === "object" ? objectHint(schema) : void 0;
|
|
524
|
+
} catch {
|
|
525
|
+
return void 0;
|
|
526
|
+
}
|
|
527
|
+
};
|
|
528
|
+
|
|
529
|
+
// src/files/vfs.ts
|
|
530
|
+
var MIME = {
|
|
531
|
+
txt: "text/plain",
|
|
532
|
+
md: "text/markdown",
|
|
533
|
+
json: "application/json",
|
|
534
|
+
csv: "text/csv",
|
|
535
|
+
html: "text/html",
|
|
536
|
+
css: "text/css",
|
|
537
|
+
js: "text/javascript",
|
|
538
|
+
ts: "text/typescript",
|
|
539
|
+
svg: "image/svg+xml",
|
|
540
|
+
png: "image/png",
|
|
541
|
+
jpg: "image/jpeg",
|
|
542
|
+
jpeg: "image/jpeg",
|
|
543
|
+
gif: "image/gif",
|
|
544
|
+
webp: "image/webp",
|
|
545
|
+
pdf: "application/pdf",
|
|
546
|
+
xml: "application/xml",
|
|
547
|
+
yaml: "text/yaml",
|
|
548
|
+
yml: "text/yaml"
|
|
549
|
+
};
|
|
550
|
+
var mimeFromPath = (path) => MIME[path.split(".").pop()?.toLowerCase() ?? ""] ?? "application/octet-stream";
|
|
551
|
+
var isTextMime = (mime) => /^text\/|json|xml|yaml|javascript|typescript|svg/.test(mime);
|
|
552
|
+
var normalizePath = (input) => {
|
|
553
|
+
const parts = [];
|
|
554
|
+
for (const seg of String(input ?? "").replace(/\\/g, "/").split("/")) {
|
|
555
|
+
if (!seg || seg === ".") continue;
|
|
556
|
+
if (seg === "..") {
|
|
557
|
+
if (parts.length === 0) throw new Error(`path "${input}" escapes the root`);
|
|
558
|
+
parts.pop();
|
|
559
|
+
continue;
|
|
560
|
+
}
|
|
561
|
+
parts.push(seg);
|
|
562
|
+
}
|
|
563
|
+
if (parts.length === 0) throw new Error("a file path is required");
|
|
564
|
+
return `/${parts.join("/")}`;
|
|
565
|
+
};
|
|
566
|
+
var byteLength = (content, encoding) => encoding === "base64" ? Math.floor(content.replace(/=+$/, "").length * 3 / 4) : new TextEncoder().encode(content).length;
|
|
567
|
+
var bytesToBase64 = (bytes) => {
|
|
568
|
+
let bin = "";
|
|
569
|
+
for (let i = 0; i < bytes.length; i += 32768) {
|
|
570
|
+
bin += String.fromCharCode(...bytes.subarray(i, i + 32768));
|
|
571
|
+
}
|
|
572
|
+
return btoa(bin);
|
|
573
|
+
};
|
|
574
|
+
var VirtualFileSystem = class {
|
|
575
|
+
memory;
|
|
576
|
+
dbName;
|
|
577
|
+
ns;
|
|
578
|
+
maxFileBytes;
|
|
579
|
+
listeners = /* @__PURE__ */ new Set();
|
|
580
|
+
constructor(opts = {}) {
|
|
581
|
+
if (opts.memory) this.memory = /* @__PURE__ */ new Map();
|
|
582
|
+
this.dbName = opts.dbName;
|
|
583
|
+
this.ns = opts.namespace ?? "default";
|
|
584
|
+
this.maxFileBytes = opts.maxFileBytes ?? 10 * 1024 * 1024;
|
|
585
|
+
}
|
|
586
|
+
key(path) {
|
|
587
|
+
return `${this.ns}:${path}`;
|
|
588
|
+
}
|
|
589
|
+
/** Subscribe to writes and deletes (e.g. to refresh a file list). Returns an unsubscribe. */
|
|
590
|
+
onChange(listener) {
|
|
591
|
+
this.listeners.add(listener);
|
|
592
|
+
return () => this.listeners.delete(listener);
|
|
593
|
+
}
|
|
594
|
+
notify(type, path) {
|
|
595
|
+
for (const l of this.listeners) {
|
|
596
|
+
try {
|
|
597
|
+
l({ type, path });
|
|
598
|
+
} catch {
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
async write(path, content, opts = {}) {
|
|
603
|
+
const p = normalizePath(path);
|
|
604
|
+
const binary = content instanceof Uint8Array;
|
|
605
|
+
const encoding = binary ? "base64" : opts.encoding ?? "utf8";
|
|
606
|
+
const text = binary ? bytesToBase64(content) : content;
|
|
607
|
+
const size = binary ? content.length : byteLength(text, encoding);
|
|
608
|
+
if (size > this.maxFileBytes) {
|
|
609
|
+
throw new Error(`"${p}" is ${size} bytes; the limit is ${this.maxFileBytes}`);
|
|
610
|
+
}
|
|
611
|
+
const file = {
|
|
612
|
+
path: p,
|
|
613
|
+
content: text,
|
|
614
|
+
encoding,
|
|
615
|
+
mimeType: opts.mimeType ?? mimeFromPath(p),
|
|
616
|
+
size,
|
|
617
|
+
updatedAt: Date.now()
|
|
618
|
+
};
|
|
619
|
+
if (this.memory) this.memory.set(p, file);
|
|
620
|
+
else {
|
|
621
|
+
const db = await openAgentWebDB({ dbName: this.dbName });
|
|
622
|
+
await db.put(FILES_STORE, file, this.key(p));
|
|
623
|
+
}
|
|
624
|
+
this.notify("write", p);
|
|
625
|
+
const { content: _drop, ...info } = file;
|
|
626
|
+
return info;
|
|
627
|
+
}
|
|
628
|
+
/** Store a data URL ("data:image/png;base64,…") as a file. */
|
|
629
|
+
async writeDataUrl(path, dataUrl) {
|
|
630
|
+
const m = /^data:([^;,]+)?(;base64)?,(.*)$/s.exec(dataUrl);
|
|
631
|
+
if (!m) throw new Error("not a data URL");
|
|
632
|
+
const mimeType = m[1] ?? "application/octet-stream";
|
|
633
|
+
return m[2] ? this.write(path, m[3], { mimeType, encoding: "base64" }) : this.write(path, decodeURIComponent(m[3]), { mimeType });
|
|
634
|
+
}
|
|
635
|
+
async read(path) {
|
|
636
|
+
const p = normalizePath(path);
|
|
637
|
+
if (this.memory) return this.memory.get(p);
|
|
638
|
+
const db = await openAgentWebDB({ dbName: this.dbName });
|
|
639
|
+
return await db.get(FILES_STORE, this.key(p));
|
|
640
|
+
}
|
|
641
|
+
/** The file as a data URL (for <img src>, downloads). */
|
|
642
|
+
async readDataUrl(path) {
|
|
643
|
+
const f = await this.read(path);
|
|
644
|
+
if (!f) return void 0;
|
|
645
|
+
return f.encoding === "base64" ? `data:${f.mimeType};base64,${f.content}` : `data:${f.mimeType};charset=utf-8,${encodeURIComponent(f.content)}`;
|
|
646
|
+
}
|
|
647
|
+
async delete(path) {
|
|
648
|
+
const p = normalizePath(path);
|
|
649
|
+
let existed;
|
|
650
|
+
if (this.memory) existed = this.memory.delete(p);
|
|
651
|
+
else {
|
|
652
|
+
const db = await openAgentWebDB({ dbName: this.dbName });
|
|
653
|
+
existed = await db.get(FILES_STORE, this.key(p)) !== void 0;
|
|
654
|
+
await db.delete(FILES_STORE, this.key(p));
|
|
655
|
+
}
|
|
656
|
+
if (existed) this.notify("delete", p);
|
|
657
|
+
return existed;
|
|
658
|
+
}
|
|
659
|
+
/** Files under a prefix ("/" = all), sorted by path. */
|
|
660
|
+
async list(prefix = "/") {
|
|
661
|
+
const dir = prefix === "/" ? "/" : `${normalizePath(prefix)}/`;
|
|
662
|
+
let files;
|
|
663
|
+
if (this.memory) files = [...this.memory.values()];
|
|
664
|
+
else {
|
|
665
|
+
const db = await openAgentWebDB({ dbName: this.dbName });
|
|
666
|
+
const range = IDBKeyRange.bound(`${this.ns}:`, `${this.ns}:\uFFFF`);
|
|
667
|
+
files = await db.getAll(FILES_STORE, range);
|
|
668
|
+
}
|
|
669
|
+
return files.filter((f) => dir === "/" || f.path.startsWith(dir)).map(({ content: _drop, ...info }) => info).sort((a, b) => a.path.localeCompare(b.path));
|
|
670
|
+
}
|
|
671
|
+
/** Remove every file (of this namespace). */
|
|
672
|
+
async clear() {
|
|
673
|
+
for (const f of await this.list()) await this.delete(f.path);
|
|
674
|
+
}
|
|
675
|
+
};
|
|
676
|
+
|
|
677
|
+
// src/files/tools.ts
|
|
678
|
+
import { jsonSchema, tool } from "ai";
|
|
679
|
+
var FILE_TOOL = /* @__PURE__ */ Symbol.for("@dudko.dev/agent-web:file-tool");
|
|
680
|
+
var bind = (t, binding) => {
|
|
681
|
+
Object.defineProperty(t, FILE_TOOL, { value: binding, enumerable: false });
|
|
682
|
+
return t;
|
|
683
|
+
};
|
|
684
|
+
var fileToolBindingOf = (t) => t && typeof t === "object" ? t[FILE_TOOL] : void 0;
|
|
685
|
+
var createFileTools = (vfs, opts = {}) => {
|
|
686
|
+
const p = opts.prefix ?? "fs_";
|
|
687
|
+
const maxRead = opts.maxReadChars ?? 5e4;
|
|
688
|
+
const tools = {
|
|
689
|
+
[`${p}list`]: markReadOnly(
|
|
690
|
+
tool({
|
|
691
|
+
description: "List the files in the workspace (attachments the user added, files you wrote). Optionally only under a directory prefix.",
|
|
692
|
+
inputSchema: jsonSchema({
|
|
693
|
+
type: "object",
|
|
694
|
+
properties: { prefix: { type: "string", description: 'Directory prefix, e.g. "/docs"' } },
|
|
695
|
+
additionalProperties: false
|
|
696
|
+
}),
|
|
697
|
+
execute: async ({ prefix }) => (await vfs.list(prefix || "/")).map((f) => ({
|
|
698
|
+
path: f.path,
|
|
699
|
+
mimeType: f.mimeType,
|
|
700
|
+
size: f.size
|
|
701
|
+
}))
|
|
702
|
+
})
|
|
703
|
+
),
|
|
704
|
+
[`${p}read`]: markReadOnly(
|
|
705
|
+
tool({
|
|
706
|
+
description: "Read a text file from the workspace by its path.",
|
|
707
|
+
inputSchema: jsonSchema({
|
|
708
|
+
type: "object",
|
|
709
|
+
properties: { path: { type: "string", description: 'Absolute path, e.g. "/notes.md"' } },
|
|
710
|
+
required: ["path"],
|
|
711
|
+
additionalProperties: false
|
|
712
|
+
}),
|
|
713
|
+
execute: async ({ path }) => {
|
|
714
|
+
const f = await vfs.read(path);
|
|
715
|
+
if (!f) {
|
|
716
|
+
const known = (await vfs.list()).map((x) => x.path).slice(0, 30);
|
|
717
|
+
throw new Error(`no file "${path}"; files: ${known.join(", ") || "none"}`);
|
|
718
|
+
}
|
|
719
|
+
if (f.encoding === "base64" && !isTextMime(f.mimeType)) {
|
|
720
|
+
return `"${f.path}" is a binary file (${f.mimeType}, ${f.size} bytes) and cannot be read as text.`;
|
|
721
|
+
}
|
|
722
|
+
const text = f.encoding === "base64" ? atob(f.content) : f.content;
|
|
723
|
+
return text.length > maxRead ? `${text.slice(0, maxRead)}\u2026 [truncated ${text.length - maxRead} chars]` : text;
|
|
724
|
+
}
|
|
725
|
+
})
|
|
726
|
+
)
|
|
727
|
+
};
|
|
728
|
+
bind(tools[`${p}list`], { vfs, op: "list" });
|
|
729
|
+
bind(tools[`${p}read`], { vfs, op: "read" });
|
|
730
|
+
if (opts.readOnly) return tools;
|
|
731
|
+
tools[`${p}write`] = tool({
|
|
732
|
+
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.",
|
|
733
|
+
inputSchema: jsonSchema({
|
|
734
|
+
type: "object",
|
|
735
|
+
properties: {
|
|
736
|
+
path: { type: "string", description: 'Absolute path, e.g. "/reports/summary.md"' },
|
|
737
|
+
content: { type: "string", description: "The full file content" },
|
|
738
|
+
mimeType: { type: "string", description: "Optional MIME type (guessed from the name)" }
|
|
739
|
+
},
|
|
740
|
+
required: ["path", "content"],
|
|
741
|
+
additionalProperties: false
|
|
742
|
+
}),
|
|
743
|
+
execute: async ({ path, content, mimeType }) => {
|
|
744
|
+
const info = await vfs.write(path, content, mimeType ? { mimeType } : {});
|
|
745
|
+
return { written: info.path, size: info.size };
|
|
746
|
+
}
|
|
747
|
+
});
|
|
748
|
+
tools[`${p}delete`] = tool({
|
|
749
|
+
description: "Delete a file from the workspace.",
|
|
750
|
+
inputSchema: jsonSchema({
|
|
751
|
+
type: "object",
|
|
752
|
+
properties: { path: { type: "string" } },
|
|
753
|
+
required: ["path"],
|
|
754
|
+
additionalProperties: false
|
|
755
|
+
}),
|
|
756
|
+
execute: async ({ path }) => ({ deleted: await vfs.delete(path) })
|
|
757
|
+
});
|
|
758
|
+
bind(tools[`${p}write`], { vfs, op: "write" });
|
|
759
|
+
bind(tools[`${p}delete`], { vfs, op: "delete" });
|
|
760
|
+
return tools;
|
|
761
|
+
};
|
|
762
|
+
|
|
763
|
+
export {
|
|
764
|
+
checkLimits,
|
|
765
|
+
ToolBudgetError,
|
|
766
|
+
TOOL_APPROVAL_MODES,
|
|
767
|
+
ToolDeniedError,
|
|
768
|
+
markReadOnly,
|
|
769
|
+
isReadOnlyTool,
|
|
770
|
+
matchRule,
|
|
771
|
+
decideToolPermission,
|
|
772
|
+
createApprovalState,
|
|
773
|
+
MODEL_TIERS,
|
|
774
|
+
pickTier,
|
|
775
|
+
nextStrongerTier,
|
|
776
|
+
resolveEscalation,
|
|
777
|
+
escalationReasonOf,
|
|
778
|
+
isEscalatableError,
|
|
779
|
+
renderEarlierAttempts,
|
|
780
|
+
createStepWrites,
|
|
781
|
+
replayedWrite,
|
|
782
|
+
recordWrite,
|
|
783
|
+
REPLAY_NOTE,
|
|
784
|
+
replayOutput,
|
|
785
|
+
isReplayedToolOutput,
|
|
786
|
+
promptHintOf,
|
|
787
|
+
toolRunContextOf,
|
|
788
|
+
limitModelOutput,
|
|
789
|
+
wrapToolsForRun,
|
|
790
|
+
createCallCounter,
|
|
791
|
+
schemaHintOf,
|
|
792
|
+
mimeFromPath,
|
|
793
|
+
isTextMime,
|
|
794
|
+
normalizePath,
|
|
795
|
+
bytesToBase64,
|
|
796
|
+
VirtualFileSystem,
|
|
797
|
+
fileToolBindingOf,
|
|
798
|
+
createFileTools
|
|
799
|
+
};
|
|
800
|
+
//# sourceMappingURL=chunk-TZITKUFW.js.map
|