reasonally 0.5.0 → 0.7.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.
@@ -2,29 +2,49 @@
2
2
  * Compaction: when the conversation nears the model's context window, earlier turns are replaced
3
3
  * by a model-written summary. The pure parts (what to keep, what to send) live here.
4
4
  */
5
+ import { commandLabel } from "./command-template.js";
5
6
  import { truncateMiddle } from "./tools/types.js";
6
7
  /** Compact once the context is this full. */
7
8
  export const COMPACT_AT = 0.8;
9
+ /** What an image counts for in a token estimate (a large screenshot, roughly). */
10
+ export const IMAGE_TOKENS = 1_600;
8
11
  /** A rough token count (4 characters per token), for before the server has reported usage. */
9
12
  export function estimateTokens(messages) {
10
13
  let chars = 0;
14
+ let images = 0;
11
15
  for (const m of messages) {
12
- chars += typeof m.content === "string" ? m.content.length : 0;
16
+ if (typeof m.content === "string")
17
+ chars += m.content.length;
18
+ else if (Array.isArray(m.content)) {
19
+ for (const part of m.content) {
20
+ if (part.type === "text")
21
+ chars += part.text.length;
22
+ else
23
+ images++;
24
+ }
25
+ }
13
26
  if (m.role === "assistant" && m.tool_calls) {
14
27
  for (const c of m.tool_calls)
15
28
  chars += c.function.name.length + c.function.arguments.length;
16
29
  }
17
30
  }
18
- return Math.ceil(chars / 4);
31
+ return Math.ceil(chars / 4) + images * IMAGE_TOKENS;
32
+ }
33
+ /** A user message's text, with a placeholder for each image. */
34
+ export function contentText(content) {
35
+ if (typeof content === "string")
36
+ return content;
37
+ return content.map((p) => (p.type === "text" ? p.text : "[image]")).join("\n");
19
38
  }
20
39
  export const shouldCompact = (contextTokens, contextLength) => contextTokens !== null && contextTokens >= contextLength * COMPACT_AT;
21
40
  /**
22
41
  * Splits the conversation (without the system message) into what gets summarized and what's kept:
23
42
  * everything from the latest user message on. Cutting at a user message never separates a tool
24
- * call from its result. Null when there's nothing earlier to summarize.
43
+ * call from its result; one the agent added (a tool call's images) isn't a place to cut, since it
44
+ * belongs with the results before it. Null when there's nothing earlier to summarize.
25
45
  */
