@useavalon/caelence-agent 0.3.0 → 0.4.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.
@@ -6,6 +6,8 @@ export interface ApprovalRequest {
6
6
  callId: string;
7
7
  toolName: string;
8
8
  input: Record<string, unknown>;
9
+ /** Why the tool asked for approval, in words the user can act on. Set by `confirm`. */
10
+ reason?: string;
9
11
  }
10
12
 
11
13
  export interface ApprovalGate {
@@ -72,6 +74,13 @@ export interface ExecApprovalGateDeps {
72
74
  * prompt and can never deny. Must not throw; a throw or "ask" falls through to the prompt.
73
75
  */
74
76
  assist?: (req: ApprovalRequest) => Promise<"allow" | "ask">;
77
+ /**
78
+ * When set, only requests this returns true for go through the normal approval path. Every
79
+ * other request runs without a prompt. Use it for a host that wants fewer prompts, such as
80
+ * asking only before deletions. The `deny` policy and the host denylist still apply to the
81
+ * requests it lets through.
82
+ */
83
+ promptOnly?: (req: ApprovalRequest) => boolean;
75
84
  }
76
85
 
77
86
  async function promptAsk(deps: ExecApprovalGateDeps, req: ApprovalRequest): Promise<boolean> {
@@ -80,6 +89,7 @@ async function promptAsk(deps: ExecApprovalGateDeps, req: ApprovalRequest): Prom
80
89
  callId: req.callId,
81
90
  toolName: req.toolName,
82
91
  input: req.input,
92
+ ...(req.reason ? { reason: req.reason } : {}),
83
93
  });
84
94
  if (!deps.ask) return false;
85
95
  return deps.ask(req);
@@ -100,6 +110,13 @@ export function createExecApprovalGate(deps: ExecApprovalGateDeps): ApprovalGate
100
110
  const always = deps.alwaysAllow ?? new Set<string>();
