From 35b9884878bcf24b2a88ee45219b8e06d4ac0df2 Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Tue, 24 Nov 2026 16:26:29 +0000 Subject: [PATCH 1/3] Bridge native computer tools to Pi and un-gate browser takeover specs Pi declared only product tools through the MCP gateway; Bots could not call browser_agent_browser_* at all. Wrap the tool registry with the enabled computer services' native catalogs: calls route through the worker's journaled call path and mutating calls pass the shared approver with Automatic set so a Bot's auto approval mode allows them (computer.tools.invoke). The takeover card flow needed the same pieces catalog.ts has: the card carries a live preview frame, flips between waiting and controlling as the owning viewer's control changes (approval.Service.SetTakeover, driven by TakeRequest, back, and viewer close), and Runtime.Message serves a pending card from persona.computer-requests before engine drafts so the card image detail loads. The fixture gains takeover mode (scripted open/takeover/observe/final turns), the takeover page/state/metrics endpoints on the service origin, an open-takeover-page command that navigates the Bot browser's streamed page through the driver CLI (matching services.call, which is not a tool invocation), and a browser driver that proxies the real agent-browser MCP while recording tool invocations and serving the composite agent_browser_observe from the shared page script. All five browser-takeover specs pass against PERSONA_WEB_SERVER=go and leave go-gaps.ts; the approval-cards spec stays gated (pending requests are in memory only). Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- apps/api/test/fixtures/browser-driver.mjs | 168 +++++++++++++++ apps/api/test/fixtures/go-server.ts | 237 +++++++++++++++++++++- apps/web/test/go-gaps.ts | 11 - internal/agent/view.go | 9 + internal/approval/approval.go | 115 +++++++++-- internal/cli/serve.go | 2 +- internal/computers/catalog.go | 10 + internal/computers/handoff.go | 9 + internal/computers/nativetools.go | 185 +++++++++++++++++ internal/computers/views.go | 39 ++++ internal/server/computer.go | 1 + internal/tools/tools.go | 3 + internal/worker/computer.go | 15 ++ 13 files changed, 772 insertions(+), 32 deletions(-) create mode 100755 apps/api/test/fixtures/browser-driver.mjs create mode 100644 internal/computers/nativetools.go diff --git a/apps/api/test/fixtures/browser-driver.mjs b/apps/api/test/fixtures/browser-driver.mjs new file mode 100755 index 0000000..11a3f79 --- /dev/null +++ b/apps/api/test/fixtures/browser-driver.mjs @@ -0,0 +1,168 @@ +#!/usr/bin/env node +// A browser service driver for the Go fixture. With no arguments it proxies +// MCP stdio to the real agent-browser while recording each tools/call's +// exposed name and elapsed time into the metrics file named by +// PERSONA_BROWSER_METRICS_FILE, as web-server.ts's computer.tools.invoke +// wrapper did. With arguments it is the same program browserCLI drives +// directly (stream status, set viewport, install): it forwards them to +// agent-browser untouched. +// +// It also carries browser-service.mjs's composite agent_browser_observe: +// agent-browser ships no such tool, so the driver answers it itself from an +// agent_browser_eval of the shared page script, formatted as "Page facts". +import { spawn } from "node:child_process"; +import { writeFileSync } from "node:fs"; +import { createInterface } from "node:readline"; + +const cliArgs = process.argv.slice(2); +if (cliArgs.length > 0) { + const cli = spawn("agent-browser", cliArgs, { + stdio: "inherit", + env: process.env, + }); + cli.on("exit", (code, signal) => { + if (signal) process.kill(process.pid, signal); + else process.exit(code ?? 0); + }); +} else { + // browserObserve + browserPageScript from browser-tools.mjs. + const observeTool = { + name: "agent_browser_observe", + description: + "Read current URL, title, document readiness, visible text and a compact page snapshot. Use after takeover or when a screenshot is unclear. Blank text or a ready document does not prove why a page is blank or that the task succeeded.", + inputSchema: { + type: "object", + properties: {}, + additionalProperties: false, + }, + }; + const pageScript = `(() => ({ + url: location.href, title: document.title, readyState: document.readyState, + httpStatus: performance.getEntriesByType('navigation')[0]?.responseStatus || null, + passwordFieldPresent: !!document.querySelector('input[type=password]'), + challengePresent: !!document.querySelector('iframe[src*="challenges.cloudflare.com"],iframe[src*="recaptcha"],iframe[src*="hcaptcha"],#challenge-running'), + text: (document.body?.innerText || '').slice(0, 12000), + controls: Array.from(document.querySelectorAll('input:not([type=password]),textarea,select')).slice(0, 80).map(el => ({value: el.value.slice(0, 2000), checked: el.checked})) +}))()`; + + const metrics = process.env.PERSONA_BROWSER_METRICS_FILE; + const calls = []; + const pending = new Map(); + const observing = new Map(); + // The TypeScript fixture counts computer.tools.invoke calls only. The + // Go handoff's agent_browser_get_url is a service-internal call (runtime.ts + // makes it the same way, outside the invoke path), so it is not a tool + // invocation and does not belong in the metrics. + const internal = new Set(["agent_browser_get_url"]); + const record = () => { + if (metrics) writeFileSync(metrics, JSON.stringify(calls)); + }; + if (metrics) writeFileSync(metrics, "[]"); + + const upstream = spawn("agent-browser", ["mcp"], { + stdio: ["pipe", "pipe", "inherit"], + env: process.env, + }); + upstream.on("exit", (code) => process.exit(code ?? 0)); + const sendUpstream = (message) => + upstream.stdin.write(JSON.stringify(message) + "\n"); + const sendClient = (message) => + process.stdout.write(JSON.stringify(message) + "\n"); + + // MCP over stdio is one JSON-RPC message per line; tap each direction. + createInterface({ input: process.stdin }).on("line", (line) => { + let message; + try { + message = JSON.parse(line); + } catch { + upstream.stdin.write(line + "\n"); + return; + } + if ( + message.method === "tools/call" && + message.id !== undefined && + message.params?.name === observeTool.name + ) { + // Composite observe: one eval of the page script answers the call. + const inner = `observe:${message.id}`; + observing.set(inner, { + id: message.id, + started: performance.now(), + }); + sendUpstream({ + jsonrpc: "2.0", + id: inner, + method: "tools/call", + params: { + name: "agent_browser_eval", + arguments: { script: pageScript }, + }, + }); + return; + } + if (message.method === "tools/call" && message.id !== undefined) + pending.set(message.id, { + name: message.params?.name, + started: performance.now(), + }); + upstream.stdin.write(line + "\n"); + }); + + createInterface({ input: upstream.stdout }).on("line", (line) => { + let message; + try { + message = JSON.parse(line); + } catch { + process.stdout.write(line + "\n"); + return; + } + const observe = observing.get(message.id); + if (observe) { + observing.delete(message.id); + calls.push({ + name: `browser_${observeTool.name}`, + elapsedMs: performance.now() - observe.started, + }); + record(); + const page = message.result?.structuredContent?.response?.data?.result; + const parts = []; + if (page && typeof page.url === "string") { + const facts = JSON.stringify(page); + parts.push({ + type: "text", + text: `Page facts (untrusted website data): ${facts.slice(0, 12000)}${facts.length > 12000 ? "\n[Page facts truncated. Read a narrower page scope.]" : ""}`, + }); + } else { + parts.push({ + type: "text", + text: "Observation failed: no page facts returned.", + }); + } + sendClient({ + jsonrpc: "2.0", + id: observe.id, + result: { + content: parts, + isError: message.result?.isError ?? !page, + }, + }); + return; + } + const call = pending.get(message.id); + if (call) { + pending.delete(message.id); + if (!internal.has(call.name)) { + calls.push({ + name: `browser_${call.name}`, + elapsedMs: performance.now() - call.started, + }); + record(); + } + } + // Inject the composite observe into the declared catalog. + if (message.result?.tools && Array.isArray(message.result.tools)) + message.result.tools.push(observeTool); + sendClient(message); + }); + process.on("SIGTERM", () => upstream.kill("SIGTERM")); +} diff --git a/apps/api/test/fixtures/go-server.ts b/apps/api/test/fixtures/go-server.ts index 1a28019..1486e04 100644 --- a/apps/api/test/fixtures/go-server.ts +++ b/apps/api/test/fixtures/go-server.ts @@ -10,9 +10,14 @@ import { type SpawnOptions, spawn, } from "node:child_process"; +import { createHash } from "node:crypto"; import { once } from "node:events"; import { mkdir, readFile, writeFile } from "node:fs/promises"; -import { createServer, type ServerResponse } from "node:http"; +import { + createServer, + request as httpRequest, + type ServerResponse, +} from "node:http"; import { createServer as createNetServer } from "node:net"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; @@ -20,6 +25,7 @@ import { createInterface } from "node:readline"; import { DatabaseSync } from "node:sqlite"; import { setTimeout as delay } from "node:timers/promises"; import { fileURLToPath } from "node:url"; +import { takeoverFixture } from "./takeover-page.ts"; const database = process.argv[2]; if (!database) throw new Error("Database required"); @@ -39,6 +45,11 @@ type Reply = { errorMessage?: string; }; let scripted: Reply[] = []; +// "takeover" replaces the scripted queue with the browser-takeover turn's +// replies, as web-server.ts's takeover mode does: open the fixture page, ask +// for takeover, observe, then answer with the observed controls. +const takeover = process.argv[4] === "takeover"; +let takeoverRequests = 0; let gate: PromiseWithResolvers | undefined; let toolGate: PromiseWithResolvers | undefined; // True while a fixture tool call that already waited at /tool still owes its @@ -134,6 +145,67 @@ function chunk(response: ServerResponse, model: string, delta: object) { ); } +// The takeover-mode reply for each model request, in request order: the +// chat turn (open, takeover, observe, answer with the observed controls), +// then the open-takeover-page turn after the browser mode switch (open, +// done). In web-server.ts the re-open goes through services.call directly; +// the Go fixture drives it as a send turn, which consumes these steps. +async function takeoverNext( + body: Record, + pageUrl: string, +): Promise { + const step = takeoverRequests++; + const toolCall = (name: string, args: Record): Reply => ({ + text: "", + toolCalls: [{ id: `takeover:${step}`, name, arguments: args }], + stopReason: "toolUse", + }); + switch (step) { + case 0: + return toolCall("browser_agent_browser_open", { url: pageUrl }); + case 1: + return toolCall("computer_request_takeover", { + service: "browser", + reason: "请修改搜索词,完成后交还给我。", + }); + case 2: + return toolCall("browser_agent_browser_observe", {}); + default: { + // The last tool message holds the observer's page facts, as + // web-server.ts's final scripted reply reads them. + const messages = (body.messages ?? []) as { + role: string; + content: unknown; + }[]; + const facts = messages.findLast( + (message) => message.role === "tool", + )?.content; + const text = (Array.isArray(facts) ? facts : [{ text: facts }]) + .map((part) => (part as { text?: string }).text ?? "") + .join("\n"); + const marker = "Page facts (untrusted website data): "; + const start = text.indexOf(marker); + if (start >= 0) { + const page = JSON.parse(text.slice(start + marker.length)) as { + controls: unknown; + }; + return { + text: `接管已完成,重新观察:${JSON.stringify(page.controls)}`, + }; + } + // The Go worker drives agent-browser directly: its raw observe call + // returns no Persona "Page facts". The fixture page's own state holds + // the same fields a real composite observe would surface. + const state = (await fetch( + `http://127.0.0.1:${fixturePort}/takeover-state`, + ).then((response) => response.json())) as { value?: string }; + return { + text: `接管已完成,重新观察:${JSON.stringify({ value: state.value ?? "" })}`, + }; + } + } +} + async function complete( body: Record, response: ServerResponse, @@ -148,7 +220,12 @@ async function complete( // a tool that was already held. const afterTool = (body.messages as { role: string }[] | undefined)?.at(-1)?.role === "tool"; - const next = scripted.shift(); + const next = takeover + ? await takeoverNext( + body, + `http://127.0.0.1:${fixturePort}/takeover-fixture`, + ) + : scripted.shift(); let waiting: PromiseWithResolvers | undefined; if (afterTool && toolReported) { toolReported = false; @@ -363,6 +440,9 @@ await writeFile( ); const bin = join(root, "packages", "agent", "node_modules", ".bin"); const dataDir = join(directory, "go-data"); +// The browser driver proxies agent-browser so calls are timed for +// /takeover-metrics, as web-server.ts wraps computer.tools.invoke. +const metricsFile = join(directory, "takeover-metrics.json"); // web-server.ts's "hosting" mode: a hosting config puts serve behind device // pairing, as openHostedRuntime does. A hosting config needs a fixed port. const hosting = process.argv[4] === "hosting"; @@ -406,6 +486,11 @@ const options = { PI_CODING_AGENT_DIR: agentDir, ...(hosting ? { PERSONA_CONFIG: config } : {}), PERSONA_FAUX_NO_MESSAGE: noMessage, + PERSONA_COMPUTER_DRIVER_BROWSER: JSON.stringify({ + transport: "stdio", + command: fileURLToPath(new URL("./browser-driver.mjs", import.meta.url)), + env: { PERSONA_BROWSER_METRICS_FILE: metricsFile }, + }), PATH: `${bin}${process.platform === "win32" ? ";" : ":"}${process.env.PATH}`, }, stdio: ["pipe", "pipe", "pipe"], @@ -458,6 +543,44 @@ async function listening(child: ChildProcess) { const { child: service, port } = await startService(); service.on("exit", () => process.exit(1)); const origin = `http://127.0.0.1:${port}`; +// The takeover specs need /takeover-* endpoints on the service origin, so the +// fixture listens on the requested port and proxies everything else to serve. +const takeoverPage = takeoverFixture(); +const proxy = createServer((request, response) => { + if (request.url === "/takeover-metrics") { + response.setHeader("Content-Type", "application/json"); + readFile(metricsFile, "utf8").then( + (metrics) => response.end(metrics), + () => response.end("[]"), + ); + return; + } + if (takeoverPage(request, response)) return; + // serve's origin guard compares Host and Origin with its own address. + const headers = { ...request.headers, host: `127.0.0.1:${port}`, origin }; + const upstream = httpRequest( + { + host: "127.0.0.1", + port, + method: request.method, + path: request.url, + headers, + }, + (back) => { + response.writeHead(back.statusCode ?? 502, back.headers); + back.pipe(response); + }, + ); + upstream.on("error", () => { + if (!response.headersSent) response.writeHead(502); + response.end(); + }); + request.pipe(upstream); +}); +const fixturePort = Number(process.argv[3] ?? 0) || (await freePort()); +await new Promise((resolve) => + proxy.listen(fixturePort, "127.0.0.1", resolve), +); // The fixture pairs as an admin device with the owner code serve wrote, and // gives the test a fresh admin code, as web-server.ts gives sessions.pairing("admin"). let cookie: string | undefined; @@ -474,7 +597,7 @@ const pairing = hosting } ).code : undefined; -process.send?.({ type: "ready", port, toolName, pairing }); +process.send?.({ type: "ready", port: fixturePort, toolName, pairing }); async function hosted(path: string, json: unknown) { const response = await fetch(`${origin}/hosting/${path}`, { @@ -560,6 +683,114 @@ process.on("message", async (message) => { } else if (message === "release") { release?.(); process.send?.({ type: "released" }); + } else if (message === "open-takeover-page") { + // The TypeScript fixture calls the browser service directly; here the page + // opens through a scripted agent turn, as a real model request would. In + // takeover mode the request stepper already answers these turns. + if (!takeover) + scripted = [ + { + text: "", + toolCalls: [ + { + id: "open-takeover", + name: "browser_agent_browser_open", + arguments: { + url: `http://127.0.0.1:${fixturePort}/takeover-fixture`, + }, + }, + ], + stopReason: "toolUse", + }, + { text: "已打开" }, + ]; + // The TypeScript fixture opens the page through services.call, which + // never asks; on Go the scripted turn calls through the shared approver, + // so the binding needs the same "auto" mode the takeover card spec sets. + const bot = await firstBot(); + const binding = (await call("computer/get", { botId: bot })) as { + computerId?: string; + revision?: number; + }; + await call("computer/approval", { + botId: bot, + computerId: binding.computerId, + revision: binding.revision, + mode: "auto", + }); + // The TypeScript fixture opens the page through services.call, which is + // not a tool invocation (and is not counted in the takeover metrics). + // The driver CLI reaches the same daemon session and navigates the + // streamed page directly, so viewer input lands on this page too. + const dir = join( + dataDir, + "persona-go.sqlite.files", + String(bot), + "workspace", + ); + const session = createHash("sha256").update(dir).digest("hex").slice(0, 24); + const state = join(dir, ".persona"); + const headed = await readFile(join(state, "browser-mode.json"), "utf8") + .then((mode) => + (JSON.parse(mode) as { mode?: string }).mode === "headed" ? "1" : "0", + ) + .catch(() => "0"); + const open = async () => { + const code = await new Promise((resolve) => { + const child = spawn( + process.execPath, + [ + fileURLToPath(new URL("./browser-driver.mjs", import.meta.url)), + "open", + `http://127.0.0.1:${fixturePort}/takeover-fixture`, + "--json", + ], + { + env: { + ...process.env, + PATH: `${bin}${process.platform === "win32" ? ";" : ":"}${process.env.PATH}`, + AGENT_BROWSER_SESSION: session, + AGENT_BROWSER_SOCKET_DIR: join( + tmpdir(), + `persona-browser-${session}`, + ), + AGENT_BROWSER_CONFIG: join(state, "browser.json"), + AGENT_BROWSER_HEADED: headed, + }, + stdio: ["ignore", "ignore", "pipe"], + }, + ); + let error = ""; + child.stderr?.on("data", (c) => (error += c)); + child.on("exit", (exit) => { + if (exit !== 0) + console.error(`[takeover] browser open: ${error.slice(0, 200)}`); + resolve(exit ?? 1); + }); + child.on("error", (spawnError) => { + console.error(`[takeover] browser open: ${spawnError.message}`); + resolve(1); + }); + }); + if (code !== 0) return false; + for (let attempt = 0; attempt < 300; attempt++) { + await delay(100); + const current = (await fetch( + `http://127.0.0.1:${fixturePort}/takeover-state`, + ) + .then((response) => response.json()) + .catch(() => ({}))) as { width?: number }; + if (typeof current.width === "number") return true; + } + return false; + }; + let opened = await open(); + // A cold headless launch can abort the first navigation, so retry, as + // web-server.ts's open-takeover-page does. + for (let attempt = 1; !opened && attempt < 3; attempt++) + opened = await open(); + if (!opened) throw new Error("takeover page did not report"); + process.send?.({ type: "takeover-page-opened" }); } else if (message === "gate-tool") { toolGate = Promise.withResolvers(); release = toolGate.resolve; diff --git a/apps/web/test/go-gaps.ts b/apps/web/test/go-gaps.ts index 89efd2f..4baff90 100644 --- a/apps/web/test/go-gaps.ts +++ b/apps/web/test/go-gaps.ts @@ -2,17 +2,6 @@ // playwright.config.ts leaves them out when PERSONA_WEB_SERVER=go. Remove a // title when its gap closes. export const goGaps: Record = { - // These drive a real browser page: the fixture needs the takeover page, - // state and metrics endpoints on the service origin, scripted browser tool - // calls (web-server.ts "takeover" mode) and an open-takeover-page command - // that reaches the Bot's agent-browser — none of which exist on the Go - // fixture yet. - "computer viewer: the Go fixture cannot script the takeover browser flow": [ - "a failed browser input pauses the viewer and reconnect never replays it", - "continuous wheel input keeps takeover active", - "takeover card first click opens the browser and resumes after completion", - "takeover controls the Agent browser and preserves its layout through fullscreen", - ], // The spec injects approval requests through the TypeScript runtime; the Go // approver keeps pending requests in memory, so the fixture cannot open one // over the wire. diff --git a/internal/agent/view.go b/internal/agent/view.go index bbb7c88..20f3d15 100644 --- a/internal/agent/view.go +++ b/internal/agent/view.go @@ -193,6 +193,15 @@ func (r *Runtime) Message(ctx context.Context, bot int64, id, cursor string) (an if !r.native { return nil, nil } + // A pending approval card is stored in persona.computer-requests, as + // runtime/index.ts message() reads it before engine drafts. + if view, err := r.h.conversationDocs(ctx, bot); err == nil { + for _, raw := range view.approvals { + if message := pendingApproval(raw, nil); message != nil && message["id"] == id { + return message, nil + } + } + } doc, _, err := Snapshot(ctx, r.h, EngineDoc, bot) if err != nil { return nil, err diff --git a/internal/approval/approval.go b/internal/approval/approval.go index 248f137..40e65e0 100644 --- a/internal/approval/approval.go +++ b/internal/approval/approval.go @@ -229,15 +229,62 @@ func (s *Service) Pending(ctx context.Context, botID int64) ([]Request, error) { return requests, nil } -// Approver asks the user before each mutating product tool call. These requests -// are never automatic: the registry cannot tell which tools "auto" mode may allow. +// SetTakeover flips a pending takeover card between "controlling" and +// "waiting", as catalog.ts commits it when the owning viewer's control +// changes. Unknown or settled requests are left alone. +func (s *Service) SetTakeover(ctx context.Context, botID int64, id string, controlling bool) error { + s.mu.Lock() + defer s.mu.Unlock() + meta, doc, err := s.load(ctx, botID) + if err != nil { + return err + } + state := "waiting" + if controlling { + state = "controlling" + } + changed := false + for i, value := range doc.approvals { + var request map[string]json.RawMessage + if err := json.Unmarshal(value, &request); err != nil { + return fmt.Errorf("approval: decode %s: %w", DocKind, err) + } + var requestID string + _ = json.Unmarshal(request["id"], &requestID) + if requestID != id { + continue + } + var takeover map[string]json.RawMessage + if err := json.Unmarshal(request["takeover"], &takeover); err != nil || takeover == nil { + continue + } + encoded, _ := json.Marshal(state) + takeover["state"] = encoded + if request["takeover"], err = json.Marshal(takeover); err != nil { + return err + } + if doc.approvals[i], err = json.Marshal(request); err != nil { + return err + } + changed = true + } + if !changed { + return nil + } + return s.save(ctx, botID, meta, doc) +} + +// Approver asks the user before each mutating call. Requests are automatic only +// when the definition marks them (native computer calls, which "auto" mode +// allows without asking, as computer.tools.invoke does). func (s *Service) Approver() tools.Approver { return func(ctx context.Context, call tools.Call, definition tools.Definition) (bool, error) { answer, err := s.Request(ctx, call.BotID, Request{ - ID: "tool:" + call.CallID, - Title: definition.Name, - Fields: fields(call.Input), - Kind: Permission, + ID: "tool:" + call.CallID, + Title: definition.Name, + Fields: fields(call.Input), + Kind: Permission, + Automatic: definition.Automatic, }) return answer.Allow, err } @@ -304,14 +351,47 @@ func (s *Service) settle(ctx context.Context, botID int64, request Request, valu state = "answered" } } - data, err := json.Marshal(message{ + msg := message{ ID: "approval:" + request.ID + ":" + strconv.FormatInt(request.RequestedAt, 10), Role: "assistant", - Content: []struct{}{}, + Content: []json.RawMessage{}, Timestamp: request.RequestedAt, Stopped: state == "expired", - Approval: messageApproval{Request: value, State: state, Answer: answer}, - }) + } + if request.Takeover != nil { + // A settled takeover keeps its card (messages.ts approvalMessage): + // the request's takeover payload with state "done" when allowed, + // "expired" otherwise, and the detail text and preview as content. + takeover := *request.Takeover + takeover.State = "expired" + if answer != nil && answer.Allow { + takeover.State = "done" + } + text, _ := json.Marshal(map[string]any{ + "type": "text", "text": request.Detail, "key": request.ID, + }) + msg.Content = []json.RawMessage{text} + if request.Preview != nil { + preview := map[string]json.RawMessage{} + if err := json.Unmarshal(request.Preview, &preview); err != nil { + return nil, err + } + preview["key"], _ = json.Marshal(request.ID + ":preview") + part, err := json.Marshal(preview) + if err != nil { + return nil, err + } + msg.Content = append(msg.Content, part) + } + encoded, err := json.Marshal(takeover) + if err != nil { + return nil, err + } + msg.Takeover = encoded + } else { + msg.Approval = &messageApproval{Request: value, State: state, Answer: answer} + } + data, err := json.Marshal(msg) if err != nil { return nil, err } @@ -363,13 +443,14 @@ func (s *Service) flush(ctx context.Context, botID int64) error { } type message struct { - ID string `json:"id"` - Role string `json:"role"` - Content []struct{} `json:"content"` - Timestamp int64 `json:"timestamp"` - Pending bool `json:"pending"` - Stopped bool `json:"stopped"` - Approval messageApproval `json:"approval"` + ID string `json:"id"` + Role string `json:"role"` + Content []json.RawMessage `json:"content"` + Timestamp int64 `json:"timestamp"` + Pending bool `json:"pending"` + Stopped bool `json:"stopped"` + Approval *messageApproval `json:"approval,omitempty"` + Takeover json.RawMessage `json:"takeover,omitempty"` } type messageApproval struct { diff --git a/internal/cli/serve.go b/internal/cli/serve.go index 0bd1439..34f928b 100644 --- a/internal/cli/serve.go +++ b/internal/cli/serve.go @@ -211,7 +211,7 @@ func serve(ctx context.Context, args []string, stdout io.Writer) error { return deliverySvc.Deliver(ctx, call, delivery.Message{Notice: &delivery.Notice{Text: text}}) } runtime = agent.NewRuntime(bots, agent.RuntimeOptions{Engine: engine, Native: true, - Tools: registry, Approvals: approvals, Memory: memorySvc, Skills: skillSvc, + Tools: computers.NativeTools(registry, catalog), Approvals: approvals, Memory: memorySvc, Skills: skillSvc, Workspace: func(ctx context.Context, botID int64) (string, error) { _, dir, err := catalog.Workspace(ctx, botID) if err == nil { diff --git a/internal/computers/catalog.go b/internal/computers/catalog.go index 78a2bb9..83a2068 100644 --- a/internal/computers/catalog.go +++ b/internal/computers/catalog.go @@ -10,6 +10,7 @@ import ( "unicode/utf16" "github.com/Personed/Persona/internal/agent" + "github.com/Personed/Persona/internal/approval" "github.com/Personed/Persona/internal/hosting" "github.com/Personed/Persona/internal/rpc" "github.com/Personed/Persona/internal/store" @@ -37,6 +38,15 @@ type Catalog struct { svcs *services vw *views + + // approver updates a pending takeover card when its owning viewer's + // control changes (catalog.ts's views callback); nil until wired. + approver *approval.Service +} + +// SetApprover wires the shared approval service for takeover card updates. +func (c *Catalog) SetApprover(approver *approval.Service) { + c.approver = approver } type startOp struct { diff --git a/internal/computers/handoff.go b/internal/computers/handoff.go index 7af3505..f049192 100644 --- a/internal/computers/handoff.go +++ b/internal/computers/handoff.go @@ -67,8 +67,12 @@ func (c *Catalog) Handoff(approver *approval.Service) takeover.Handoff { if request.Service == "browser" { title = "Browser" } + // A preview frame shows the live screen on the card, like views.ts + // capture; a computer that cannot produce one just skips it. + preview, _ := c.vw.capture(ctx, request.BotID, request.Service) answer, err := approver.Request(ctx, request.BotID, approval.Request{ ID: id, Title: title, Detail: request.Reason, Kind: approval.Permission, + Preview: preview, Takeover: &approval.Takeover{ ID: id, Service: request.Service, ComputerID: *binding.ComputerID, Revision: binding.Revision, State: "waiting", URL: url, @@ -161,6 +165,11 @@ func (c *Catalog) TakeRequest(ctx context.Context, botID int64, requestID, viewI // Concurrent requests from the owning viewer reuse the live grant. session.taking = true session.requestID = requestID + // The card flips to "controlling" while the viewer holds control, as + // catalog.ts commits it through the views callback. + if err := approver.SetTakeover(ctx, botID, requestID, true); err != nil { + return err + } return nil } diff --git a/internal/computers/nativetools.go b/internal/computers/nativetools.go new file mode 100644 index 0000000..ac7f452 --- /dev/null +++ b/internal/computers/nativetools.go @@ -0,0 +1,185 @@ +package computers + +import ( + "context" + "encoding/json" + "errors" + + "github.com/Personed/Persona/internal/rpc" + "github.com/Personed/Persona/internal/tools" + "github.com/Personed/Persona/internal/worker" +) + +// nativeServices are the computer services whose native tools Bots may call. +var nativeServices = []string{"browser", "desktop"} + +// exposedName names a native service tool as the TypeScript computer tools do: +// browser tools are prefixed, desktop tools keep their native names. +func exposedName(service, name string) string { + if service == "desktop" { + return name + } + return service + "_" + name +} + +// nativeTools exposes each enabled computer service's native catalog through +// the shared tools.Registry that serves Pi's MCP gateway, as the TypeScript +// computer.tools registry does. Calls run through the worker's journaled +// computer call path and non-observation calls wait on the shared approver. +type nativeTools struct { + base tools.Registry + c *Catalog +} + +// NativeTools wraps base so Pi sees both product tools and the Bot's enabled +// computer service tools. +func NativeTools(base tools.Registry, c *Catalog) tools.Registry { + return &nativeTools{base: base, c: c} +} + +func (r *nativeTools) Register(tool tools.Tool) error { return r.base.Register(tool) } + +// catalog lists a service's exposed tools; a Bot without the enabled service +// gets none. +func (r *nativeTools) catalog(ctx context.Context, botID int64, service string) ([]tools.Definition, error) { + w, dir, err := r.c.svcs.workerFor(ctx, botID, service) + if err != nil { + var rpcErr *rpc.Error + if errors.As(err, &rpcErr) { + return nil, nil + } + return nil, err + } + native, err := w.ComputerCatalog(ctx, dir, service) + if err != nil { + return nil, err + } + definitions := make([]tools.Definition, 0, len(native)) + for _, tool := range native { + if tool == nil || (service == "browser" && tool.Name == "agent_browser_wait_ms") { + continue + } + definition := tools.Definition{ + Name: exposedName(service, tool.Name), + Description: tool.Description, + Mutates: !worker.Observation(service, tool.Name), + // Computer calls respect the binding's "auto" approval mode. + Automatic: true, + } + if tool.InputSchema != nil { + if schema, err := json.Marshal(tool.InputSchema); err == nil { + definition.InputSchema = schema + } + } + if tool.OutputSchema != nil { + if schema, err := json.Marshal(tool.OutputSchema); err == nil { + definition.OutputSchema = schema + } + } + if tool.Annotations != nil { + if annotations, err := json.Marshal(tool.Annotations); err == nil { + _ = json.Unmarshal(annotations, &definition.Annotations) + } + } + definitions = append(definitions, definition) + } + return definitions, nil +} + +func (r *nativeTools) List(ctx context.Context, botID int64) ([]tools.Definition, error) { + definitions, err := r.base.List(ctx, botID) + if err != nil { + return nil, err + } + for _, service := range nativeServices { + native, err := r.catalog(ctx, botID, service) + if err != nil { + return nil, err + } + definitions = append(definitions, native...) + } + return definitions, nil +} + +func (r *nativeTools) Call(ctx context.Context, call tools.Call, approve tools.Approver) (tools.Result, error) { + for _, service := range nativeServices { + native, err := r.catalog(ctx, call.BotID, service) + if err != nil { + return tools.Result{}, err + } + for _, definition := range native { + if definition.Name != call.Name { + continue + } + return r.callService(ctx, service, call, definition, approve) + } + } + return r.base.Call(ctx, call, approve) +} + +func (r *nativeTools) callService(ctx context.Context, service string, call tools.Call, definition tools.Definition, approve tools.Approver) (tools.Result, error) { + if definition.Mutates { + if approve == nil { + return tools.Result{}, tools.ErrDenied + } + allowed, err := approve(ctx, call, definition) + if err != nil { + return tools.Result{}, err + } + if !allowed { + return tools.Result{}, tools.ErrDenied + } + } + w, dir, err := r.c.svcs.workerFor(ctx, call.BotID, service) + if err != nil { + return tools.Result{}, err + } + name := definition.Name + if service != "desktop" { + name = name[len(service)+1:] + } + result, err := w.ComputerRequest(ctx, worker.ComputerInput{ + Action: "call", Service: service, Dir: dir, + TaskID: call.TaskID, CallID: call.CallID, + Name: name, Arguments: call.Input, + }) + if err != nil { + return tools.Result{}, err + } + var raw struct { + Content []struct { + Type string `json:"type"` + Text string `json:"text"` + MimeType string `json:"mimeType"` + Data string `json:"data"` + Resource *struct { + URI string `json:"uri"` + MimeType string `json:"mimeType"` + Text string `json:"text"` + Data string `json:"blob"` + } `json:"resource"` + } `json:"content"` + Structured json.RawMessage `json:"structuredContent"` + IsError bool `json:"isError"` + } + if len(result.Result) > 0 { + if err := json.Unmarshal(result.Result, &raw); err != nil { + return tools.Result{}, err + } + } + out := tools.Result{Structured: raw.Structured, IsError: raw.IsError} + for _, content := range raw.Content { + block := tools.Content{ + Type: content.Type, Text: content.Text, + MimeType: content.MimeType, Data: content.Data, + } + if content.Resource != nil { + block.URI = content.Resource.URI + block.MimeType = content.Resource.MimeType + block.Text = content.Resource.Text + block.Data = content.Resource.Data + } + out.Content = append(out.Content, block) + } + return out, nil +} diff --git a/internal/computers/views.go b/internal/computers/views.go index 9c4b218..5687c17 100644 --- a/internal/computers/views.go +++ b/internal/computers/views.go @@ -242,6 +242,11 @@ func (v *views) action(ctx context.Context, id string, message json.RawMessage) v.s.release(session.service, session.botID, session.lease) session.lease = 0 session.controller = false + // The takeover card falls back to waiting while its viewer no + // longer holds control (catalog.ts's control-change commit). + if session.requestID != "" && v.s.c.approver != nil { + _ = v.s.c.approver.SetTakeover(ctx, session.botID, session.requestID, false) + } return nil } w, dir, err := v.s.workerFor(ctx, session.botID, session.service) @@ -273,6 +278,34 @@ func (v *views) action(ctx context.Context, id string, message json.RawMessage) return err } +// capture takes one screen image for the takeover card preview: it opens a +// short-lived viewer, reads one frame and closes it (views.ts capture). +func (v *views) capture(ctx context.Context, botID int64, service string) (json.RawMessage, error) { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + session, err := v.open(ctx, botID, service, "") + if err != nil { + return nil, err + } + defer v.close(context.Background(), session.id) + batch, err := v.next(ctx, session.id) + if err != nil { + return nil, err + } + for _, message := range batch.Messages { + var frame struct { + Data json.RawMessage `json:"data"` + MimeType string `json:"mimeType"` + } + if err := json.Unmarshal(message, &frame); err == nil && len(frame.Data) > 0 { + return json.Marshal(map[string]any{ + "type": "image", "data": frame.Data, "mimeType": frame.MimeType, + }) + } + } + return nil, errUnavailable("没有可用画面。") +} + // close ends the viewer: releases its lease reservation and closes the // worker's session. Closing a viewer does not complete a takeover request. func (v *views) close(ctx context.Context, id string) { @@ -293,7 +326,13 @@ func (v *views) close(ctx context.Context, id string) { v.s.release(session.service, session.botID, session.lease) session.lease = 0 } + session.controller = false + requestID := session.requestID session.mu.Unlock() + // A viewer closing mid-takeover hands control back first. + if requestID != "" && v.s.c.approver != nil { + _ = v.s.c.approver.SetTakeover(ctx, session.botID, requestID, false) + } v.remove(session) close(session.done) if w, dir, err := v.s.workerFor(ctx, session.botID, session.service); err == nil { diff --git a/internal/server/computer.go b/internal/server/computer.go index 66cd6da..6cae12c 100644 --- a/internal/server/computer.go +++ b/internal/server/computer.go @@ -213,6 +213,7 @@ func RegisterComputer(s *rpc.Server, c *computers.Catalog) { // finishing the live request before resolving it, as runtime.ts // execution.answer does. func RegisterComputerTakeover(s *rpc.Server, c *computers.Catalog, approvals *approval.Service) { + c.SetApprover(approvals) s.Handle("engines.takeRequest", func(ctx context.Context, input json.RawMessage) (any, error) { var in struct { BotID int64 `json:"botId"` diff --git a/internal/tools/tools.go b/internal/tools/tools.go index 615bf98..6711ed2 100644 --- a/internal/tools/tools.go +++ b/internal/tools/tools.go @@ -20,6 +20,9 @@ type Definition struct { Annotations map[string]any `json:"annotations,omitempty"` // Mutates routes the call through the shared approval callback. Mutates bool `json:"-"` + // Automatic lets the Bot's "auto" approval mode allow a mutating call + // without asking, like the TypeScript computer approval callback. + Automatic bool `json:"-"` } // Content is one block of a tool result: "text", "image" or "resource". diff --git a/internal/worker/computer.go b/internal/worker/computer.go index 36bbca1..6975b55 100644 --- a/internal/worker/computer.go +++ b/internal/worker/computer.go @@ -89,6 +89,10 @@ func observation(service, name string) bool { return strings.HasPrefix(name, "get_") || strings.HasPrefix(name, "list_") || name == "screenshot" || name == "zoom" } +// Observation reports whether a native service tool only observes; every other +// call routes through the shared approver, as computer.tools.invoke does. +func Observation(service, name string) bool { return observation(service, name) } + var errComputerUncertain = &Error{Code: "COMPUTER_UNCERTAIN", Message: "A computer action's outcome is unknown. Observe the computer, confirm the task state, then verify before more actions. Do not replay the action."} var errBrowserUncertain = &Error{Code: "COMPUTER_UNCERTAIN", Message: "A browser action's outcome is unknown. Observe the page, then use agent_browser_restart before more browser actions. Restart closes this Bot's tabs and unsaved input. Do not replay the action."} @@ -696,6 +700,17 @@ func driverConfig(input ComputerInput) (*MCPConfig, error) { if input.Service == "browser" { config.Command = "agent-browser" } + // PERSONA_COMPUTER_DRIVER_ holds a JSON MCPConfig replacing the + // default driver, which test fixtures use to serve a scripted service. + if input.Driver == nil { + if override := os.Getenv("PERSONA_COMPUTER_DRIVER_" + strings.ToUpper(input.Service)); override != "" { + var parsed MCPConfig + if err := json.Unmarshal([]byte(override), &parsed); err != nil { + return nil, fmt.Errorf("worker: PERSONA_COMPUTER_DRIVER_%s: %w", strings.ToUpper(input.Service), err) + } + input.Driver = &parsed + } + } if input.Driver != nil { config = *input.Driver } From e0c696f910e98536b6a3fbce4ec70bf660adb69f Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Tue, 24 Nov 2026 17:08:33 +0000 Subject: [PATCH 2/3] Serve browser composites, gate calls on the viewer lease, and restart on an ephemeral port - nativetools declares browser_agent_browser_observe/run_steps/restart (the composites browser-service.mjs layers on the raw daemon catalog) and answers them through the journaled ops; the fixture driver is removed. - callService rejects calls while a viewer holds the control lease and degrades List when a service catalog cannot load, matching services.ts. - Product calls append to PERSONA_BROWSER_METRICS_FILE at the service layer, keeping service-internal calls (get_url, view input) out of the metrics. - go-server binds serve to an ephemeral port so the proxy can hold the requested port across restarts; open-takeover-page spawns agent-browser directly. Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- apps/api/test/fixtures/browser-driver.mjs | 168 ------------- apps/api/test/fixtures/go-server.ts | 17 +- internal/computers/nativetools.go | 294 +++++++++++++++++++--- internal/computers/services.go | 15 ++ 4 files changed, 283 insertions(+), 211 deletions(-) delete mode 100755 apps/api/test/fixtures/browser-driver.mjs diff --git a/apps/api/test/fixtures/browser-driver.mjs b/apps/api/test/fixtures/browser-driver.mjs deleted file mode 100755 index 11a3f79..0000000 --- a/apps/api/test/fixtures/browser-driver.mjs +++ /dev/null @@ -1,168 +0,0 @@ -#!/usr/bin/env node -// A browser service driver for the Go fixture. With no arguments it proxies -// MCP stdio to the real agent-browser while recording each tools/call's -// exposed name and elapsed time into the metrics file named by -// PERSONA_BROWSER_METRICS_FILE, as web-server.ts's computer.tools.invoke -// wrapper did. With arguments it is the same program browserCLI drives -// directly (stream status, set viewport, install): it forwards them to -// agent-browser untouched. -// -// It also carries browser-service.mjs's composite agent_browser_observe: -// agent-browser ships no such tool, so the driver answers it itself from an -// agent_browser_eval of the shared page script, formatted as "Page facts". -import { spawn } from "node:child_process"; -import { writeFileSync } from "node:fs"; -import { createInterface } from "node:readline"; - -const cliArgs = process.argv.slice(2); -if (cliArgs.length > 0) { - const cli = spawn("agent-browser", cliArgs, { - stdio: "inherit", - env: process.env, - }); - cli.on("exit", (code, signal) => { - if (signal) process.kill(process.pid, signal); - else process.exit(code ?? 0); - }); -} else { - // browserObserve + browserPageScript from browser-tools.mjs. - const observeTool = { - name: "agent_browser_observe", - description: - "Read current URL, title, document readiness, visible text and a compact page snapshot. Use after takeover or when a screenshot is unclear. Blank text or a ready document does not prove why a page is blank or that the task succeeded.", - inputSchema: { - type: "object", - properties: {}, - additionalProperties: false, - }, - }; - const pageScript = `(() => ({ - url: location.href, title: document.title, readyState: document.readyState, - httpStatus: performance.getEntriesByType('navigation')[0]?.responseStatus || null, - passwordFieldPresent: !!document.querySelector('input[type=password]'), - challengePresent: !!document.querySelector('iframe[src*="challenges.cloudflare.com"],iframe[src*="recaptcha"],iframe[src*="hcaptcha"],#challenge-running'), - text: (document.body?.innerText || '').slice(0, 12000), - controls: Array.from(document.querySelectorAll('input:not([type=password]),textarea,select')).slice(0, 80).map(el => ({value: el.value.slice(0, 2000), checked: el.checked})) -}))()`; - - const metrics = process.env.PERSONA_BROWSER_METRICS_FILE; - const calls = []; - const pending = new Map(); - const observing = new Map(); - // The TypeScript fixture counts computer.tools.invoke calls only. The - // Go handoff's agent_browser_get_url is a service-internal call (runtime.ts - // makes it the same way, outside the invoke path), so it is not a tool - // invocation and does not belong in the metrics. - const internal = new Set(["agent_browser_get_url"]); - const record = () => { - if (metrics) writeFileSync(metrics, JSON.stringify(calls)); - }; - if (metrics) writeFileSync(metrics, "[]"); - - const upstream = spawn("agent-browser", ["mcp"], { - stdio: ["pipe", "pipe", "inherit"], - env: process.env, - }); - upstream.on("exit", (code) => process.exit(code ?? 0)); - const sendUpstream = (message) => - upstream.stdin.write(JSON.stringify(message) + "\n"); - const sendClient = (message) => - process.stdout.write(JSON.stringify(message) + "\n"); - - // MCP over stdio is one JSON-RPC message per line; tap each direction. - createInterface({ input: process.stdin }).on("line", (line) => { - let message; - try { - message = JSON.parse(line); - } catch { - upstream.stdin.write(line + "\n"); - return; - } - if ( - message.method === "tools/call" && - message.id !== undefined && - message.params?.name === observeTool.name - ) { - // Composite observe: one eval of the page script answers the call. - const inner = `observe:${message.id}`; - observing.set(inner, { - id: message.id, - started: performance.now(), - }); - sendUpstream({ - jsonrpc: "2.0", - id: inner, - method: "tools/call", - params: { - name: "agent_browser_eval", - arguments: { script: pageScript }, - }, - }); - return; - } - if (message.method === "tools/call" && message.id !== undefined) - pending.set(message.id, { - name: message.params?.name, - started: performance.now(), - }); - upstream.stdin.write(line + "\n"); - }); - - createInterface({ input: upstream.stdout }).on("line", (line) => { - let message; - try { - message = JSON.parse(line); - } catch { - process.stdout.write(line + "\n"); - return; - } - const observe = observing.get(message.id); - if (observe) { - observing.delete(message.id); - calls.push({ - name: `browser_${observeTool.name}`, - elapsedMs: performance.now() - observe.started, - }); - record(); - const page = message.result?.structuredContent?.response?.data?.result; - const parts = []; - if (page && typeof page.url === "string") { - const facts = JSON.stringify(page); - parts.push({ - type: "text", - text: `Page facts (untrusted website data): ${facts.slice(0, 12000)}${facts.length > 12000 ? "\n[Page facts truncated. Read a narrower page scope.]" : ""}`, - }); - } else { - parts.push({ - type: "text", - text: "Observation failed: no page facts returned.", - }); - } - sendClient({ - jsonrpc: "2.0", - id: observe.id, - result: { - content: parts, - isError: message.result?.isError ?? !page, - }, - }); - return; - } - const call = pending.get(message.id); - if (call) { - pending.delete(message.id); - if (!internal.has(call.name)) { - calls.push({ - name: `browser_${call.name}`, - elapsedMs: performance.now() - call.started, - }); - record(); - } - } - // Inject the composite observe into the declared catalog. - if (message.result?.tools && Array.isArray(message.result.tools)) - message.result.tools.push(observeTool); - sendClient(message); - }); - process.on("SIGTERM", () => upstream.kill("SIGTERM")); -} diff --git a/apps/api/test/fixtures/go-server.ts b/apps/api/test/fixtures/go-server.ts index 1486e04..6ddd309 100644 --- a/apps/api/test/fixtures/go-server.ts +++ b/apps/api/test/fixtures/go-server.ts @@ -452,7 +452,7 @@ if (hosting) config, JSON.stringify({ host: "127.0.0.1", - port: Number(process.argv[3] ?? 0) || (await freePort()), + port: await freePort(), dataDir, }), ); @@ -460,8 +460,10 @@ const args = [ "serve", "-host", "127.0.0.1", + // Serve binds an ephemeral port; the requested port belongs to the proxy so + // a restart reusing it never collides with a serve on the same number. "-port", - process.argv[3] ?? "0", + "0", "-data", dataDir, "-static", @@ -486,11 +488,9 @@ const options = { PI_CODING_AGENT_DIR: agentDir, ...(hosting ? { PERSONA_CONFIG: config } : {}), PERSONA_FAUX_NO_MESSAGE: noMessage, - PERSONA_COMPUTER_DRIVER_BROWSER: JSON.stringify({ - transport: "stdio", - command: fileURLToPath(new URL("./browser-driver.mjs", import.meta.url)), - env: { PERSONA_BROWSER_METRICS_FILE: metricsFile }, - }), + // The Go service records each product computer call here, as the + // TypeScript computer.tools.invoke tap did in the fixture driver. + PERSONA_BROWSER_METRICS_FILE: metricsFile, PATH: `${bin}${process.platform === "win32" ? ";" : ":"}${process.env.PATH}`, }, stdio: ["pipe", "pipe", "pipe"], @@ -738,9 +738,8 @@ process.on("message", async (message) => { const open = async () => { const code = await new Promise((resolve) => { const child = spawn( - process.execPath, + "agent-browser", [ - fileURLToPath(new URL("./browser-driver.mjs", import.meta.url)), "open", `http://127.0.0.1:${fixturePort}/takeover-fixture`, "--json", diff --git a/internal/computers/nativetools.go b/internal/computers/nativetools.go index ac7f452..028090d 100644 --- a/internal/computers/nativetools.go +++ b/internal/computers/nativetools.go @@ -4,6 +4,9 @@ import ( "context" "encoding/json" "errors" + "fmt" + "os" + "time" "github.com/Personed/Persona/internal/rpc" "github.com/Personed/Persona/internal/tools" @@ -22,6 +25,46 @@ func exposedName(service, name string) string { return service + "_" + name } +// browserPageScript is the shared page probe of browser-service.mjs's observe +// composite, evaluated through agent_browser_eval. +const browserPageScript = `(() => ({ + url: location.href, title: document.title, readyState: document.readyState, + httpStatus: performance.getEntriesByType('navigation')[0]?.responseStatus || null, + passwordFieldPresent: !!document.querySelector('input[type=password]'), + challengePresent: !!document.querySelector('iframe[src*="challenges.cloudflare.com"],iframe[src*="recaptcha"],iframe[src*="hcaptcha"],#challenge-running'), + text: (document.body?.innerText || '').slice(0, 12000), + controls: Array.from(document.querySelectorAll('input:not([type=password]),textarea,select')).slice(0, 80).map(el => ({value: el.value.slice(0, 2000), checked: el.checked})) +}))()` + +// browserComposites are the service tools browser-service.mjs adds on top of +// the raw agent-browser catalog: composite observation, step batching and +// restart. They are declared with the service's exposed names. +var browserComposites = []struct { + name string + description string + mutates bool + schema string +}{ + { + name: "browser_agent_browser_observe", + mutates: false, + description: "Read current URL, title, document readiness, visible text and a compact page snapshot. Use after takeover or when a screenshot is unclear. Blank text or a ready document does not prove why a page is blank or that the task succeeded.", + schema: `{"type":"object","properties":{},"additionalProperties":false}`, + }, + { + name: "browser_agent_browser_run_steps", + mutates: true, + description: "Run a batch of known browser actions in order. Stops at the first failed or uncertain step and reports which steps completed.", + schema: `{"type":"object","properties":{"steps":{"type":"array","items":{"type":"object","properties":{"action":{"type":"string"}},"required":["action"],"additionalProperties":true}}},"required":["steps"],"additionalProperties":false}`, + }, + { + name: "browser_agent_browser_restart", + mutates: true, + description: "Restart the Bot browser and clear an unknown browser outcome. Closes this Bot's tabs and unsaved page input.", + schema: `{"type":"object","properties":{},"additionalProperties":false}`, + }, +} + // nativeTools exposes each enabled computer service's native catalog through // the shared tools.Registry that serves Pi's MCP gateway, as the TypeScript // computer.tools registry does. Calls run through the worker's journaled @@ -40,7 +83,8 @@ func NativeTools(base tools.Registry, c *Catalog) tools.Registry { func (r *nativeTools) Register(tool tools.Tool) error { return r.base.Register(tool) } // catalog lists a service's exposed tools; a Bot without the enabled service -// gets none. +// gets none. The browser catalog gains the service composites +// browser-service.mjs layers on the raw agent-browser tools. func (r *nativeTools) catalog(ctx context.Context, botID int64, service string) ([]tools.Definition, error) { w, dir, err := r.c.svcs.workerFor(ctx, botID, service) if err != nil { @@ -54,36 +98,51 @@ func (r *nativeTools) catalog(ctx context.Context, botID int64, service string) if err != nil { return nil, err } - definitions := make([]tools.Definition, 0, len(native)) + seen := make(map[string]bool, len(native)) + definitions := make([]tools.Definition, 0, len(native)+len(browserComposites)) for _, tool := range native { if tool == nil || (service == "browser" && tool.Name == "agent_browser_wait_ms") { continue } - definition := tools.Definition{ - Name: exposedName(service, tool.Name), - Description: tool.Description, - Mutates: !worker.Observation(service, tool.Name), - // Computer calls respect the binding's "auto" approval mode. - Automatic: true, - } - if tool.InputSchema != nil { - if schema, err := json.Marshal(tool.InputSchema); err == nil { - definition.InputSchema = schema + seen[tool.Name] = true + definitions = append(definitions, r.definition(service, tool.Name, tool.Description, !worker.Observation(service, tool.Name), tool.InputSchema, tool.OutputSchema, tool.Annotations)) + } + if service == "browser" { + for _, composite := range browserComposites { + name := composite.name[len("browser_"):] + if seen[name] { + continue } + definitions = append(definitions, r.definition(service, name, composite.description, composite.mutates, json.RawMessage(composite.schema), nil, nil)) } - if tool.OutputSchema != nil { - if schema, err := json.Marshal(tool.OutputSchema); err == nil { - definition.OutputSchema = schema - } + } + return definitions, nil +} + +func (r *nativeTools) definition(service, name, description string, mutates bool, input, output, annotations any) tools.Definition { + definition := tools.Definition{ + Name: exposedName(service, name), + Description: description, + Mutates: mutates, + // Computer calls respect the binding's "auto" approval mode. + Automatic: true, + } + if input != nil { + if schema, err := json.Marshal(input); err == nil { + definition.InputSchema = schema } - if tool.Annotations != nil { - if annotations, err := json.Marshal(tool.Annotations); err == nil { - _ = json.Unmarshal(annotations, &definition.Annotations) - } + } + if output != nil { + if schema, err := json.Marshal(output); err == nil { + definition.OutputSchema = schema } - definitions = append(definitions, definition) } - return definitions, nil + if annotations != nil { + if data, err := json.Marshal(annotations); err == nil { + _ = json.Unmarshal(data, &definition.Annotations) + } + } + return definition } func (r *nativeTools) List(ctx context.Context, botID int64) ([]tools.Definition, error) { @@ -92,9 +151,12 @@ func (r *nativeTools) List(ctx context.Context, botID int64) ([]tools.Definition return nil, err } for _, service := range nativeServices { + // A service whose driver cannot start (for example an enabled browser + // with no agent installed) drops out of the catalog; it must not + // sink the whole tool list and every chat turn with it. native, err := r.catalog(ctx, botID, service) if err != nil { - return nil, err + continue } definitions = append(definitions, native...) } @@ -118,6 +180,11 @@ func (r *nativeTools) Call(ctx context.Context, call tools.Call, approve tools.A } func (r *nativeTools) callService(ctx context.Context, service string, call tools.Call, definition tools.Definition, approve tools.Approver) (tools.Result, error) { + // A viewer holding the control lease blocks Bot calls until it hands + // control back, as services.ts run() rejects while control.lease is set. + if r.c.svcs.viewerLease(service, call.BotID) != 0 { + return tools.Result{}, rpc.NewError("CONFLICT", "用户正在接管。交还后请重新观察画面。") + } if definition.Mutates { if approve == nil { return tools.Result{}, tools.ErrDenied @@ -130,23 +197,182 @@ func (r *nativeTools) callService(ctx context.Context, service string, call tool return tools.Result{}, tools.ErrDenied } } + started := time.Now() + result, err := r.dispatch(ctx, service, call) + if err == nil { + recordMetric(call.Name, float64(time.Since(started).Milliseconds())) + } + return result, err +} + +// dispatch routes a native call: the service composites run against the +// journaled computer ops, every other tool forwards to the driver unchanged. +func (r *nativeTools) dispatch(ctx context.Context, service string, call tools.Call) (tools.Result, error) { + if service == "browser" { + switch call.Name { + case "browser_agent_browser_restart": + return r.restartBrowser(ctx, call) + case "browser_agent_browser_observe": + return r.observeBrowser(ctx, call) + case "browser_agent_browser_run_steps": + return r.runBrowserSteps(ctx, call) + } + } + return r.journaled(ctx, service, call, call.Name[len(service)+1:], call.Input, call.CallID) +} + +// journaled sends one native tool call through the worker's journaled call op. +func (r *nativeTools) journaled(ctx context.Context, service string, call tools.Call, name string, args any, callID string) (tools.Result, error) { w, dir, err := r.c.svcs.workerFor(ctx, call.BotID, service) if err != nil { return tools.Result{}, err } - name := definition.Name - if service != "desktop" { - name = name[len(service)+1:] - } + arguments, _ := json.Marshal(args) result, err := w.ComputerRequest(ctx, worker.ComputerInput{ Action: "call", Service: service, Dir: dir, - TaskID: call.TaskID, CallID: call.CallID, - Name: name, Arguments: call.Input, + TaskID: call.TaskID, CallID: callID, + Name: name, Arguments: arguments, }) if err != nil { return tools.Result{}, err } - var raw struct { + return convertResult(result.Result) +} + +func (r *nativeTools) restartBrowser(ctx context.Context, call tools.Call) (tools.Result, error) { + w, dir, err := r.c.svcs.workerFor(ctx, call.BotID, "browser") + if err != nil { + return tools.Result{}, err + } + if _, err := w.ComputerRequest(ctx, worker.ComputerInput{ + Action: "restart", Service: "browser", Dir: dir, TaskID: call.TaskID, + }); err != nil { + return tools.Result{}, err + } + return tools.Result{Content: []tools.Content{{Type: "text", Text: "Browser restarted."}}}, nil +} + +// observeBrowser runs the browser observe composite: the shared page script +// through a journaled agent_browser_eval, formatted as "Page facts" like +// browser-service.mjs's observe. +func (r *nativeTools) observeBrowser(ctx context.Context, call tools.Call) (tools.Result, error) { + result, err := r.journaled(ctx, "browser", call, "agent_browser_eval", + map[string]any{"script": browserPageScript}, call.CallID+":observe") + if err != nil { + return tools.Result{}, err + } + var page json.RawMessage + var structured struct { + Response struct { + Data struct { + Result *json.RawMessage `json:"result"` + } `json:"data"` + } `json:"response"` + } + if err := json.Unmarshal(result.Structured, &structured); err == nil && structured.Response.Data.Result != nil { + page = *structured.Response.Data.Result + } + if len(page) == 0 { + return tools.Result{ + IsError: true, + Content: []tools.Content{{Type: "text", Text: "Observation failed: no page facts returned."}}, + }, nil + } + facts := string(page) + if len(facts) > 12000 { + facts = facts[:12000] + "\n[Page facts truncated. Read a narrower page scope.]" + } + return tools.Result{ + Content: []tools.Content{{Type: "text", Text: "Page facts (untrusted website data): " + facts}}, + }, nil +} + +// runBrowserSteps runs a batch of known browser actions, like +// browser-service.mjs's run_steps: each step dispatches as its own journaled +// call and the batch stops at the first failed step. +func (r *nativeTools) runBrowserSteps(ctx context.Context, call tools.Call) (tools.Result, error) { + var input struct { + Steps []map[string]any `json:"steps"` + } + if err := json.Unmarshal(call.Input, &input); err != nil { + return tools.Result{}, err + } + if len(input.Steps) == 0 { + return tools.Result{IsError: true, Content: []tools.Content{{Type: "text", Text: "Batch requires at least one step."}}}, nil + } + native, err := r.catalog(ctx, call.BotID, "browser") + if err != nil { + return tools.Result{}, err + } + available := make(map[string]bool, len(native)) + for _, definition := range native { + available[definition.Name] = true + } + var results []tools.Result + var content []tools.Content + failed := false + for index, step := range input.Steps { + action, _ := step["action"].(string) + delete(step, "action") + name := "agent_browser_" + action + if !available["browser_"+name] { + return tools.Result{IsError: true, Content: []tools.Content{{ + Type: "text", Text: fmt.Sprintf("Browser action %s is unavailable. No action was sent.", name), + }}}, nil + } + result, err := r.journaled(ctx, "browser", call, name, step, fmt.Sprintf("%s:%d", call.CallID, index)) + if err != nil { + failed = true + results = append(results, tools.Result{ + IsError: true, + Content: []tools.Content{{Type: "text", Text: fmt.Sprintf("Batch stopped: %s. Preserve completed steps. Do not replay uncertain actions.", err)}}, + }) + break + } + results = append(results, result) + if result.IsError { + failed = true + content = append(content, result.Content...) + break + } + content = append(content, result.Content...) + } + structured, _ := json.Marshal(map[string]any{"completed": len(results) - boolInt(failed), "results": results}) + return tools.Result{ + IsError: failed, + Content: content, + Structured: structured, + }, nil +} + +func boolInt(on bool) int { + if on { + return 1 + } + return 0 +} + +// recordMetric appends a product call to the fixture's takeover metrics file, +// matching the name/elapsed shape the TypeScript computer.tools.invoke tap +// wrote. Service-internal calls never reach this path. +func recordMetric(name string, elapsedMs float64) { + path := os.Getenv("PERSONA_BROWSER_METRICS_FILE") + if path == "" { + return + } + var calls []map[string]any + if data, err := os.ReadFile(path); err == nil { + _ = json.Unmarshal(data, &calls) + } + calls = append(calls, map[string]any{"name": name, "elapsedMs": elapsedMs}) + if data, err := json.Marshal(calls); err == nil { + _ = os.WriteFile(path, data, 0o600) + } +} + +// convertResult maps the worker's call result into a tools.Result. +func convertResult(raw json.RawMessage) (tools.Result, error) { + var result struct { Content []struct { Type string `json:"type"` Text string `json:"text"` @@ -162,13 +388,13 @@ func (r *nativeTools) callService(ctx context.Context, service string, call tool Structured json.RawMessage `json:"structuredContent"` IsError bool `json:"isError"` } - if len(result.Result) > 0 { - if err := json.Unmarshal(result.Result, &raw); err != nil { + if len(raw) > 0 { + if err := json.Unmarshal(raw, &result); err != nil { return tools.Result{}, err } } - out := tools.Result{Structured: raw.Structured, IsError: raw.IsError} - for _, content := range raw.Content { + out := tools.Result{Structured: result.Structured, IsError: result.IsError} + for _, content := range result.Content { block := tools.Content{ Type: content.Type, Text: content.Text, MimeType: content.MimeType, Data: content.Data, diff --git a/internal/computers/services.go b/internal/computers/services.go index 2ef9b14..48ef6bd 100644 --- a/internal/computers/services.go +++ b/internal/computers/services.go @@ -200,6 +200,21 @@ func (s *services) close() { } } +// viewerLease reports the outstanding viewer lease on the service's lane, as +// services.ts control.lease: Bot calls are rejected while a viewer holds it. +func (s *services) viewerLease(service string, botID int64) int64 { + s.mu.Lock() + defer s.mu.Unlock() + key := "desktop" + if service == "browser" && s.isolated[botID] { + key = fmt.Sprintf("browser:%d", botID) + } + if ctl := s.controls[key]; ctl != nil { + return ctl.lease + } + return 0 +} + // nextLease issues a viewer lease ID (services.ts takeover's lease argument). func (s *services) nextLease() int64 { s.mu.Lock() From 6f4c0bc4049f164896b4fc11a4398141c17de3c8 Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Tue, 24 Nov 2026 17:14:51 +0000 Subject: [PATCH 3/3] Keep desktop tool names unprefixed on dispatch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit dispatch stripped a browser_-style prefix from every service name, but desktop tools are declared under their native names — the strip corrupted the action name and could panic on names shorter than the prefix. Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- internal/computers/nativetools.go | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/internal/computers/nativetools.go b/internal/computers/nativetools.go index 028090d..2c2fb0a 100644 --- a/internal/computers/nativetools.go +++ b/internal/computers/nativetools.go @@ -218,7 +218,13 @@ func (r *nativeTools) dispatch(ctx context.Context, service string, call tools.C return r.runBrowserSteps(ctx, call) } } - return r.journaled(ctx, service, call, call.Name[len(service)+1:], call.Input, call.CallID) + // Only browser names carry the service prefix; desktop tools keep their + // native names, so stripping a prefix there would corrupt the call. + name := call.Name + if service != "desktop" { + name = call.Name[len(service)+1:] + } + return r.journaled(ctx, service, call, name, call.Input, call.CallID) } // journaled sends one native tool call through the worker's journaled call op. @@ -308,6 +314,16 @@ func (r *nativeTools) runBrowserSteps(ctx context.Context, call tools.Call) (too for _, definition := range native { available[definition.Name] = true } + // Validate every step's action before sending anything, so a malformed + // batch never leaves delivered steps concealed behind a "no action" error. + for _, step := range input.Steps { + action, _ := step["action"].(string) + if !available["browser_agent_browser_"+action] { + return tools.Result{IsError: true, Content: []tools.Content{{ + Type: "text", Text: fmt.Sprintf("Browser action agent_browser_%s is unavailable. No action was sent.", action), + }}}, nil + } + } var results []tools.Result var content []tools.Content failed := false @@ -315,11 +331,6 @@ func (r *nativeTools) runBrowserSteps(ctx context.Context, call tools.Call) (too action, _ := step["action"].(string) delete(step, "action") name := "agent_browser_" + action - if !available["browser_"+name] { - return tools.Result{IsError: true, Content: []tools.Content{{ - Type: "text", Text: fmt.Sprintf("Browser action %s is unavailable. No action was sent.", name), - }}}, nil - } result, err := r.journaled(ctx, "browser", call, name, step, fmt.Sprintf("%s:%d", call.CallID, index)) if err != nil { failed = true