reasonally 0.4.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +56 -12
- package/dist/agent/bundled-commands.js +24 -0
- package/dist/agent/client.js +53 -3
- package/dist/agent/command-files.js +334 -0
- package/dist/agent/command-template.js +179 -0
- package/dist/agent/compact.js +58 -8
- package/dist/agent/context.js +82 -0
- package/dist/agent/loop.js +163 -32
- package/dist/agent/permissions.js +151 -1
- package/dist/agent/session.js +75 -6
- package/dist/agent/tools/index.js +9 -0
- package/dist/agent/tools/task.js +1 -1
- package/dist/agent/tools/web/ddg.js +131 -0
- package/dist/agent/tools/web/dom.js +9 -0
- package/dist/agent/tools/web/html.js +90 -0
- package/dist/agent/tools/web/page.js +218 -0
- package/dist/agent/tools/web-fetch.js +175 -0
- package/dist/agent/tools/web-search.js +158 -0
- package/dist/browser/guards.js +15 -0
- package/dist/browser/messages.js +61 -0
- package/dist/browser/sessions.js +2 -60
- package/dist/cli.js +1 -1
- package/dist/tui/app.js +172 -41
- package/dist/tui/args.js +4 -0
- package/dist/tui/commands.js +71 -15
- package/dist/tui/start.js +2 -0
- package/package.json +5 -2
package/dist/agent/loop.js
CHANGED
|
@@ -1,12 +1,20 @@
|
|
|
1
1
|
import { MessageAccumulator } from "./accumulate.js";
|
|
2
|
-
import { retryDelayMs, StreamError, streamChat } from "./client.js";
|
|
3
|
-
import { compactedMessages, estimateTokens, isContextOverflow, shouldCompact, splitForCompaction,
|
|
2
|
+
import { retryDelayMs, searchWeb, StreamError, streamChat, webUserAgent, } from "./client.js";
|
|
3
|
+
import { compactedMessages, contentText, estimateTokens, isContextOverflow, shouldCompact, splitForCompaction, summaryRequest, SUMMARY_SYSTEM, transcriptForSummary, } from "./compact.js";
|
|
4
|
+
import { elideForWire, withoutImages } from "./context.js";
|
|
4
5
|
import { costMicros } from "./cost.js";
|
|
5
|
-
import { alwaysLabel, decide, MODE_LABELS, rememberAllow, } from "./permissions.js";
|
|
6
|
+
import { alwaysLabel, decide, endBrowserTask, hostsIn, MODE_LABELS, rememberAllow, rememberBrowser, } from "./permissions.js";
|
|
6
7
|
import { toolSchemas } from "./tools/index.js";
|
|
7
8
|
import { MAX_PLAN_CHARS, partialPlan, PLAN_OUTCOME_LABELS, PLAN_TOOL, } from "./tools/plan.js";
|
|
8
9
|
import { HELPER_NOTE, MAX_PARALLEL_HELPERS } from "./tools/task.js";
|
|
10
|
+
import { WEB_FETCH_TOOL } from "./tools/web-fetch.js";
|
|
11
|
+
import { WEB_SEARCH_TOOL } from "./tools/web-search.js";
|
|
9
12
|
import { ToolInputError, truncateMiddle, } from "./tools/types.js";
|
|
13
|
+
/** A web tool the user turned off (a model may still try one it used earlier in the thread). */
|
|
14
|
+
const TURNED_OFF = {
|
|
15
|
+
[WEB_SEARCH_TOOL]: "Web search is turned off.",
|
|
16
|
+
[WEB_FETCH_TOOL]: "Reading web pages is turned off.",
|
|
17
|
+
};
|
|
10
18
|
/** Per request; keeps credit holds modest when several requests run at once. */
|
|
11
19
|
export const MAX_OUTPUT_TOKENS = 32_000;
|
|
12
20
|
/** Model calls per user message before the agent stops and asks. */
|
|
@@ -23,10 +31,11 @@ const PLAN_DRAFT_EVERY_MS = 50;
|
|
|
23
31
|
export function lastToldPlan(messages) {
|
|
24
32
|
for (let i = messages.length - 1; i >= 0; i--) {
|
|
25
33
|
const m = messages[i];
|
|
26
|
-
if ((m.role !== "user" && m.role !== "tool") ||
|
|
34
|
+
if ((m.role !== "user" && m.role !== "tool") || (m.role === "user" && m.synthetic))
|
|
27
35
|
continue;
|
|
28
|
-
const
|
|
29
|
-
const
|
|
36
|
+
const text = contentText(m.content);
|
|
37
|
+
const on = Math.max(text.lastIndexOf(PLAN_ON_NOTE), text.lastIndexOf(HELPER_PLAN_ON_NOTE));
|
|
38
|
+
const off = Math.max(text.lastIndexOf(PLAN_OFF_NOTE), text.startsWith(PLAN_APPROVED) ? 0 : -1);
|
|
30
39
|
if (on !== -1 || off !== -1)
|
|
31
40
|
return on > off;
|
|
32
41
|
}
|
|
@@ -48,9 +57,15 @@ export function sleep(ms, signal) {
|
|
|
48
57
|
signal.addEventListener("abort", onAbort, { once: true });
|
|
49
58
|
});
|
|
50
59
|
}
|
|
51
|
-
/** The conversation as sent: our own display-only fields stay out of the request. */
|
|
60
|
+
/** The conversation as sent: our own display-only fields and tags stay out of the request. */
|
|
52
61
|
export function wireMessages(messages) {
|
|
53
62
|
return messages.map((m) => {
|
|
63
|
+
if (m.role === "user" && (m.synthetic !== undefined || m.command !== undefined)) {
|
|
64
|
+
return { role: "user", content: m.content };
|
|
65
|
+
}
|
|
66
|
+
if (m.role === "tool" && m.elide !== undefined) {
|
|
67
|
+
return { role: "tool", tool_call_id: m.tool_call_id, content: m.content };
|
|
68
|
+
}
|
|
54
69
|
if (m.role !== "assistant")
|
|
55
70
|
return m;
|
|
56
71
|
const out = { role: "assistant", content: m.content };
|
|
@@ -61,6 +76,26 @@ export function wireMessages(messages) {
|
|
|
61
76
|
return out;
|
|
62
77
|
});
|
|
63
78
|
}
|
|
79
|
+
/** An image as a message part, in a data URL. */
|
|
80
|
+
const imagePart = (image) => ({
|
|
81
|
+
type: "image_url",
|
|
82
|
+
image_url: { url: `data:${image.mime};base64,${image.data}` },
|
|
83
|
+
});
|
|
84
|
+
/**
|
|
85
|
+
* The images a batch of tool calls returned, as one user message after their results (a tool
|
|
86
|
+
* message only holds text). Each call's images follow a line naming it.
|
|
87
|
+
*/
|
|
88
|
+
export function toolImagesMessage(batch) {
|
|
89
|
+
const content = [];
|
|
90
|
+
for (const { call, images } of batch) {
|
|
91
|
+
if (!images.length)
|
|
92
|
+
continue;
|
|
93
|
+
const what = images.length === 1 ? "Image" : `${images.length} images`;
|
|
94
|
+
content.push({ type: "text", text: `${what} from ${call.function.name} (${call.id}):` });
|
|
95
|
+
content.push(...images.map(imagePart));
|
|
96
|
+
}
|
|
97
|
+
return content.length ? { role: "user", content, synthetic: "tool-images" } : null;
|
|
98
|
+
}
|
|
64
99
|
const isAbort = (error, signal) => signal.aborted || error?.name === "AbortError";
|
|
65
100
|
export class Agent {
|
|
66
101
|
options;
|
|
@@ -77,10 +112,25 @@ export class Agent {
|
|
|
77
112
|
/** A token estimate after compaction, until the server reports usage again. */
|
|
78
113
|
estimatedTokens = null;
|
|
79
114
|
sleep;
|
|
115
|
+
/** What the web tools use: credentials are read when a search runs, so a new key applies. */
|
|
116
|
+
web;
|
|
80
117
|
constructor(options) {
|
|
81
118
|
this.options = options;
|
|
82
119
|
this.messages = [{ role: "system", content: options.systemPrompt }];
|
|
83
120
|
this.sleep = options.sleep ?? sleep;
|
|
121
|
+
this.web = {
|
|
122
|
+
fetch: (input, init) => (this.options.webFetch ?? fetch)(input, init),
|
|
123
|
+
fallback: (body, signal) => searchWeb({
|
|
124
|
+
apiBaseUrl: this.options.apiBaseUrl,
|
|
125
|
+
apiKey: this.options.apiKey,
|
|
126
|
+
body,
|
|
127
|
+
signal,
|
|
128
|
+
fetch: this.options.fetch,
|
|
129
|
+
client: this.options.client,
|
|
130
|
+
}),
|
|
131
|
+
userAgent: webUserAgent(options.client),
|
|
132
|
+
transport: options.webTransport,
|
|
133
|
+
};
|
|
84
134
|
}
|
|
85
135
|
get model() {
|
|
86
136
|
return this.options.model;
|
|
@@ -106,21 +156,57 @@ export class Agent {
|
|
|
106
156
|
this.lastUsage = null;
|
|
107
157
|
this.estimatedTokens = messages.length ? estimateTokens(this.messages) : null;
|
|
108
158
|
}
|
|
109
|
-
/**
|
|
110
|
-
|
|
159
|
+
/**
|
|
160
|
+
* Adds the user's message and works on it until done, stopped or failed. `images` (pasted or
|
|
161
|
+
* attached) go with it to models that take images; other models get the text alone. `command`
|
|
162
|
+
* is the slash command `text` came from, kept on the message for showing it.
|
|
163
|
+
*/
|
|
164
|
+
async *send(text, signal, images, command) {
|
|
111
165
|
const content = this.interrupted ? `${INTERRUPTED_NOTE}\n\n${text}` : text;
|
|
112
166
|
this.interrupted = false;
|
|
167
|
+
// Pages on sites the user links to open without asking, in the browser too (for this task).
|
|
168
|
+
// (A helper's prompt is the model's.)
|
|
169
|
+
if (!this.options.isHelper) {
|
|
170
|
+
const { allows } = this.options.permissions;
|
|
171
|
+
for (const host of hostsIn(text)) {
|
|
172
|
+
allows.hosts.add(host);
|
|
173
|
+
allows.browserTask.add(host);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
const pictures = images?.length && this.model.images ? images : [];
|
|
177
|
+
if (images?.length && !pictures.length) {
|
|
178
|
+
yield { type: "notice", text: "This model doesn't take images, so only the text was sent." };
|
|
179
|
+
}
|
|
180
|
+
const withPictures = (body) => pictures.length ? [{ type: "text", text: body }, ...pictures.map(imagePart)] : body;
|
|
113
181
|
const note = this.modeNote();
|
|
114
182
|
const last = this.messages.at(-1);
|
|
115
|
-
// After a failed request the user's message is still last: add to it
|
|
116
|
-
|
|
183
|
+
// After a failed request the user's message is still last: add to it (only when it's text the
|
|
184
|
+
// user typed: never images or a message the agent added).
|
|
185
|
+
if (last?.role === "user" && typeof last.content === "string" && !last.synthetic) {
|
|
117
186
|
const merged = `${last.content}\n\n${content}`;
|
|
118
|
-
last.content = note ? `${note}\n\n${merged}` : merged;
|
|
187
|
+
last.content = withPictures(note ? `${note}\n\n${merged}` : merged);
|
|
188
|
+
// Two messages in one: neither command describes it any more.
|
|
189
|
+
delete last.command;
|
|
119
190
|
this.replaceAll(this.messages.slice(1), "merge");
|
|
120
191
|
}
|
|
121
|
-
else
|
|
122
|
-
this.append({
|
|
123
|
-
|
|
192
|
+
else {
|
|
193
|
+
this.append({
|
|
194
|
+
role: "user",
|
|
195
|
+
content: withPictures(note ? `${note}\n\n${content}` : content),
|
|
196
|
+
...(command ? { command } : {}),
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
yield* this.turn(signal);
|
|
200
|
+
}
|
|
201
|
+
/** Works until done; the task's browser grants end with the turn (a helper's turn is its parent's). */
|
|
202
|
+
async *turn(signal) {
|
|
203
|
+
try {
|
|
204
|
+
yield* this.work(signal);
|
|
205
|
+
}
|
|
206
|
+
finally {
|
|
207
|
+
if (!this.options.isHelper)
|
|
208
|
+
endBrowserTask(this.options.permissions.allows);
|
|
209
|
+
}
|
|
124
210
|
}
|
|
125
211
|
/**
|
|
126
212
|
* A note for the model when Plan mode starts or stops applying, else null. The note goes in
|
|
@@ -136,19 +222,33 @@ export class Agent {
|
|
|
136
222
|
return PLAN_OFF_NOTE;
|
|
137
223
|
return this.options.isHelper ? HELPER_PLAN_ON_NOTE : PLAN_ON_NOTE;
|
|
138
224
|
}
|
|
139
|
-
/**
|
|
140
|
-
|
|
225
|
+
/**
|
|
226
|
+
* Adds a tool result (with a mode note when the mode changed since the model last heard). With
|
|
227
|
+
* `elide`, the result can be left out of requests once it's old (see context.ts); the mode note
|
|
228
|
+
* stays either way.
|
|
229
|
+
*/
|
|
230
|
+
appendToolResult(callId, output, elide) {
|
|
141
231
|
const content = truncateMiddle(output, MAX_TOOL_OUTPUT_CHARS);
|
|
142
232
|
const note = this.modeNote();
|
|
233
|
+
const withNote = (text) => (note ? `${text}\n\n${note}` : text);
|
|
143
234
|
this.append({
|
|
144
235
|
role: "tool",
|
|
145
236
|
tool_call_id: callId,
|
|
146
|
-
content:
|
|
237
|
+
content: withNote(content),
|
|
238
|
+
...(elide !== undefined ? { elide: withNote(elide) } : {}),
|
|
147
239
|
});
|
|
148
240
|
}
|
|
241
|
+
/** Adds the images a batch of tool calls returned, for a model that takes images. */
|
|
242
|
+
appendToolImages(batch) {
|
|
243
|
+
if (!this.model.images)
|
|
244
|
+
return;
|
|
245
|
+
const message = toolImagesMessage(batch);
|
|
246
|
+
if (message)
|
|
247
|
+
this.append(message);
|
|
248
|
+
}
|
|
149
249
|
/** Tries again after an error, without a new message (e.g. after adding credits). */
|
|
150
250
|
async *retry(signal) {
|
|
151
|
-
yield* this.
|
|
251
|
+
yield* this.turn(signal);
|
|
152
252
|
}
|
|
153
253
|
/** Whether `retry` has something to do: the conversation ends with an unanswered message. */
|
|
154
254
|
get canRetry() {
|
|
@@ -247,16 +347,16 @@ export class Agent {
|
|
|
247
347
|
this.options.onChange?.({ type: "usage", usage: acc.usage, costMicros: cost });
|
|
248
348
|
return cost;
|
|
249
349
|
}
|
|
250
|
-
/** `/compact`: summarize now, as its own turn. */
|
|
251
|
-
async *compactNow(signal) {
|
|
252
|
-
const ok = yield* this.compact(signal);
|
|
350
|
+
/** `/compact`: summarize now, as its own turn, paying attention to `focus` when given. */
|
|
351
|
+
async *compactNow(signal, focus) {
|
|
352
|
+
const ok = yield* this.compact(signal, focus);
|
|
253
353
|
yield { type: "done", reason: signal.aborted ? "aborted" : ok ? "complete" : "error" };
|
|
254
354
|
}
|
|
255
355
|
/**
|
|
256
356
|
* Replaces everything before the latest user message with a summary written by the model.
|
|
257
357
|
* Returns whether it happened; failures leave the conversation as it was.
|
|
258
358
|
*/
|
|
259
|
-
async *compact(signal) {
|
|
359
|
+
async *compact(signal, focus) {
|
|
260
360
|
const split = splitForCompaction(this.messages.slice(1));
|
|
261
361
|
if (!split) {
|
|
262
362
|
yield { type: "notice", text: "There's nothing earlier to summarize yet." };
|
|
@@ -271,7 +371,7 @@ export class Agent {
|
|
|
271
371
|
{ role: "system", content: SUMMARY_SYSTEM },
|
|
272
372
|
{
|
|
273
373
|
role: "user",
|
|
274
|
-
content: `${transcriptForSummary(split.head, maxChars)}\n\n---\n\n${
|
|
374
|
+
content: `${transcriptForSummary(split.head, maxChars)}\n\n---\n\n${summaryRequest(focus)}`,
|
|
275
375
|
},
|
|
276
376
|
],
|
|
277
377
|
stream: true,
|
|
@@ -327,9 +427,12 @@ export class Agent {
|
|
|
327
427
|
this.append({ role: "assistant", content: partial.content });
|
|
328
428
|
}
|
|
329
429
|
async *callModel(signal) {
|
|
430
|
+
// Images from earlier in the conversation stay out when the model doesn't take them (the
|
|
431
|
+
// user switched models).
|
|
432
|
+
const sent = elideForWire(this.messages);
|
|
330
433
|
const body = {
|
|
331
434
|
model: this.model.id,
|
|
332
|
-
messages: wireMessages(this.
|
|
435
|
+
messages: wireMessages(this.model.images ? sent : withoutImages(sent)),
|
|
333
436
|
tools: toolSchemas(this.options.tools),
|
|
334
437
|
stream: true,
|
|
335
438
|
stream_options: { include_usage: true },
|
|
@@ -411,6 +514,13 @@ export class Agent {
|
|
|
411
514
|
let stop = null;
|
|
412
515
|
/** Calls after a presented plan wait for the user's answer to it, so they're not run. */
|
|
413
516
|
let afterPlan = false;
|
|
517
|
+
/** Images the calls returned, sent after all their results. */
|
|
518
|
+
const images = [];
|
|
519
|
+
const finished = (call, result) => {
|
|
520
|
+
this.appendToolResult(call.id, result.output, result.elide);
|
|
521
|
+
if (result.images?.length)
|
|
522
|
+
images.push({ call, images: result.images });
|
|
523
|
+
};
|
|
414
524
|
for (let i = 0; i < calls.length; i++) {
|
|
415
525
|
const call = calls[i];
|
|
416
526
|
if (afterPlan && !stop && !signal.aborted) {
|
|
@@ -426,7 +536,7 @@ export class Agent {
|
|
|
426
536
|
}
|
|
427
537
|
i += batch.length - 1;
|
|
428
538
|
const outcomes = yield* this.runConcurrently(batch, signal);
|
|
429
|
-
outcomes.forEach(({ result }, j) =>
|
|
539
|
+
outcomes.forEach(({ result }, j) => finished(batch[j], result));
|
|
430
540
|
for (const [j, { result, title }] of outcomes.entries()) {
|
|
431
541
|
yield { type: "tool_done", id: batch[j].id, name: "task", title, result };
|
|
432
542
|
}
|
|
@@ -449,7 +559,7 @@ export class Agent {
|
|
|
449
559
|
mode: result.plan.outcome === "approved-auto" ? "auto-edit" : "ask",
|
|
450
560
|
};
|
|
451
561
|
}
|
|
452
|
-
|
|
562
|
+
finished(call, result);
|
|
453
563
|
yield { type: "tool_done", id: call.id, name: call.function.name, title, result };
|
|
454
564
|
if (call.function.name === PLAN_TOOL && result.plan)
|
|
455
565
|
afterPlan = true;
|
|
@@ -458,6 +568,7 @@ export class Agent {
|
|
|
458
568
|
else if (declined)
|
|
459
569
|
stop = "declined";
|
|
460
570
|
}
|
|
571
|
+
this.appendToolImages(images);
|
|
461
572
|
if (stop === "aborted")
|
|
462
573
|
this.interrupted = true;
|
|
463
574
|
return stop;
|
|
@@ -491,7 +602,7 @@ export class Agent {
|
|
|
491
602
|
apiBaseUrl: parent.apiBaseUrl,
|
|
492
603
|
apiKey: parent.apiKey,
|
|
493
604
|
model: parent.model,
|
|
494
|
-
tools: parent.tools.filter((t) => t.name !== "task" && t.name !== "todo" && t.name !== PLAN_TOOL),
|
|
605
|
+
tools: parent.tools.filter((t) => t.helpers !== false && t.name !== "task" && t.name !== "todo" && t.name !== PLAN_TOOL),
|
|
495
606
|
systemPrompt: `${this.messages[0].content}\n\n${HELPER_NOTE}`,
|
|
496
607
|
toolContext: { ...parent.toolContext, todos: [] },
|
|
497
608
|
// Helpers read freely; their edits and commands ask unless the user chose "Don't ask",
|
|
@@ -503,14 +614,20 @@ export class Agent {
|
|
|
503
614
|
},
|
|
504
615
|
allows: parent.permissions.allows,
|
|
505
616
|
context: parent.permissions.context,
|
|
617
|
+
get web() {
|
|
618
|
+
return parent.permissions.web;
|
|
619
|
+
},
|
|
506
620
|
},
|
|
507
621
|
approve: (request, sig, origin) => parent.approve({ ...request, title: `Helper "${description}": ${request.title}` }, sig, {
|
|
508
622
|
callId: origin?.callId ?? "",
|
|
509
623
|
helper: { description, callId: taskCallId },
|
|
510
624
|
}),
|
|
511
625
|
fetch: parent.fetch,
|
|
626
|
+
webFetch: parent.webFetch,
|
|
627
|
+
webTransport: parent.webTransport,
|
|
512
628
|
sleep: parent.sleep,
|
|
513
629
|
onProcess: parent.onProcess,
|
|
630
|
+
onBrowserSiteAllowed: parent.onBrowserSiteAllowed,
|
|
514
631
|
client: parent.client,
|
|
515
632
|
isHelper: true,
|
|
516
633
|
onChange: (change) => {
|
|
@@ -570,7 +687,7 @@ export class Agent {
|
|
|
570
687
|
});
|
|
571
688
|
const tool = this.options.tools.find((t) => t.name === name);
|
|
572
689
|
if (!tool)
|
|
573
|
-
return fail(`There is no tool called "${name}".`);
|
|
690
|
+
return fail(TURNED_OFF[name] ?? `There is no tool called "${name}".`);
|
|
574
691
|
let args;
|
|
575
692
|
try {
|
|
576
693
|
const parsed = call.function.arguments.trim()
|
|
@@ -591,6 +708,7 @@ export class Agent {
|
|
|
591
708
|
output: this.options.onOutput && ((chunk) => this.options.onOutput?.(call.id, chunk)),
|
|
592
709
|
process: this.options.onProcess,
|
|
593
710
|
helpers: this.options.isHelper ? undefined : this.helpers,
|
|
711
|
+
web: this.web,
|
|
594
712
|
};
|
|
595
713
|
let prepared;
|
|
596
714
|
try {
|
|
@@ -611,9 +729,11 @@ export class Agent {
|
|
|
611
729
|
paths: prepared.paths,
|
|
612
730
|
command: prepared.command,
|
|
613
731
|
readOnlyPaths: prepared.readOnlyPaths,
|
|
732
|
+
host: prepared.host,
|
|
733
|
+
act: prepared.act,
|
|
614
734
|
};
|
|
615
|
-
const { mode, allows, context } = this.options.permissions;
|
|
616
|
-
const decision = decide(request, mode, context, allows);
|
|
735
|
+
const { mode, allows, context, web } = this.options.permissions;
|
|
736
|
+
const decision = decide(request, mode, context, allows, web);
|
|
617
737
|
if (decision.kind === "deny") {
|
|
618
738
|
return { ...fail(decision.reason, prepared.title) };
|
|
619
739
|
}
|
|
@@ -627,6 +747,12 @@ export class Agent {
|
|
|
627
747
|
preview: prepared.preview,
|
|
628
748
|
reason: decision.reason,
|
|
629
749
|
always: decision.canAlways ? alwaysLabel(request) : null,
|
|
750
|
+
...(prepared.kind === "browser"
|
|
751
|
+
? {
|
|
752
|
+
...(prepared.host !== undefined ? { host: prepared.host } : {}),
|
|
753
|
+
...(prepared.act !== undefined ? { act: prepared.act } : {}),
|
|
754
|
+
}
|
|
755
|
+
: {}),
|
|
630
756
|
}, signal, { callId: call.id });
|
|
631
757
|
}
|
|
632
758
|
catch {
|
|
@@ -649,7 +775,12 @@ export class Agent {
|
|
|
649
775
|
declined: !feedback,
|
|
650
776
|
};
|
|
651
777
|
}
|
|
652
|
-
if (
|
|
778
|
+
if (request.kind === "browser") {
|
|
779
|
+
const site = rememberBrowser(request, answer.kind, allows);
|
|
780
|
+
if (site !== null)
|
|
781
|
+
this.options.onBrowserSiteAllowed?.(site);
|
|
782
|
+
}
|
|
783
|
+
else if (answer.kind === "always")
|
|
653
784
|
rememberAllow(request, allows);
|
|
654
785
|
}
|
|
655
786
|
try {
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
* Paths arrive already resolved (absolute, symlinks followed) by the tool that asks.
|
|
4
4
|
*/
|
|
5
5
|
import { basename, isAbsolute, join, relative, sep } from "node:path";
|
|
6
|
+
import { isLoopbackHostname } from "../browser/guards.js";
|
|
6
7
|
/** In the order Shift+Tab goes through them. */
|
|
7
8
|
export const MODES = ["ask", "auto-edit", "plan", "full"];
|
|
8
9
|
export const MODE_LABELS = {
|
|
@@ -15,12 +16,22 @@ export const MODE_LABELS = {
|
|
|
15
16
|
export const PLAN_EDIT_REFUSED = "Not changed: plan mode is on.\nNothing can change until the user approves a plan. Put this change in your plan, and present the plan with present_plan when it's ready.";
|
|
16
17
|
/** Why Plan mode asks before a command or MCP tool. */
|
|
17
18
|
export const PLAN_ASK_REASON = "Plan mode is on, and this could change something.";
|
|
19
|
+
export const DEFAULT_WEB_POLICY = { search: "allow", fetch: "ask" };
|
|
20
|
+
export const WEB_OFF = { search: "off", fetch: "off" };
|
|
18
21
|
export const emptyAllows = () => ({
|
|
19
22
|
edits: false,
|
|
20
23
|
readsOutside: false,
|
|
21
24
|
commands: new Set(),
|
|
22
25
|
tools: new Set(),
|
|
26
|
+
hosts: new Set(),
|
|
27
|
+
browserTask: new Set(),
|
|
28
|
+
browserOutward: new Set(),
|
|
23
29
|
});
|
|
30
|
+
/** Ends a task's browser grants (when a turn ends): the user's always-allowed sites stay. */
|
|
31
|
+
export function endBrowserTask(allows) {
|
|
32
|
+
allows.browserTask.clear();
|
|
33
|
+
allows.browserOutward.clear();
|
|
34
|
+
}
|
|
24
35
|
/** Inside `dir` (or `dir` itself). */
|
|
25
36
|
export function isInside(path, dir) {
|
|
26
37
|
const rel = relative(dir, path);
|
|
@@ -52,7 +63,12 @@ export function classifyPath(path, ctx) {
|
|
|
52
63
|
}
|
|
53
64
|
return isInside(path, ctx.cwd) ? "project" : "outside";
|
|
54
65
|
}
|
|
55
|
-
export function decide(request, mode, ctx, allows) {
|
|
66
|
+
export function decide(request, mode, ctx, allows, web = DEFAULT_WEB_POLICY) {
|
|
67
|
+
// The web touches no files, and works the same in every mode (Plan mode included: it only looks).
|
|
68
|
+
if (request.kind === "web")
|
|
69
|
+
return decideWeb(request, mode, allows, web);
|
|
70
|
+
if (request.kind === "browser")
|
|
71
|
+
return decideBrowser(request, mode, allows, ctx);
|
|
56
72
|
const classes = new Set(request.paths.map((p) => classifyPath(p, ctx)));
|
|
57
73
|
if (classes.has("forbidden"))
|
|
58
74
|
return { kind: "deny", reason: FORBIDDEN };
|
|
@@ -93,6 +109,26 @@ export function decide(request, mode, ctx, allows) {
|
|
|
93
109
|
}
|
|
94
110
|
}
|
|
95
111
|
}
|
|
112
|
+
/**
|
|
113
|
+
* Searching: per the user's choice ("Ask first" can become "don't ask again"). Reading a page: asks
|
|
114
|
+
* once per site, unless the user allowed every site, chose "Don't ask", or linked the site.
|
|
115
|
+
*/
|
|
116
|
+
function decideWeb(request, mode, allows, web) {
|
|
117
|
+
if (request.host === undefined) {
|
|
118
|
+
if (web.search === "off")
|
|
119
|
+
return { kind: "deny", reason: "Web search is turned off." };
|
|
120
|
+
if (web.search === "allow" || mode === "full" || allows.tools.has(request.tool)) {
|
|
121
|
+
return { kind: "allow" };
|
|
122
|
+
}
|
|
123
|
+
return { kind: "ask", reason: null, canAlways: true };
|
|
124
|
+
}
|
|
125
|
+
if (web.fetch === "off")
|
|
126
|
+
return { kind: "deny", reason: "Reading web pages is turned off." };
|
|
127
|
+
if (web.fetch === "allow" || mode === "full" || allows.hosts.has(request.host)) {
|
|
128
|
+
return { kind: "allow" };
|
|
129
|
+
}
|
|
130
|
+
return { kind: "ask", reason: null, canAlways: true };
|
|
131
|
+
}
|
|
96
132
|
/**
|
|
97
133
|
* Plan mode: reads as in "Ask before edits"; a command that only looks runs when every file it
|
|
98
134
|
* names is in the project; anything else that runs asks each time, and earlier "don't ask again"
|
|
@@ -115,6 +151,80 @@ function decideInPlan(request, outside, ctx, allows) {
|
|
|
115
151
|
}
|
|
116
152
|
return { kind: "ask", reason: PLAN_ASK_REASON, canAlways: false };
|
|
117
153
|
}
|
|
154
|
+
case "web":
|
|
155
|
+
case "browser":
|
|
156
|
+
return { kind: "allow" }; // decided before Plan mode's rules (see `decide`)
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
/** Why the browser asks, beyond the site. */
|
|
160
|
+
export const BROWSER_REASONS = {
|
|
161
|
+
outward: "This sends or changes something on the site.",
|
|
162
|
+
money: "This could spend or move money.",
|
|
163
|
+
script: "This runs code in the page.",
|
|
164
|
+
handoff: "This hands the browser to you.",
|
|
165
|
+
};
|
|
166
|
+
/**
|
|
167
|
+
* The browser, per site and action (see `BrowserAct`):
|
|
168
|
+
* - This computer (`localhost`, `*.localhost`, `127.0.0.1`, `[::1]`): everything runs, in every
|
|
169
|
+
* mode; only a handoff asks.
|
|
170
|
+
* - A site the user always allows, or allowed for this task: looking and acting run; sending asks
|
|
171
|
+
* (its "always" covers this site for this task); money and scripts ask every time.
|
|
172
|
+
* - Any other site: looking and acting ask ("yes" covers this task, "always" every task); the rest
|
|
173
|
+
* as above.
|
|
174
|
+
* - Plan mode: off this computer, acting and sending ask every time.
|
|
175
|
+
* - "Don't ask": everything runs but money (asks every time) and handoffs.
|
|
176
|
+
* A handoff always asks, without "always". An action that doesn't say what it does counts as a
|
|
177
|
+
* script.
|
|
178
|
+
*/
|
|
179
|
+
export function decideBrowser(request, mode, allows, ctx) {
|
|
180
|
+
const act = request.act ?? "script";
|
|
181
|
+
const host = request.host;
|
|
182
|
+
const every = (reason) => ({ kind: "ask", reason, canAlways: false });
|
|
183
|
+
if (act === "handoff")
|
|
184
|
+
return every(BROWSER_REASONS.handoff);
|
|
185
|
+
if (host !== undefined && isLoopbackHostname(host))
|
|
186
|
+
return { kind: "allow" };
|
|
187
|
+
if (mode === "full")
|
|
188
|
+
return act === "money" ? every(BROWSER_REASONS.money) : { kind: "allow" };
|
|
189
|
+
if (act === "money" || act === "script")
|
|
190
|
+
return every(BROWSER_REASONS[act]);
|
|
191
|
+
if (mode === "plan" && (act === "act" || act === "outward"))
|
|
192
|
+
return every(PLAN_ASK_REASON);
|
|
193
|
+
// With no site (a blank tab) there's nothing to remember an answer for.
|
|
194
|
+
const canAlways = host !== undefined;
|
|
195
|
+
const allowed = host !== undefined &&
|
|
196
|
+
(allows.browserTask.has(host) || Boolean(ctx.browserSites?.includes(host)));
|
|
197
|
+
if (act === "outward") {
|
|
198
|
+
if (allowed && allows.browserOutward.has(host))
|
|
199
|
+
return { kind: "allow" };
|
|
200
|
+
return { kind: "ask", reason: BROWSER_REASONS.outward, canAlways };
|
|
201
|
+
}
|
|
202
|
+
return allowed ? { kind: "allow" } : { kind: "ask", reason: null, canAlways };
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Records the user's "yes" or "always" to a browser prompt. Returns a site the user now always
|
|
206
|
+
* allows, for the host to save (it comes back in `PermissionContext.browserSites`), else null.
|
|
207
|
+
* - Looking or acting: the site is allowed for this task; "always" also returns it.
|
|
208
|
+
* - Sending: the site is allowed for this task; "always" lets it send there for this task.
|
|
209
|
+
* - Money, scripts and handoffs cover that one action.
|
|
210
|
+
* Never touches `allows.hosts` (web_fetch's).
|
|
211
|
+
*/
|
|
212
|
+
export function rememberBrowser(request, answer, allows) {
|
|
213
|
+
const host = request.host;
|
|
214
|
+
if (request.kind !== "browser" || host === undefined)
|
|
215
|
+
return null;
|
|
216
|
+
switch (request.act) {
|
|
217
|
+
case "look":
|
|
218
|
+
case "act":
|
|
219
|
+
allows.browserTask.add(host);
|
|
220
|
+
return answer === "always" ? host : null;
|
|
221
|
+
case "outward":
|
|
222
|
+
allows.browserTask.add(host);
|
|
223
|
+
if (answer === "always")
|
|
224
|
+
allows.browserOutward.add(host);
|
|
225
|
+
return null;
|
|
226
|
+
default:
|
|
227
|
+
return null;
|
|
118
228
|
}
|
|
119
229
|
}
|
|
120
230
|
/** Records "yes, and don't ask again this session" for a request that was asked about. */
|
|
@@ -132,6 +242,15 @@ export function rememberAllow(request, allows) {
|
|
|
132
242
|
else
|
|
133
243
|
allows.tools.add(request.tool);
|
|
134
244
|
break;
|
|
245
|
+
case "web":
|
|
246
|
+
if (request.host !== undefined)
|
|
247
|
+
allows.hosts.add(request.host);
|
|
248
|
+
else
|
|
249
|
+
allows.tools.add(request.tool);
|
|
250
|
+
break;
|
|
251
|
+
case "browser":
|
|
252
|
+
rememberBrowser(request, "always", allows);
|
|
253
|
+
break;
|
|
135
254
|
case "meta":
|
|
136
255
|
break;
|
|
137
256
|
}
|
|
@@ -147,7 +266,38 @@ export function alwaysLabel(request) {
|
|
|
147
266
|
return request.command !== undefined
|
|
148
267
|
? "yes, and don't ask again for this exact command"
|
|
149
268
|
: `yes, and don't ask again for ${request.tool}`;
|
|
269
|
+
case "web":
|
|
270
|
+
return request.host !== undefined
|
|
271
|
+
? `yes, and don't ask again for ${request.host}`
|
|
272
|
+
: "yes, and allow web searches this session";
|
|
273
|
+
case "browser":
|
|
274
|
+
if (request.host === undefined)
|
|
275
|
+
return "yes";
|
|
276
|
+
return request.act === "outward"
|
|
277
|
+
? `yes, and allow this on ${request.host} for this task`
|
|
278
|
+
: `yes, and always allow ${request.host} in the browser`;
|
|
150
279
|
case "meta":
|
|
151
280
|
return "yes";
|
|
152
281
|
}
|
|
153
282
|
}
|
|
283
|
+
/** A page's site for the per-site rules: its host, lowercased, without a leading "www.". */
|
|
284
|
+
export function siteOf(url) {
|
|
285
|
+
const host = (typeof url === "string" ? new URL(url) : url).hostname.toLowerCase();
|
|
286
|
+
return host.startsWith("www.") ? host.slice(4) : host;
|
|
287
|
+
}
|
|
288
|
+
const LINK = /\bhttps?:\/\/[^\s<>"'`]+/gi;
|
|
289
|
+
/** The sites of the web links in a message the user wrote (their pages open without asking). */
|
|
290
|
+
export function hostsIn(text) {
|
|
291
|
+
const sites = new Set();
|
|
292
|
+
for (const [link] of text.matchAll(LINK)) {
|
|
293
|
+
try {
|
|
294
|
+
const url = new URL(link.replace(/[.,;:!?)\]}]+$/, ""));
|
|
295
|
+
if (url.hostname)
|
|
296
|
+
sites.add(siteOf(url));
|
|
297
|
+
}
|
|
298
|
+
catch {
|
|
299
|
+
// not a link after all
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
return [...sites];
|
|
303
|
+
}
|