101
111
  return {
102
112
  async request(req) {
113
+ // A tool asked for a human on this call. Nothing else may answer for the user: not
114
+ // promptOnly, "always allow", the auto policy, or the decision-model assist.
115
+ if (req.reason) {
116
+ if (deps.policy === "deny") return false;
117
+ return promptAsk(deps, req);
118
+ }
119
+ if (deps.promptOnly && !deps.promptOnly(req)) return true;
103
120
  if (isFileWriteTool(req.toolName) && deps.resolveUploadEdit) {
104
121
  const path = typeof req.input.path === "string" ? req.input.path : "";
105
122
  const hit = deps.resolveUploadEdit(path);
@@ -15,7 +15,13 @@ export type AgentEvent =
15
15
  output?: string;
16
16
  error?: string;
17
17
  }
18
- | { kind: "approval_request"; callId: string; toolName: string; input: Record<string, unknown> }
18
+ | {
19
+ kind: "approval_request";
20
+ callId: string;
21
+ toolName: string;
22
+ input: Record<string, unknown>;
23
+ reason?: string;
24
+ }
19
25
  | { kind: "session_meta"; sessionId: string; title: string }
20
26
  | {
21
27
  kind: "usage";
@@ -0,0 +1,605 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { mkdtemp, rm } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { DEFAULT_CONFIG } from "../config.ts";
6
+ import { noopObservability } from "../observability/noop.ts";
7
+ import { createHarness } from "../runtime.ts";
8
+ import { createExecApprovalGate } from "./approval.ts";
9
+ import type { AgentEvent, MainModelProvider } from "./events.ts";
10
+ import { textResult, UNKNOWN_TOOL_ANNOTATIONS } from "./mcp.ts";
11
+ import { type RunTurnDeps, runTurn, type TurnInterceptor } from "./run-turn.ts";
12
+ import { createFileSessionStore, createMemorySessionStore } from "./session.ts";
13
+ import type { ConstructAgent } from "./strands.ts";
14
+
15
+ const provider: MainModelProvider = {
16
+ kind: "fake",
17
+ modelId: "fake",
18
+ async *stream() {
19
+ yield { type: "done" };
20
+ },
21
+ };
22
+
23
+ function tool(name: string) {
24
+ return {
25
+ name,
26
+ description: name,
27
+ inputSchema: { type: "object", properties: {} },
28
+ annotations: UNKNOWN_TOOL_ANNOTATIONS,
29
+ async handler() {
30
+ return textResult("ok");
31
+ },
32
+ };
33
+ }
34
+
35
+ function spy() {
36
+ const seen = { ran: 0, system: "", tools: [] as string[], message: "" };
37
+ const constructAgent: ConstructAgent = (input) => {
38
+ seen.system = input.systemPrompt;
39
+ seen.tools = input.tools.map((t) => t.name);
40
+ return {
41
+ async run(message, emit) {
42
+ seen.ran += 1;
43
+ seen.message = message;
44
+ emit({ kind: "text_delta", text: "agent answer" });
45
+ },
46
+ };
47
+ };
48
+ return { seen, constructAgent };
49
+ }
50
+
51
+ function deps(extra: Partial<RunTurnDeps> & { constructAgent: ConstructAgent }): RunTurnDeps {
52
+ return {
53
+ cwd: "/tmp",
54
+ name: "test",
55
+ systemPrompt: "base",
56
+ tools: [tool("read_file"), tool("open_search")],
57
+ approval: createExecApprovalGate({ policy: "auto" }),
58
+ store: createMemorySessionStore(),
59
+ provider,
60
+ observability: noopObservability,
61
+ ...extra,
62
+ };
63
+ }
64
+
65
+ function texts(events: AgentEvent[]): string {
66
+ return events
67
+ .filter((e) => e.kind === "text_delta")
68
+ .map((e) => (e as { text: string }).text)
69
+ .join("");
70
+ }
71
+
72
+ describe("displayMessage", () => {
73
+ test("the model sees the message and the transcript stores the display text", async () => {
74
+ const s = spy();
75
+ // The file store is what users get. Its new sessions start as "New chat" and take a real title.
76
+ const cwd = await mkdtemp(join(tmpdir(), "display-msg-"));
77
+ try {
78
+ const d = deps({ constructAgent: s.constructAgent, store: createFileSessionStore(cwd) });
79
+ const session = await runTurn(
80
+ d,
81
+ { message: "[Mode banner]\n\nopen my notes", displayMessage: "open my notes" },
82
+ () => undefined,
83
+ );
84
+ expect(s.seen.message).toBe("[Mode banner]\n\nopen my notes");
85
+ const user = session?.messages.find((m) => m.kind === "turn" && m.role === "user");
86
+ expect(user && "content" in user ? user.content : "").toBe("open my notes");
87
+ expect(session?.title).toBe("open my notes");
88
+ expect(JSON.stringify(session)).not.toContain("Mode banner");
89
+ } finally {
90
+ await rm(cwd, { recursive: true, force: true });
91
+ }
92
+ });
93
+
94
+ test("without it the message is stored as before", async () => {
95
+ const s = spy();
96
+ const session = await runTurn(
97
+ deps({ constructAgent: s.constructAgent }),
98
+ { message: "hello" },
99
+ () => undefined,
100
+ );
101
+ const user = session?.messages.find((m) => m.kind === "turn" && m.role === "user");
102
+ expect(user && "content" in user ? user.content : "").toBe("hello");
103
+ });
104
+ });
105
+
106
+ describe("systemAppend and excludeTools", () => {
107
+ test("apply to one turn only", async () => {
108
+ const s = spy();
109
+ const d = deps({ constructAgent: s.constructAgent });
110
+ await runTurn(
111
+ d,
112
+ { message: "hi", systemAppend: "Speak plainly.", excludeTools: ["open_search"] },
113
+ () => undefined,
114
+ );
115
+ expect(s.seen.system).toContain("Speak plainly.");
116
+ expect(s.seen.tools).toEqual(["read_file"]);
117
+ await runTurn(d, { message: "again" }, () => undefined);
118
+ expect(s.seen.system).not.toContain("Speak plainly.");
119
+ expect(s.seen.tools).toEqual(["read_file", "open_search"]);
120
+ });
121
+
122
+ test("hidden tools are not offered to an interceptor either", async () => {
123
+ const s = spy();
124
+ let names: string[] = [];
125
+ const intercept: TurnInterceptor = async ({ toolNames }) => {
126
+ names = [...toolNames];
127
+ return undefined;
128
+ };
129
+ await runTurn(
130
+ deps({ constructAgent: s.constructAgent, intercept }),
131
+ { message: "hi", excludeTools: ["open_search"] },
132
+ () => undefined,
133
+ );
134
+ expect(names).toEqual(["read_file"]);
135
+ });
136
+ });
137
+
138
+ describe("intercept", () => {
139
+ test("a reply ends the turn without calling the agent", async () => {
140
+ const s = spy();
141
+ const events: AgentEvent[] = [];
142
+ const session = await runTurn(
143
+ deps({ constructAgent: s.constructAgent, intercept: async () => ({ reply: "handled" }) }),
144
+ { message: "do it" },
145
+ (e) => events.push(e),
146
+ );
147
+ expect(s.seen.ran).toBe(0);
148
+ expect(texts(events)).toBe("handled");
149
+ expect(events.at(-1)?.kind).toBe("completion");
150
+ const roles = session?.messages
151
+ .map((m) => (m.kind === "turn" ? m.role : m.kind))
152
+ .filter((r) => r !== "system");
153
+ expect(roles).toEqual(["user", "assistant"]);
154
+ });
155
+
156
+ test("does not repeat text the interceptor already streamed", async () => {
157
+ const s = spy();
158
+ const events: AgentEvent[] = [];
159
+ await runTurn(
160
+ deps({
161
+ constructAgent: s.constructAgent,
162
+ intercept: async ({ emit }) => {
163
+ emit({ kind: "text_delta", text: "streamed once" });
164
+ return { reply: "streamed once" };
165
+ },
166
+ }),
167
+ { message: "do it" },
168
+ (e) => events.push(e),
169
+ );
170
+ expect(texts(events)).toBe("streamed once");
171
+ });
172
+
173
+ test("returning undefined, or throwing before any output, passes to the agent", async () => {
174
+ for (const intercept of [
175
+ async () => undefined,
176
+ async () => {
177
+ throw new Error("boom");
178
+ },
179
+ ] as TurnInterceptor[]) {
180
+ const s = spy();
181
+ await runTurn(
182
+ deps({ constructAgent: s.constructAgent, intercept }),
183
+ { message: "x" },
184
+ () => undefined,
185
+ );
186
+ expect(s.seen.ran).toBe(1);
187
+ }
188
+ });
189
+
190
+ test("throwing after output ends the turn with an error and never double-answers", async () => {
191
+ const s = spy();
192
+ const events: AgentEvent[] = [];
193
+ await runTurn(
194
+ deps({
195
+ constructAgent: s.constructAgent,
196
+ intercept: async ({ emit }) => {
197
+ emit({ kind: "text_delta", text: "partial work " });
198
+ throw new Error("lost the window");
199
+ },
200
+ }),
201
+ { message: "do it" },
202
+ (e) => events.push(e),
203
+ );
204
+ expect(s.seen.ran).toBe(0);
205
+ expect(texts(events)).toBe("partial work ");
206
+ expect(events.at(-1)).toMatchObject({ kind: "error", message: "lost the window" });
207
+ expect(events.some((e) => e.kind === "completion")).toBe(false);
208
+ });
209
+
210
+ test("is skipped when editing an earlier turn", async () => {
211
+ const s = spy();
212
+ const store = createMemorySessionStore();
213
+ const first = await runTurn(
214
+ deps({ constructAgent: s.constructAgent, store }),
215
+ { message: "one" },
216
+ () => undefined,
217
+ );
218
+ let called = 0;
219
+ await runTurn(
220
+ deps({
221
+ constructAgent: s.constructAgent,
222
+ store,
223
+ intercept: async () => {
224
+ called += 1;
225
+ return { reply: "no" };
226
+ },
227
+ }),
228
+ { message: "edited", sessionId: first?.id, editUserTurn: 0 },
229
+ () => undefined,
230
+ );
231
+ expect(called).toBe(0);
232
+ });
233
+
234
+ test("a storage failure while saving the reply is an error, not a rejection", async () => {
235
+ const s = spy();
236
+ const real = createMemorySessionStore();
237
+ const store: typeof real = {
238
+ ...real,
239
+ async append(session, message) {
240
+ if (message.kind === "turn" && message.role === "assistant") throw new Error("disk full");
241
+ return real.append(session, message);
242
+ },
243
+ };
244
+ const events: AgentEvent[] = [];
245
+ await runTurn(
246
+ deps({ constructAgent: s.constructAgent, store, intercept: async () => ({ reply: "ok" }) }),
247
+ { message: "x" },
248
+ (e) => events.push(e),
249
+ );
250
+ expect(events.at(-1)).toMatchObject({ kind: "error", message: "disk full" });
251
+ });
252
+ });
253
+
254
+ describe("through createHarness", () => {
255
+ test("the browser and decisions read the display text, not the host prefix", async () => {
256
+ const cwd = await mkdtemp(join(tmpdir(), "host-ext-"));
257
+ try {
258
+ const s = spy();
259
+ let started = 0;
260
+ const harness = await createHarness({
261
+ cwd,
262
+ config: DEFAULT_CONFIG,
263
+ provider,
264
+ constructAgent: s.constructAgent,
265
+ observability: noopObservability,
266
+ browserLoader: async () => {
267
+ started += 1;
268
+ return { tools: [], close: () => undefined };
269
+ },
270
+ });
271
+ // @browser only in the host prefix: must NOT turn the browser on.
272
+ await harness.runTurn("[Host says @browser]\n\nhello", () => undefined, {
273
+ displayMessage: "hello",
274
+ });
275
+ expect(started).toBe(0);
276
+ // @browser in what the user typed: turns it on.
277
+ await harness.runTurn("[banner]\n\n@browser open it", () => undefined, {
278
+ displayMessage: "@browser open it",
279
+ });
280
+ expect(started).toBe(1);
281
+ harness.close();
282
+ } finally {
283
+ await rm(cwd, { recursive: true, force: true });
284
+ }
285
+ });
286
+
287
+ test("systemAppend at construction applies to every turn, and promptOnly skips other prompts", async () => {
288
+ const cwd = await mkdtemp(join(tmpdir(), "host-ext-"));
289
+ try {
290
+ let system = "";
291
+ let asked = 0;
292
+ const harness = await createHarness({
293
+ cwd,
294
+ config: DEFAULT_CONFIG,
295
+ provider,
296
+ systemAppend: "You are the host app.",
297
+ constructAgent: (input) => {
298
+ system = input.systemPrompt;
299
+ return {
300
+ async run() {
301
+ await input.tools.find((t) => t.name === "exec")?.invoke({ command: "echo hi" });
302
+ await input.tools.find((t) => t.name === "exec")?.invoke({ command: "rm -rf x" });
303
+ },
304
+ };
305
+ },
306
+ observability: noopObservability,
307
+ });
308
+ await harness.runTurn("go", () => undefined, {
309
+ approvalAsk: async () => {
310
+ asked += 1;
311
+ return false;
312
+ },
313
+ promptOnly: (req) => /\brm\b/.test(String(req.input.command ?? "")),
314
+ });
315
+ expect(system).toContain("You are the host app.");
316
+ expect(asked).toBe(1);
317
+ harness.close();
318
+ } finally {
319
+ await rm(cwd, { recursive: true, force: true });
320
+ }
321
+ });
322
+ });
323
+
324
+ describe("hostData", () => {
325
+ test("reaches the interceptor untouched, and is empty when unset", async () => {
326
+ const s = spy();
327
+ const seen: Array<Record<string, unknown>> = [];
328
+ const intercept: TurnInterceptor = async ({ hostData }) => {
329
+ seen.push(hostData);
330
+ return undefined;
331
+ };
332
+ const d = deps({ constructAgent: s.constructAgent, intercept });
333
+ await runTurn(d, { message: "a", hostData: { autoApprove: true, n: 2 } }, () => undefined);
334
+ await runTurn(d, { message: "b" }, () => undefined);
335
+ expect(seen).toEqual([{ autoApprove: true, n: 2 }, {}]);
336
+ });
337
+
338
+ test("flows from createHarness turn options", async () => {
339
+ const cwd = await mkdtemp(join(tmpdir(), "host-data-"));
340
+ try {
341
+ let seen: Record<string, unknown> = {};
342
+ const harness = await createHarness({
343
+ cwd,
344
+ config: DEFAULT_CONFIG,
345
+ provider,
346
+ constructAgent: spy().constructAgent,
347
+ observability: noopObservability,
348
+ intercept: async ({ hostData }) => {
349
+ seen = hostData;
350
+ return undefined;
351
+ },
352
+ });
353
+ await harness.runTurn("hi", () => undefined, { hostData: { mode: "voice" } });
354
+ expect(seen).toEqual({ mode: "voice" });
355
+ harness.close();
356
+ } finally {
357
+ await rm(cwd, { recursive: true, force: true });
358
+ }
359
+ });
360
+ });
361
+
362
+ describe("provider factory for hosts", () => {
363
+ test("the interceptor receives the user's words and a provider factory", async () => {
364
+ const s = spy();
365
+ let seenMessage = "";
366
+ let hasProvider = false;
367
+ const calls: Array<[string, string | undefined]> = [];
368
+ await runTurn(
369
+ deps({
370
+ constructAgent: s.constructAgent,
371
+ resolveProvider: (id, title) => {
372
+ calls.push([id, title]);
373
+ return provider;
374
+ },
375
+ intercept: async (ctx) => {
376
+ seenMessage = ctx.message;
377
+ hasProvider = typeof ctx.provider === "function";
378
+ ctx.provider?.("acme/model", "agent:writer");
379
+ return { reply: "done" };
380
+ },
381
+ }),
382
+ { message: "[banner]\n\nopen notes", displayMessage: "open notes" },
383
+ () => undefined,
384
+ );
385
+ expect(seenMessage).toBe("open notes");
386
+ expect(hasProvider).toBe(true);
387
+ expect(calls).toEqual([["acme/model", "agent:writer"]]);
388
+ });
389
+
390
+ test("with a fixed provider the factory returns it for every model", async () => {
391
+ const s = spy();
392
+ let got: MainModelProvider | undefined;
393
+ await runTurn(
394
+ deps({
395
+ constructAgent: s.constructAgent,
396
+ intercept: async (ctx) => {
397
+ got = ctx.provider("any/model", "agent:writer");
398
+ return { reply: "done" };
399
+ },
400
+ }),
401
+ { message: "hi" },
402
+ () => undefined,
403
+ );
404
+ expect(got).toBe(provider);
405
+ });
406
+
407
+ test("the title becomes the X-Title header on real OpenRouter calls", async () => {
408
+ const { constructOpenRouterProvider } = await import("./strands.ts");
409
+ const seenTitles: string[] = [];
410
+ const realFetch = globalThis.fetch;
411
+ globalThis.fetch = (async (_url: unknown, init?: RequestInit) => {
412
+ const headers = new Headers(init?.headers);
413
+ seenTitles.push(headers.get("x-title") ?? "");
414
+ return new Response(JSON.stringify({ error: { message: "stop" } }), { status: 400 });
415
+ }) as unknown as typeof fetch;
416
+ try {
417
+ for (const title of ["agent:writer", undefined]) {
418
+ const p = constructOpenRouterProvider({
419
+ apiKey: "sk-test",
420
+ model: "acme/model",
421
+ baseUrl: "https://openrouter.ai/api/v1",
422
+ ...(title ? { title } : {}),
423
+ });
424
+ for await (const _event of p.stream({ messages: [{ role: "user", content: "hi" }] })) {
425
+ // drain
426
+ }
427
+ }
428
+ } finally {
429
+ globalThis.fetch = realFetch;
430
+ }
431
+ expect(seenTitles[0]).toBe("agent:writer");
432
+ expect(seenTitles[1]).toBe("Caelence agent");
433
+ });
434
+ });
435
+
436
+ describe("browser turn option", () => {
437
+ async function setup(config: Partial<typeof DEFAULT_CONFIG> = {}) {
438
+ const cwd = await mkdtemp(join(tmpdir(), "host-browser-"));
439
+ const counter = { starts: 0 };
440
+ const seen = { tools: [] as string[] };
441
+ const harness = await createHarness({
442
+ cwd,
443
+ config: { ...DEFAULT_CONFIG, ...config },
444
+ provider,
445
+ observability: noopObservability,
446
+ constructAgent: (input) => {
447
+ seen.tools = input.tools.map((t) => t.name);
448
+ return { async run() {} };
449
+ },
450
+ browserLoader: async () => {
451
+ counter.starts += 1;
452
+ return {
453
+ tools: [
454
+ {
455
+ name: "browser__browser_navigate",
456
+ description: "navigate",
457
+ inputSchema: { type: "object", properties: {} },
458
+ annotations: UNKNOWN_TOOL_ANNOTATIONS,
459
+ async handler() {
460
+ return textResult("ok");
461
+ },
462
+ },
463
+ ],
464
+ close: () => undefined,
465
+ };
466
+ },
467
+ });
468
+ return { cwd, harness, counter, seen };
469
+ }
470
+
471
+ test("turns the browser on for the turn and the rest of the chat, without @browser", async () => {
472
+ const { cwd, harness, counter, seen } = await setup();
473
+ try {
474
+ expect(harness.browserActive).toBe(false);
475
+ await harness.runTurn("write an article on medium", () => undefined, { browser: true });
476
+ expect(seen.tools).toContain("browser__browser_navigate");
477
+ expect(harness.browserActive).toBe(true);
478
+ await harness.runTurn("now publish it", () => undefined);
479
+ expect(seen.tools).toContain("browser__browser_navigate");
480
+ expect(counter.starts).toBe(1);
481
+ } finally {
482
+ harness.close();
483
+ await rm(cwd, { recursive: true, force: true });
484
+ }
485
+ });
486
+
487
+ test("does not start the server on turns that do not ask for it", async () => {
488
+ const { cwd, harness, counter, seen } = await setup();
489
+ try {
490
+ await harness.runTurn("hello", () => undefined, { browser: false });
491
+ await harness.runTurn("hello again", () => undefined);
492
+ expect(counter.starts).toBe(0);
493
+ expect(seen.tools).not.toContain("browser__browser_navigate");
494
+ expect(harness.browserActive).toBe(false);
495
+ } finally {
496
+ harness.close();
497
+ await rm(cwd, { recursive: true, force: true });
498
+ }
499
+ });
500
+
501
+ test("a new chat turns it off again", async () => {
502
+ const { cwd, harness } = await setup();
503
+ try {
504
+ await harness.runTurn("go", () => undefined, { browser: true });
505
+ expect(harness.browserActive).toBe(true);
506
+ harness.setSession(undefined);
507
+ expect(harness.browserActive).toBe(false);
508
+ } finally {
509
+ harness.close();
510
+ await rm(cwd, { recursive: true, force: true });
511
+ }
512
+ });
513
+
514
+ test("config enabled:false wins over the turn option", async () => {
515
+ const { cwd, harness, counter } = await setup({ browser: { enabled: false } });
516
+ try {
517
+ await harness.runTurn("go", () => undefined, { browser: true });
518
+ expect(counter.starts).toBe(0);
519
+ expect(harness.browserActive).toBe(false);
520
+ } finally {
521
+ harness.close();
522
+ await rm(cwd, { recursive: true, force: true });
523
+ }
524
+ });
525
+
526
+ test("is ignored outside agent mode", async () => {
527
+ const { cwd, harness, counter } = await setup({ mode: "ask" });
528
+ try {
529
+ await harness.runTurn("go", () => undefined, { browser: true });
530
+ expect(counter.starts).toBe(0);
531
+ expect(harness.browserActive).toBe(false);
532
+ } finally {
533
+ harness.close();
534
+ await rm(cwd, { recursive: true, force: true });
535
+ }
536
+ });
537
+ });
538
+
539
+ describe("own-Chrome backend restarts after the browser becomes ready", () => {
540
+ test("a failed attach is retried on the next turn with a fresh server", async () => {
541
+ const cwd = await mkdtemp(join(tmpdir(), "host-restart-"));
542
+ const starts: number[] = [];
543
+ const closes: number[] = [];
544
+ let ready = false;
545
+ const seen = { tools: [] as string[] };
546
+ const harness = await createHarness({
547
+ cwd,
548
+ config: { ...DEFAULT_CONFIG, browser: { backend: "chrome", app: "arc" } },
549
+ provider,
550
+ observability: noopObservability,
551
+ constructAgent: (input) => {
552
+ seen.tools = input.tools.map((t) => t.name);
553
+ return {
554
+ async run() {
555
+ // The agent's first browser action each turn.
556
+ await input.tools
557
+ .find((t) => t.name === "browser__browser_tabs")
558
+ ?.invoke({ action: "list" });
559
+ },
560
+ };
561
+ },
562
+ browserLoader: async () => {
563
+ const id = starts.length;
564
+ starts.push(id);
565
+ const isReady = ready;
566
+ return {
567
+ tools: [
568
+ {
569
+ name: "browser__browser_tabs",
570
+ description: "tabs",
571
+ inputSchema: { type: "object", properties: {} },
572
+ annotations: UNKNOWN_TOOL_ANNOTATIONS,
573
+ async handler() {
574
+ return isReady
575
+ ? textResult("### Result - 0: (current) [](about:blank)")
576
+ : textResult(
577
+ "Error: Could not connect to chrome: DevToolsActivePort file not found",
578
+ true,
579
+ );
580
+ },
581
+ },
582
+ ],
583
+ close: () => {
584
+ closes.push(id);
585
+ },
586
+ };
587
+ },
588
+ });
589
+ try {
590
+ await harness.runTurn("@browser go", () => undefined);
591
+ expect(starts).toHaveLength(1);
592
+ // The user turns the switch on. The next turn must not reuse the dead server.
593
+ ready = true;
594
+ await harness.runTurn("done, try again", () => undefined);
595
+ expect(starts).toHaveLength(2);
596
+ expect(closes).toEqual([0]);
597
+ // Healthy now: a third turn reuses the second server.
598
+ await harness.runTurn("and again", () => undefined);
599
+ expect(starts).toHaveLength(2);
600
+ } finally {
601
+ harness.close();
602
+ await rm(cwd, { recursive: true, force: true });
603
+ }
604
+ });
605
+ });
package/src/core/mcp.ts CHANGED
@@ -68,6 +68,13 @@ export interface McpToolDefinition {
68
68
  inputSchema: Record<string, unknown>;
69
69
  annotations: McpToolAnnotations;
70
70
  handler(input: Record<string, unknown>): Promise<ToolResult>;
71
+ /**
72
+ * Return a short, plain reason when this particular call needs the user's approval, or nothing
73
+ * when it can run. Unlike a tool that is always risky, this decides per call. An approval the
74
+ * user gives for one call never covers the next, and "always allow" and host auto-approve
75
+ * modes do not skip it.
76
+ */
77
+ confirm?(input: Record<string, unknown>): string | undefined;
71
78
  }
72
79
 
73
80
  export interface McpToolSet {