26
46
  export function splitForCompaction(messages) {
27
- const lastUser = messages.map((m) => m.role).lastIndexOf("user");
47
+ const lastUser = messages.findLastIndex((m) => m.role === "user" && !m.synthetic);
28
48
  if (lastUser <= 0)
29
49
  return null;
30
50
  return { head: messages.slice(0, lastUser), tail: messages.slice(lastUser) };
@@ -34,8 +54,15 @@ const clip = (text, max) => truncateMiddle(text, max);
34
54
  export function transcriptForSummary(head, maxChars) {
35
55
  const parts = [];
36
56
  for (const m of head) {
37
- if (m.role === "user")
38
- parts.push(`USER:\n${clip(m.content, 8000)}`);
57
+ if (m.role === "user") {
58
+ // A tool call's images: the summarizer only reads text.
59
+ if (m.synthetic)
60
+ parts.push(`TOOL IMAGES:\n${clip(contentText(m.content), 2000)}`);
61
+ else {
62
+ const label = m.command ? `USER (${commandLabel(m.command)})` : "USER";
63
+ parts.push(`${label}:\n${clip(contentText(m.content), 8000)}`);
64
+ }
65
+ }
39
66
  else if (m.role === "assistant") {
40
67
  if (m.content)
41
68
  parts.push(`ASSISTANT:\n${clip(m.content, 8000)}`);
@@ -57,6 +84,13 @@ export const SUMMARY_REQUEST = `Summarize the conversation above. Include:
57
84
  - The current state: what works, what's broken, errors still open (quote key messages).
58
85
  - What remains to do next.
59
86
  Keep specifics (paths, names, versions, error text). Leave out pleasantries and repeated detail.`;
87
+ /** The summary request, asked to keep what the user named (`/compact keep the API decisions`). */
88
+ export function summaryRequest(focus) {
89
+ const keep = focus?.trim();
90
+ return keep
91
+ ? `${SUMMARY_REQUEST}\nPay particular attention to: ${clip(keep, 2000)}`
92
+ : SUMMARY_REQUEST;
93
+ }
60
94
  export const SUMMARY_PREFIX = "[Summary of the conversation so far]";
61
95
  /** The conversation after compaction: the summary leads the first kept user message. */
62
96
  export function compactedMessages(summary, tail, todos) {
@@ -65,10 +99,26 @@ export function compactedMessages(summary, tail, todos) {
65
99
  : "";
66
100
  const [first, ...rest] = tail;
67
101
  const lead = `${SUMMARY_PREFIX}\n${summary.trim()}${todoText}\n\n[Latest message]\n`;
68
- if (first?.role !== "user") {
102
+ if (first?.role !== "user" || first.synthetic) {
69
103
  return [{ role: "user", content: `${lead}(none)` }, ...tail];
70
104
  }
71
- return [{ role: "user", content: lead + first.content }, ...rest];
105
+ return [
106
+ {
107
+ role: "user",
108
+ content: withLead(lead, first.content),
109
+ ...(first.command ? { command: first.command } : {}),
110
+ },
111
+ ...rest,
112
+ ];
113
+ }
114
+ /** `lead` in front of a message's text (its first text part, when it has parts). */
115
+ function withLead(lead, content) {
116
+ if (typeof content === "string")
117
+ return lead + content;
118
+ const i = content.findIndex((p) => p.type === "text");
119
+ if (i === -1)
120
+ return [{ type: "text", text: lead.trimEnd() }, ...content];
121
+ return content.map((p, j) => (j === i && p.type === "text" ? { ...p, text: lead + p.text } : p));
72
122
  }
73
123
  /** Whether an error says the request was too long for the model's context. */
74
124
  export function isContextOverflow(error) {
@@ -0,0 +1,82 @@
1
+ export const WIRE_ELISION = { keepImages: 2, budgetChars: 60_000 };
2
+ /** What an image counts for against the budget: about 1,600 tokens, at 4 characters a token. */
3
+ export const IMAGE_CHARS = 1_600 * 4;
4
+ /** What the model sees in place of an old screenshot. */
5
+ export const IMAGE_ELIDED = "[image no longer shown]";
6
+ /** What a model that doesn't take images sees in place of one. */
7
+ export const IMAGE_NOT_SENT = "[image not shown: this model doesn't take images]";
8
+ /** The conversation with every image replaced by a note, for a model that doesn't take images. */
9
+ export function withoutImages(messages) {
10
+ if (!messages.some((m) => m.role === "user" && Array.isArray(m.content)))
11
+ return messages;
12
+ return messages.map((m) => {
13
+ if (m.role !== "user" || typeof m.content === "string")
14
+ return m;
15
+ if (!m.content.some((p) => p.type === "image_url"))
16
+ return m;
17
+ const content = m.content.map((p) => p.type === "image_url" ? { type: "text", text: IMAGE_NOT_SENT } : p);
18
+ return { ...m, content };
19
+ });
20
+ }
21
+ /** The conversation as it's sent: old replaceable results and images replaced (see above). */
22
+ export function elideForWire(messages, { keepImages, budgetChars } = WIRE_ELISION) {
23
+ const elided = new Set();
24
+ /** Sent whole so far: kept by the last batch, or added since. */
25
+ let pending = [];
26
+ /** Added since the last batch. */
27
+ let added = 0;
28
+ for (const [index, m] of messages.entries()) {
29
+ const units = [];
30
+ if (m.role === "tool" && m.elide !== undefined) {
31
+ units.push({ kind: "result", index, chars: m.content.length });
32
+ }
33
+ else if (m.role === "user" && m.synthetic === "tool-images" && Array.isArray(m.content)) {
34
+ m.content.forEach((p, part) => {
35
+ if (p.type === "image_url")
36
+ units.push({ kind: "image", index, part, chars: IMAGE_CHARS });
37
+ });
38
+ }
39
+ for (const unit of units) {
40
+ pending.push(unit);
41
+ added += unit.chars;
42
+ if (added <= budgetChars)
43
+ continue;
44
+ // Over budget: keep the newest result and the newest images, replace the rest of the batch.
45
+ const kept = new Set();
46
+ const results = pending.filter((u) => u.kind === "result");
47
+ if (results.length)
48
+ kept.add(results.at(-1));
49
+ const images = pending.filter((u) => u.kind === "image");
50
+ for (const u of images.slice(Math.max(0, images.length - keepImages)))
51
+ kept.add(u);
52
+ for (const u of pending)
53
+ if (!kept.has(u))
54
+ elided.add(u);
55
+ pending = pending.filter((u) => kept.has(u));
56
+ added = 0;
57
+ }
58
+ }
59
+ if (!elided.size)
60
+ return messages;
61
+ const results = new Set();
62
+ const images = new Map();
63
+ for (const u of elided) {
64
+ if (u.kind === "result")
65
+ results.add(u.index);
66
+ else
67
+ images.set(u.index, (images.get(u.index) ?? new Set()).add(u.part));
68
+ }
69
+ return messages.map((m, index) => {
70
+ if (results.has(index)) {
71
+ const tool = m;
72
+ return { ...tool, content: tool.elide };
73
+ }
74
+ const parts = images.get(index);
75
+ if (parts) {
76
+ const user = m;
77
+ const content = user.content.map((p, i) => parts.has(i) ? { type: "text", text: IMAGE_ELIDED } : p);
78
+ return { ...user, content };
79
+ }
80
+ return m;
81
+ });
82
+ }
@@ -1,8 +1,9 @@
1
1
  import { MessageAccumulator } from "./accumulate.js";
2
2
  import { retryDelayMs, searchWeb, StreamError, streamChat, webUserAgent, } from "./client.js";
3
- import { compactedMessages, estimateTokens, isContextOverflow, shouldCompact, splitForCompaction, SUMMARY_REQUEST, SUMMARY_SYSTEM, transcriptForSummary, } from "./compact.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, hostsIn, 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";
@@ -30,10 +31,11 @@ const PLAN_DRAFT_EVERY_MS = 50;
30
31
  export function lastToldPlan(messages) {
31
32
  for (let i = messages.length - 1; i >= 0; i--) {
32
33
  const m = messages[i];
33
- if ((m.role !== "user" && m.role !== "tool") || typeof m.content !== "string")
34
+ if ((m.role !== "user" && m.role !== "tool") || (m.role === "user" && m.synthetic))
34
35
  continue;
35
- const on = Math.max(m.content.lastIndexOf(PLAN_ON_NOTE), m.content.lastIndexOf(HELPER_PLAN_ON_NOTE));
36
- const off = Math.max(m.content.lastIndexOf(PLAN_OFF_NOTE), m.content.startsWith(PLAN_APPROVED) ? 0 : -1);
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);
37
39
  if (on !== -1 || off !== -1)
38
40
  return on > off;
39
41
  }
@@ -55,9 +57,15 @@ export function sleep(ms, signal) {
55
57
  signal.addEventListener("abort", onAbort, { once: true });
56
58
  });
57
59
  }
58
- /** 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. */
59
61
  export function wireMessages(messages) {
60
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
+ }
61
69
  if (m.role !== "assistant")
62
70
  return m;
63
71
  const out = { role: "assistant", content: m.content };
@@ -68,6 +76,26 @@ export function wireMessages(messages) {
68
76
  return out;
69
77
  });
70
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
+ }
71
99
  const isAbort = (error, signal) => signal.aborted || error?.name === "AbortError";
72
100
  export class Agent {
73
101
  options;
@@ -128,26 +156,57 @@ export class Agent {
128
156
  this.lastUsage = null;
129
157
  this.estimatedTokens = messages.length ? estimateTokens(this.messages) : null;
130
158
  }
131
- /** Adds the user's message and works on it until done, stopped or failed. */
132
- async *send(text, signal) {
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) {
133
165
  const content = this.interrupted ? `${INTERRUPTED_NOTE}\n\n${text}` : text;
134
166
  this.interrupted = false;
135
- // Pages on sites the user links to open without asking. (A helper's prompt is the model's.)
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.)
136
169
  if (!this.options.isHelper) {
137
- for (const host of hostsIn(text))
138
- this.options.permissions.allows.hosts.add(host);
170
+ const { allows } = this.options.permissions;
171
+ for (const host of hostsIn(text)) {
172
+ allows.hosts.add(host);
173
+ allows.browserTask.add(host);
174
+ }
139
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;
140
181
  const note = this.modeNote();
141
182
  const last = this.messages.at(-1);
142
- // After a failed request the user's message is still last: add to it.
143
- if (last?.role === "user") {
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) {
144
186
  const merged = `${last.content}\n\n${content}`;
145
- 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;
146
190
  this.replaceAll(this.messages.slice(1), "merge");
147
191
  }
148
- else
149
- this.append({ role: "user", content: note ? `${note}\n\n${content}` : content });
150
- yield* this.work(signal);
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
+ }
151
210
  }
152
211
  /**
153
212
  * A note for the model when Plan mode starts or stops applying, else null. The note goes in
@@ -163,19 +222,33 @@ export class Agent {
163
222
  return PLAN_OFF_NOTE;
164
223
  return this.options.isHelper ? HELPER_PLAN_ON_NOTE : PLAN_ON_NOTE;
165
224
  }
166
- /** Adds a tool result (with a mode note when the mode changed since the model last heard). */
167
- appendToolResult(callId, output) {
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) {
168
231
  const content = truncateMiddle(output, MAX_TOOL_OUTPUT_CHARS);
169
232
  const note = this.modeNote();
233
+ const withNote = (text) => (note ? `${text}\n\n${note}` : text);
170
234
  this.append({
171
235
  role: "tool",
172
236
  tool_call_id: callId,
173
- content: note ? `${content}\n\n${note}` : content,
237
+ content: withNote(content),
238
+ ...(elide !== undefined ? { elide: withNote(elide) } : {}),
174
239
  });
175
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
+ }
176
249
  /** Tries again after an error, without a new message (e.g. after adding credits). */
177
250
  async *retry(signal) {
178
- yield* this.work(signal);
251
+ yield* this.turn(signal);
179
252
  }
180
253
  /** Whether `retry` has something to do: the conversation ends with an unanswered message. */
181
254
  get canRetry() {
@@ -274,16 +347,16 @@ export class Agent {
274
347
  this.options.onChange?.({ type: "usage", usage: acc.usage, costMicros: cost });
275
348
  return cost;
276
349
  }
277
- /** `/compact`: summarize now, as its own turn. */
278
- async *compactNow(signal) {
279
- 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);
280
353
  yield { type: "done", reason: signal.aborted ? "aborted" : ok ? "complete" : "error" };
281
354
  }
282
355
  /**
283
356
  * Replaces everything before the latest user message with a summary written by the model.
284
357
  * Returns whether it happened; failures leave the conversation as it was.
285
358
  */
286
- async *compact(signal) {
359
+ async *compact(signal, focus) {
287
360
  const split = splitForCompaction(this.messages.slice(1));
288
361
  if (!split) {
289
362
  yield { type: "notice", text: "There's nothing earlier to summarize yet." };
@@ -298,7 +371,7 @@ export class Agent {
298
371
  { role: "system", content: SUMMARY_SYSTEM },
299
372
  {
300
373
  role: "user",
301
- content: `${transcriptForSummary(split.head, maxChars)}\n\n---\n\n${SUMMARY_REQUEST}`,
374
+ content: `${transcriptForSummary(split.head, maxChars)}\n\n---\n\n${summaryRequest(focus)}`,
302
375
  },
303
376
  ],
304
377
  stream: true,
@@ -354,9 +427,12 @@ export class Agent {
354
427
  this.append({ role: "assistant", content: partial.content });
355
428
  }
356
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);
357
433
  const body = {
358
434
  model: this.model.id,
359
- messages: wireMessages(this.messages),
435
+ messages: wireMessages(this.model.images ? sent : withoutImages(sent)),
360
436
  tools: toolSchemas(this.options.tools),
361
437
  stream: true,
362
438
  stream_options: { include_usage: true },
@@ -438,6 +514,13 @@ export class Agent {
438
514
  let stop = null;
439
515
  /** Calls after a presented plan wait for the user's answer to it, so they're not run. */
440
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
+ };
441
524
  for (let i = 0; i < calls.length; i++) {
442
525
  const call = calls[i];
443
526
  if (afterPlan && !stop && !signal.aborted) {
@@ -453,7 +536,7 @@ export class Agent {
453
536
  }
454
537
  i += batch.length - 1;
455
538
  const outcomes = yield* this.runConcurrently(batch, signal);
456
- outcomes.forEach(({ result }, j) => this.appendToolResult(batch[j].id, result.output));
539
+ outcomes.forEach(({ result }, j) => finished(batch[j], result));
457
540
  for (const [j, { result, title }] of outcomes.entries()) {
458
541
  yield { type: "tool_done", id: batch[j].id, name: "task", title, result };
459
542
  }
@@ -476,7 +559,7 @@ export class Agent {
476
559
  mode: result.plan.outcome === "approved-auto" ? "auto-edit" : "ask",
477
560
  };
478
561
  }
479
- this.appendToolResult(call.id, result.output);
562
+ finished(call, result);
480
563
  yield { type: "tool_done", id: call.id, name: call.function.name, title, result };
481
564
  if (call.function.name === PLAN_TOOL && result.plan)
482
565
  afterPlan = true;
@@ -485,6 +568,7 @@ export class Agent {
485
568
  else if (declined)
486
569
  stop = "declined";
487
570
  }
571
+ this.appendToolImages(images);
488
572
  if (stop === "aborted")
489
573
  this.interrupted = true;
490
574
  return stop;
@@ -518,7 +602,7 @@ export class Agent {
518
602
  apiBaseUrl: parent.apiBaseUrl,
519
603
  apiKey: parent.apiKey,
520
604
  model: parent.model,
521
- 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),
522
606
  systemPrompt: `${this.messages[0].content}\n\n${HELPER_NOTE}`,
523
607
  toolContext: { ...parent.toolContext, todos: [] },
524
608
  // Helpers read freely; their edits and commands ask unless the user chose "Don't ask",
@@ -543,6 +627,7 @@ export class Agent {
543
627
  webTransport: parent.webTransport,
544
628
  sleep: parent.sleep,
545
629
  onProcess: parent.onProcess,
630
+ onBrowserSiteAllowed: parent.onBrowserSiteAllowed,
546
631
  client: parent.client,
547
632
  isHelper: true,
548
633
  onChange: (change) => {
@@ -645,6 +730,7 @@ export class Agent {
645
730
  command: prepared.command,
646
731
  readOnlyPaths: prepared.readOnlyPaths,
647
732
  host: prepared.host,
733
+ act: prepared.act,
648
734
  };
649
735
  const { mode, allows, context, web } = this.options.permissions;
650
736
  const decision = decide(request, mode, context, allows, web);
@@ -661,6 +747,12 @@ export class Agent {
661
747
  preview: prepared.preview,
662
748
  reason: decision.reason,
663
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
+ : {}),
664
756
  }, signal, { callId: call.id });
665
757
  }
666
758
  catch {
@@ -683,7 +775,12 @@ export class Agent {
683
775
  declined: !feedback,
684
776
  };
685
777
  }
686
- if (answer.kind === "always")
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")
687
784
  rememberAllow(request, allows);
688
785
  }
689
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 = {
@@ -23,7 +24,14 @@ export const emptyAllows = () => ({
23
24
  commands: new Set(),
24
25
  tools: new Set(),
25
26
  hosts: new Set(),
27
+ browserTask: new Set(),
28
+ browserOutward: new Set(),
26
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
+ }
27
35
  /** Inside `dir` (or `dir` itself). */
28
36
  export function isInside(path, dir) {
29
37
  const rel = relative(dir, path);
@@ -59,6 +67,8 @@ export function decide(request, mode, ctx, allows, web = DEFAULT_WEB_POLICY) {
59
67
  // The web touches no files, and works the same in every mode (Plan mode included: it only looks).
60
68
  if (request.kind === "web")
61
69
  return decideWeb(request, mode, allows, web);
70
+ if (request.kind === "browser")
71
+ return decideBrowser(request, mode, allows, ctx);
62
72
  const classes = new Set(request.paths.map((p) => classifyPath(p, ctx)));
63
73
  if (classes.has("forbidden"))
64
74
  return { kind: "deny", reason: FORBIDDEN };
@@ -142,9 +152,81 @@ function decideInPlan(request, outside, ctx, allows) {
142
152
  return { kind: "ask", reason: PLAN_ASK_REASON, canAlways: false };
143
153
  }
144
154
  case "web":
155
+ case "browser":
145
156
  return { kind: "allow" }; // decided before Plan mode's rules (see `decide`)
146
157
  }
147
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;
228
+ }
229
+ }
148
230
  /** Records "yes, and don't ask again this session" for a request that was asked about. */
149
231
  export function rememberAllow(request, allows) {
150
232
  switch (request.kind) {
@@ -166,6 +248,9 @@ export function rememberAllow(request, allows) {
166
248
  else
167
249
  allows.tools.add(request.tool);
168
250
  break;
251
+ case "browser":
252
+ rememberBrowser(request, "always", allows);
253
+ break;
169
254
  case "meta":
170
255
  break;
171
256
  }
@@ -185,6 +270,12 @@ export function alwaysLabel(request) {
185
270
  return request.host !== undefined
186
271
  ? `yes, and don't ask again for ${request.host}`
187
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`;
188
279
  case "meta":
189
280
  return "yes";
190
281
  }