Computer use for the Pi coding agent — Windows apps, browsers and desktops through native UI trees, screenshots and real input.
TypeScript accessibilityagent-toolsai-agentbrowser-automationcomputer-usecuadesktop-automationelectronpipi-coding-agentpi-extensionpi-packageplaywrighttypescriptui-automationvisionwebview2windowswindows-automationwsl
feat: typed computer_files, computer_clipboard and computer_record (LPT-934 step 3)
alexshpunt-clanker[bot]cc8c69f1809a
diff --git a/docs/computer-resources.md b/docs/computer-resources.mdindex e27cdce..8fbc92c 100644--- a/docs/computer-resources.md+++ b/docs/computer-resources.md@@ -11,7 +11,7 @@ The current desktop scope is Windows, with Pi running on it directly or in its W## Typed tools-Some operations have their own tool with typed fields, in both modes. They are deferred like the tools above: `tool_search` loads the best matches of a query, such as `computer open window` or `computer wait browser`. Their receipts match Insert receipts.+Some operations have their own tool with typed fields, in both modes. They are deferred like the tools above. `tool_search` loads at most 8 best matches per query, so search one group at a time: `computer open window`, `computer wait browser`, `computer files clipboard record`. Their receipts match Insert receipts.| Tool | Does | Replaces || --- | --- | --- |@@ -20,6 +20,9 @@ Some operations have their own tool with typed fields, in both modes. They are d| `computer_display` | Changes a display's resolution | Insert `resize` into a display || `computer_wait` | Waits until a window's UI or a browser page meets [conditions](#verify-and-wait), or checks them once (`mode: "check"`) | Insert `wait_for` and `verify` into a window || `computer_browser` | Navigates, manages tabs, answers dialogs, uploads, waits for or cancels downloads, and runs page JavaScript in a browser window by its address | Insert of those [page actions](#browser-pages) into a DOM observation |+| `computer_files` | Copies a workspace file into the session's folder on a machine (`put`), copies one out (`get`), or lists the folder (`list`) | Insert `put`, `get`, `files` into a machine |+| `computer_clipboard` | Reads (`include_image` adds the image) or replaces a machine's clipboard with text or an image, in YOLO | Insert `clipboard_read`, `clipboard_write` |+| `computer_record` | Records the main display to video (`video_start`, `video_stop`) or playback audio (`audio`) on a machine in YOLO; captures frames of a window or display (`sequence`) and returns a sequence address for Read with a `frames:` view | Insert `record_start`, `record_stop`, `audio_record`; Read `sequence:` || Delete (`computer_delete` without IDE) | Closes a window like its close button, or releases a sandbox, isolated session, machine or `computer:session` | Insert `close` and `kill` |Delete of a window asks it to close: a browser the session opened closes with its disposable profile, an attached browser is detached first, and any other window gets the standard close request. The receipt says whether the window closed; an app that asks about unsaved work keeps it open, so Read it next. Add `?force=true` to the window address to kill the hung app of a window this session opened. Safe mode closes only windows the session opened.diff --git a/src/computer-tools.ts b/src/computer-tools.tsindex 74117e8..cbae9fa 100644--- a/src/computer-tools.ts+++ b/src/computer-tools.ts@@ -4,6 +4,7 @@ import { Text } from "@earendil-works/pi-tui";import { ComputerRequestError, type ComputerResources } from "./computer-resources.ts";import type { ComputerAddress } from "./computer-address.ts";import { computerActionRenderer } from "./computer-action-renderer.ts";+import { parseComputerViews } from "./computer-views.ts";import { COMPUTER_DELETE_HELP, computerAction, deleteComputer } from "./provider.ts";const plain = (value: unknown) => String(value).replace(/[\x00-\x1f\x7f-\x9f]/g, " ");@@ -144,6 +145,103 @@ const browserParameters = Type.Object({timeout_ms: Type.Optional(Type.Integer({ minimum: 1, maximum: 60000, description: "Time limit; default 5000 for switch_tab, close_tab, dialog and cancel_download, 30000 otherwise." })),}, { additionalProperties: false });+const machineSchema = Type.String({ description: "computer:machine/<name>; computer:machine/local is this machine." });++/** A machine address itself, the one place files, clipboard, video and audio commands run. */+function machineAddress(resources: ComputerResources, source: string): ComputerAddress {+ const address = resources.address(source);+ if (address.kind !== "machine" || address.part) throw new ComputerRequestError("Give a machine address such as computer:machine/local or computer:machine/<name>.");+ return address;+}++/** Fields an action takes; any other given field, or a missing required one, refuses the request. */+function fieldsFor(action: string, fields: Record<string, unknown>, allowed: string[], required: string[] = []) {+ const extra = Object.keys(fields).filter(key => fields[key] !== undefined && !allowed.includes(key));+ if (extra.length) throw new ComputerRequestError(`${action} takes no ${extra.join(", ")}.`);+ const missing = required.filter(key => fields[key] === undefined);+ if (missing.length) throw new ComputerRequestError(`${action} needs ${missing.join(" and ")}.`);+}++const filesParameters = Type.Object({+ machine: machineSchema,+ action: Type.Union([Type.Literal("put"), Type.Literal("get"), Type.Literal("list")], { description: "put copies a workspace file into this session's folder on the machine; get copies a file from that folder into the workspace; list shows the folder's Windows path and files. Apps there open and save files in that folder; closing the session removes it." }),+ from: Type.Optional(Type.String({ description: "put: workspace file path." })),+ name: Type.Optional(Type.String({ description: "put: file name in the folder, default the name of from; get: the file to copy out." })),+ to: Type.Optional(Type.String({ description: "get: workspace path to write." })),+}, { additionalProperties: false });++/** The machine command of computer_files. */+export function filesCommand(params: Static<typeof filesParameters>): Record<string, unknown> {+ const { machine: _machine, action, ...fields } = params;+ if (action === "put") fieldsFor(action, fields, ["from", "name"], ["from"]);+ else if (action === "get") fieldsFor(action, fields, ["name", "to"], ["name", "to"]);+ else fieldsFor(action, fields, []);+ return { action: action === "list" ? "files" : action, ...fields };+}++const clipboardParameters = Type.Object({+ machine: machineSchema,+ action: Type.Union([Type.Literal("read"), Type.Literal("write")], { description: "YOLO only; the clipboard is shared with the user's own apps. read returns its formats and text; write replaces it with text or an image." }),+ include_image: Type.Optional(Type.Boolean({ description: "read: also return the clipboard's image as PNG." })),+ text: Type.Optional(Type.String({ description: "write: the text to put on the clipboard." })),+ image: Type.Optional(Type.String({ description: "write: workspace path of an image file to put on the clipboard instead of text." })),+}, { additionalProperties: false });++/** The machine command of computer_clipboard. */+export function clipboardCommand(params: Static<typeof clipboardParameters>): Record<string, unknown> {+ const { machine: _machine, action, ...fields } = params;+ if (action === "read") {+ fieldsFor(action, fields, ["include_image"]);+ return { action: "clipboard_read", ...(fields.include_image ? { image: true } : {}) };+ }+ fieldsFor(action, fields, ["text", "image"]);+ if ((fields.text === undefined) === (fields.image === undefined)) throw new ComputerRequestError("write needs exactly one of text or image.");+ return { action: "clipboard_write", ...(fields.text !== undefined ? { text: fields.text } : { image: fields.image }) };+}++const recordParameters = Type.Object({+ at: Type.String({ description: "video_start, video_stop and audio: computer:machine/<name>; sequence: a window or display address." }),+ action: Type.Union([Type.Literal("video_start"), Type.Literal("video_stop"), Type.Literal("audio"), Type.Literal("sequence")], { description: "video_start records the machine's main display to video (YOLO) until video_stop or seconds pass; video_stop ends it and can fetch the file; audio records the machine's playback for seconds (YOLO); sequence captures frames of a window or display over duration_ms and returns a sequence address, whose frames Read shows with a frames: view." }),+ seconds: Type.Optional(Type.Integer({ minimum: 1, maximum: 600, description: "video_start: recording limit, 1..600; audio: recording length, 1..300." })),+ to: Type.Optional(Type.String({ description: "video_stop and audio: workspace path to fetch the recorded file into." })),+ transcribe: Type.Optional(Type.Boolean({ description: "audio: add a speech transcript made by faster-whisper on this machine; it can be wrong." })),+ duration_ms: Type.Optional(Type.Integer({ minimum: 1, maximum: 60000, description: "sequence: capture length." })),+ fps: Type.Optional(Type.Integer({ minimum: 1, maximum: 30, description: "sequence: frames per second to aim for, default 4; the result reports the rate reached." })),+ max_frames: Type.Optional(Type.Integer({ minimum: 1, maximum: 300, description: "sequence: frame limit, default 40." })),+ timeout_ms: Type.Optional(Type.Integer({ minimum: 1, maximum: 90000, description: "sequence: total time limit, at least duration_ms, default 15000." })),+ maxLongEdge: Type.Optional(Type.Integer({ minimum: 64, maximum: 4096, description: "sequence: longest frame edge in pixels." })),+ scale: Type.Optional(Type.Number({ minimum: 0.05, maximum: 1, description: "sequence: frame scale instead of maxLongEdge." })),+ region: Type.Optional(Type.Object({ x: Type.Integer({ minimum: 0 }), y: Type.Integer({ minimum: 0 }), width: Type.Integer({ minimum: 1 }), height: Type.Integer({ minimum: 1 }) },+ { additionalProperties: false, description: "sequence: part of the window or display to capture, in its local pixels." })),+}, { additionalProperties: false });++const SEQUENCE_FIELDS = ["duration_ms", "fps", "max_frames", "timeout_ms", "maxLongEdge", "scale", "region"];++/**+ * What computer_record runs: a machine command for video and audio, or the Read sequence view of a window or display.+ */+export function recordCommand(params: Static<typeof recordParameters>): { command: Record<string, unknown> } | { views: string[] } {+ const { at: _at, action, ...fields } = params;+ if (action === "sequence") {+ fieldsFor(action, fields, SEQUENCE_FIELDS, ["duration_ms"]);+ const views = [`sequence:${JSON.stringify(fields)}`];+ try { parseComputerViews(views); }+ catch (error) { throw new ComputerRequestError(error instanceof Error ? error.message : String(error)); }+ return { views };+ }+ if (action === "video_start") {+ fieldsFor(action, fields, ["seconds"], ["seconds"]);+ return { command: { action: "record_start", seconds: fields.seconds } };+ }+ if (action === "video_stop") {+ fieldsFor(action, fields, ["to"]);+ return { command: { action: "record_stop", ...fields } };+ }+ fieldsFor(action, fields, ["seconds", "to", "transcribe"], ["seconds"]);+ if (fields.seconds! > 300) throw new ComputerRequestError("audio records at most 300 seconds.");+ return { command: { action: "audio_record", ...fields } };+}+/*** Register the typed computer_* tools that replace Insert commands one cluster at a time. They are deferred: a* tool_search for computer loads them, so sessions that never use the computer pay nothing for them.@@ -212,6 +310,55 @@ export function registerComputerTools(pi: ExtensionAPI, resources: ComputerResouaddress => resources.browserAction(address, ctx.cwd, command, signal)));},});+ pi.registerTool({+ ...common, name: "computer_files", label: "Computer files",+ description: "Use computer_files to copy files between the workspace and this session's own folder on a machine, or to list that folder, so apps there can open or save them.",+ parameters: filesParameters,+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },+ ...rendered("computer_files", args => `${args.machine} ${args.action}${args.from ? ` ${args.from}` : args.name ? ` ${args.name}` : ""}`),+ async execute(_id, params, signal, _update, ctx) {+ let command: Record<string, unknown> = {};+ return actionResult(await computerAction(resources, params.machine, params.action, () => {+ command = filesCommand(params);+ return machineAddress(resources, params.machine);+ }, address => resources.perform(address, ctx.cwd, JSON.stringify(command), "insert", signal)));+ },+ });+ pi.registerTool({+ ...common, name: "computer_clipboard", label: "Computer clipboard",+ description: "Use computer_clipboard to read or replace a machine's clipboard in YOLO mode, with text or an image.",+ parameters: clipboardParameters,+ annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: false },+ ...rendered("computer_clipboard", args => `${args.machine} ${args.action}${args.image ? ` ${args.image}` : ""}`),+ async execute(_id, params, signal, _update, ctx) {+ let command: Record<string, unknown> = {};+ return actionResult(await computerAction(resources, params.machine, `clipboard_${params.action}`, () => {+ command = clipboardCommand(params);+ return machineAddress(resources, params.machine);+ }, address => resources.perform(address, ctx.cwd, JSON.stringify(command), "insert", signal)));+ },+ });+ pi.registerTool({+ ...common, name: "computer_record", label: "Computer record",+ description: "Use computer_record to record a machine's display to video or its playback audio, or to capture frames of a window or display over time for motion and animation.",+ parameters: recordParameters,+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },+ ...rendered("computer_record", args => `${args.at} ${args.action}${args.seconds ? ` ${args.seconds} s` : args.duration_ms ? ` ${args.duration_ms} ms` : ""}`),+ async execute(_id, params, signal, _update, ctx) {+ let run: ReturnType<typeof recordCommand> = { command: {} };+ return actionResult(await computerAction(resources, params.at, params.action, () => {+ run = recordCommand(params);+ if ("views" in run) {+ const address = resources.address(params.at);+ if (address.kind !== "window" && address.kind !== "display") throw new ComputerRequestError("sequence captures a window or display address.");+ return address;+ }+ return machineAddress(resources, params.at);+ }, async address => "views" in run+ ? (await resources.read(address, ctx.cwd, run.views, signal))!+ : resources.perform(address, ctx.cwd, JSON.stringify(run.command), "insert", signal)));+ },+ });pi.registerTool({...common, name: "computer_display", label: "Computer display",description: "Use computer_display to change a display's resolution in YOLO mode, for example to test an app at another size; closing computer use restores it.",diff --git a/test/computer-tools.test.ts b/test/computer-tools.test.tsindex b5ff95a..2e1386e 100644--- a/test/computer-tools.test.ts+++ b/test/computer-tools.test.ts@@ -1,6 +1,6 @@import { expect, test, vi } from "vitest";import { requireComputerAddress, ComputerResources } from "../src/computer-resources.ts";-import { openCommand, waitCommand, windowCommand } from "../src/computer-tools.ts";+import { clipboardCommand, filesCommand, openCommand, recordCommand, waitCommand, windowCommand } from "../src/computer-tools.ts";import type { WebBrowser, WebLauncher } from "../src/web-browser.ts";import type { MachineHost } from "../src/machine-host.ts";import { deleteComputer } from "../src/provider.ts";@@ -44,6 +44,39 @@ test("computer_wait maps to wait_for or a single verify sample", () => {expect(() => waitCommand({ window: "w", conditions, mode: "check", timeout_ms: 10 })).toThrow("check takes one sample, so timeout_ms do not apply.");});+test("computer_files maps put, get and list and takes only their fields", () => {+ expect(filesCommand({ machine: "m", action: "put", from: "a.txt" })).toEqual({ action: "put", from: "a.txt" });+ expect(filesCommand({ machine: "m", action: "put", from: "a.txt", name: "b.txt" })).toEqual({ action: "put", from: "a.txt", name: "b.txt" });+ expect(filesCommand({ machine: "m", action: "get", name: "b.txt", to: "out/b.txt" })).toEqual({ action: "get", name: "b.txt", to: "out/b.txt" });+ expect(filesCommand({ machine: "m", action: "list" })).toEqual({ action: "files" });+ expect(() => filesCommand({ machine: "m", action: "put" })).toThrow("put needs from.");+ expect(() => filesCommand({ machine: "m", action: "get", name: "b.txt" })).toThrow("get needs to.");+ expect(() => filesCommand({ machine: "m", action: "list", to: "x" })).toThrow("list takes no to.");+});++test("computer_clipboard reads with or without the image and writes exactly one of text or image", () => {+ expect(clipboardCommand({ machine: "m", action: "read" })).toEqual({ action: "clipboard_read" });+ expect(clipboardCommand({ machine: "m", action: "read", include_image: true })).toEqual({ action: "clipboard_read", image: true });+ expect(clipboardCommand({ machine: "m", action: "write", text: "hi" })).toEqual({ action: "clipboard_write", text: "hi" });+ expect(clipboardCommand({ machine: "m", action: "write", image: "a.png" })).toEqual({ action: "clipboard_write", image: "a.png" });+ expect(() => clipboardCommand({ machine: "m", action: "write" })).toThrow("write needs exactly one of text or image.");+ expect(() => clipboardCommand({ machine: "m", action: "write", text: "hi", image: "a.png" })).toThrow("write needs exactly one of text or image.");+ expect(() => clipboardCommand({ machine: "m", action: "read", text: "hi" })).toThrow("read takes no text.");+});++test("computer_record maps video and audio to machine commands and sequence to the Read view", () => {+ expect(recordCommand({ at: "m", action: "video_start", seconds: 30 })).toEqual({ command: { action: "record_start", seconds: 30 } });+ expect(recordCommand({ at: "m", action: "video_stop", to: "v.mp4" })).toEqual({ command: { action: "record_stop", to: "v.mp4" } });+ expect(recordCommand({ at: "m", action: "audio", seconds: 5, transcribe: true })).toEqual({ command: { action: "audio_record", seconds: 5, transcribe: true } });+ expect(recordCommand({ at: "w", action: "sequence", duration_ms: 2000, fps: 10, region: { x: 0, y: 0, width: 100, height: 50 } }))+ .toEqual({ views: ['sequence:{"duration_ms":2000,"fps":10,"region":{"x":0,"y":0,"width":100,"height":50}}'] });+ expect(() => recordCommand({ at: "m", action: "video_start" })).toThrow("video_start needs seconds.");+ expect(() => recordCommand({ at: "m", action: "audio", seconds: 400 })).toThrow("audio records at most 300 seconds.");+ expect(() => recordCommand({ at: "w", action: "sequence" })).toThrow("sequence needs duration_ms.");+ expect(() => recordCommand({ at: "w", action: "sequence", duration_ms: 5000, timeout_ms: 1000 })).toThrow("timeout_ms duration..");+ expect(() => recordCommand({ at: "m", action: "video_stop", seconds: 3 })).toThrow("video_stop takes no seconds.");+});+/** A Chrome window (pid 4100) attached to a fake Playwright worker that records page actions. */function browserFixture() {const target = { pid: 4100, window_id: 77, title: "Page - Google Chrome", app_name: "chrome.exe" };diff --git a/test/extension-modes.integration.test.ts b/test/extension-modes.integration.test.tsindex ba1f23f..1218112 100644--- a/test/extension-modes.integration.test.ts+++ b/test/extension-modes.integration.test.ts@@ -31,17 +31,27 @@ test("without Pi Agent IDE, tool_search finds the deferred computer tools and th{ id: "guide", name: "computer_read", arguments: { path: "docs:computer" } },{ id: "session", name: "computer_read", arguments: { path: "computer:session" } },{ id: "close", name: "computer_insert", arguments: { path: "computer:session", text: '{"action":"close"}' } },+ { id: "open", name: "tool_search", arguments: { query: "computer open window" } },{ id: "more", name: "tool_search", arguments: { query: "computer wait browser" } },{ id: "display", name: "computer_display", arguments: { display: "computer:display/primary", width: 1920, height: 1080 } },+ { id: "files", name: "tool_search", arguments: { query: "computer files clipboard record" } },+ { id: "list", name: "computer_files", arguments: { machine: "computer:session", action: "list" } },+ { id: "sequence", name: "computer_record", arguments: { at: "computer:machine/local/display/primary", action: "sequence" } },{ id: "delete", name: "computer_delete", arguments: { path: "computer:session" } },]);- expect(getToolCallNames(result)).toEqual(["tool_search", "computer_read", "computer_read", "computer_insert", "tool_search", "computer_display", "computer_delete"]);+ expect(getToolCallNames(result)).toEqual(["tool_search", "computer_read", "computer_read", "computer_insert", "tool_search", "tool_search", "computer_display", "tool_search", "computer_files", "computer_record", "computer_delete"]);for (const id of ["find", "guide", "session", "close", "delete"])expect(getToolExecution(result, id).isError, getToolResultText(result, id)).toBe(false);expect(getToolResultText(result, "find")).toContain("computer_read");- // tool_search loads the best matches of each query, at most 8 by default.- for (const tool of ["computer_open", "computer_window", "computer_display", "computer_delete"]) expect(getToolResultText(result, "find")).toContain(tool);- for (const tool of ["computer_wait", "computer_browser"]) expect(getToolResultText(result, "more")).toContain(tool);+ // tool_search loads the best matches of each query, at most 8 by default, so the guide names one query per cluster.+ // A query lists only tools it newly loads; together the guide's cluster queries load every computer tool.+ const loaded = ["find", "open", "more", "files"].map(id => getToolResultText(result, id)).join("\n");+ for (const tool of ["computer_search", "computer_insert", "computer_write", "computer_delete", "computer_open", "computer_window", "computer_display",+ "computer_wait", "computer_browser", "computer_files", "computer_clipboard", "computer_record"]) expect(loaded).toContain(`- ${tool}:`);+ // Files, clipboard and recording run on a machine address, and a sequence needs its length; both refuse before native work.+ expect(getToolResultText(result, "list")).toContain("Give a machine address");+ expect(getToolResultText(result, "sequence")).toContain("sequence needs duration_ms.");+ for (const id of ["list", "sequence"]) expect(getToolExecution(result, id).isError).toBe(true);// A typed tool refuses a bad address with a receipt before any native work.expect(getToolExecution(result, "display").isError).toBe(true);expect(getToolResultText(result, "display")).not.toContain("unknown");diff --git a/test/fixtures/window-management-extension.ts b/test/fixtures/window-management-extension.tsindex 41740cf..6d39fed 100644--- a/test/fixtures/window-management-extension.ts+++ b/test/fixtures/window-management-extension.ts@@ -197,6 +197,10 @@ export default async function fixture(pi: ExtensionAPI): Promise<void> {await denied("computer_wait", { window: "computer:machine/local", conditions: [{ target: button, is: "exists" }] });await denied("computer_wait", { window: first, mode: "check", timeout_ms: 10, conditions: [{ target: button, is: "exists" }] });await denied("computer_browser", { window: first, action: "reload" });+ await denied("computer_files", { machine: first, action: "list" });+ await denied("computer_clipboard", { machine: "computer:machine/local/windows", action: "read" });+ await denied("computer_record", { at: first, action: "video_start", seconds: 5 });+ await denied("computer_record", { at: "computer:machine/local", action: "sequence", duration_ms: 100 });const external = reference(await ok("search", { path: "computer:machine/local/windows", query: "Unowned management fixture" }), "window");mode = "safe";const refused = await window({ action: "focus" }, external);diff --git a/test/unified-tools.integration.test.ts b/test/unified-tools.integration.test.tsindex d83aff3..6b4d26d 100644--- a/test/unified-tools.integration.test.ts+++ b/test/unified-tools.integration.test.ts@@ -30,7 +30,7 @@ test("production Pi exposes only computer tools, with no direct or Codemode brow],}).run("Check the production loadout. Only discover apps; never open a window or send input.");// Without Pi Agent IDE, production computer use offers deferred tools that tool_search loads.- const standalone = ["computer_browser", "computer_delete", "computer_display", "computer_insert", "computer_open", "computer_read", "computer_search", "computer_wait", "computer_window", "computer_write"];+ const standalone = ["computer_browser", "computer_clipboard", "computer_delete", "computer_display", "computer_files", "computer_insert", "computer_open", "computer_read", "computer_record", "computer_search", "computer_wait", "computer_window", "computer_write"];expect(getToolExecutionDetails(getToolExecution(result, "registry"))).toEqual({names: standalone,exposure: Object.fromEntries(standalone.map(name => [name, "deferred"])),