Skip to content

Computer use for the Pi coding agent — Windows apps, browsers and desktops through native UI trees, screenshots and real input.

Short addresses and agent-given window names (LPT-932)

alexshpunt-clanker[bot]8e7d0a2a4186
diff --git a/docs/computer-resources.md b/docs/computer-resources.md
index b7446b5..b9e39fa 100644
--- a/docs/computer-resources.md
+++ b/docs/computer-resources.md
@@ -15,6 +15,19 @@ Every machine is addressed the same way: `computer:machine/local` is this one, a
No address falls back to this machine. Window, window-state, observation and sequence addresses belong to the machine (or sandbox) that issued them, and every Read, Search and Insert on them runs there. Display addresses name their machine. An address that no machine of this session issued, or that was released, is refused with the reason before anything is sent. Every receipt names its machine in its first line, for example `Computer observed (yolo) on lab`.
+### Short addresses and names
+
+Results show addresses in a short form: `computer:<machine>/<letter><number><tag>`, for example `computer:lab/w3qk` for a window, `o` for an observation, `s` for a sequence, `t` for a window state, `a` for an app, `b` for a sandbox and `d` for a listed display. Numbers count per machine and kind. The two-letter tag is drawn once per Pi run: an address kept from an earlier run is refused instead of reaching whatever window got the same number. Observation options go on the short form too (`computer:lab/o7qk?hint=1:a&delivery=foreground`). The long forms (`computer:window/w-...`) keep working and stay in structured details.
+
+Give a window a name and use it wherever the window's address goes:
+
+| Insert | Into | Effect |
+| --- | --- | --- |
+| `{"action":"name","as":"game"}` | a window address | `computer:game` now names that window |
+| `{"action":"name","as":"game","title":"Chrome"}` | a machine address | Names the one window whose title matches (text or `regex:`); several matches refuse with the candidates |
+
+A name is 1-32 lowercase letters, digits, `-` or `_`, starts with a letter, and is not an address word or a machine name. One window has one name; naming it again replaces the name, and a live window's name is not taken over. A name resolves only to its window: it is refused once the window has closed (a full window listing of its machine notices that) or its machine was released. Read `computer:session` for the current names and the windows listed so far.
+
| Address | Use |
| --- | --- |
| `computer:machine/<name>/windows` | Search its windows |
diff --git a/src/computer-address.ts b/src/computer-address.ts
index ec53e8a..2f92c27 100644
--- a/src/computer-address.ts
+++ b/src/computer-address.ts
@@ -11,6 +11,8 @@ export type ComputerAddress =
| { kind: "observation"; source: string; ref: string; hint?: string; delivery?: "background" | "foreground"; delayMs?: number };
const references = new Set(["app", "window", "observation", "sequence", "window-state", "sandbox", "machine"]);
+/** Words a long address starts with; machine names and window names never take them. */
+export const ADDRESS_KINDS: ReadonlySet<string> = new Set([...references, "session", "display"]);
const parts = new Set(["windows", "apps", "displays"]);
/** Resolve this namespace or reject malformed owned addresses before any native work. */
diff --git a/src/computer-resources.ts b/src/computer-resources.ts
index 7ee3477..32a6b4b 100644
--- a/src/computer-resources.ts
+++ b/src/computer-resources.ts
@@ -1,5 +1,6 @@
import { randomUUID } from "node:crypto";
-import { parseComputerAddress, computerSource, displaySource, type ComputerAddress } from "./computer-address.ts";
+import { parseComputerAddress, computerSource, displaySource, ADDRESS_KINDS, type ComputerAddress } from "./computer-address.ts";
+import { ShortAddresses, SHORT_REFERENCE } from "./short-addresses.ts";
import { parseComputerViews, type ComputerViews } from "./computer-views.ts";
import { checkedName, type ProcessHealth } from "./machine-host.ts";
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
@@ -25,7 +26,7 @@ export const LOCAL_MACHINE = "local";
/** How to use a machine address: the same on every machine. */
export function machineGuide(source: string): string[] {
return [`Search ${source}/windows for its windows and ${source}/apps for its installed apps; Read ${source}/displays for its displays and ${source}/display/primary for its main display (Insert resize into a display address to change its resolution).`,
- `Insert open, open_browser, open_sandbox, open_session, webview2_debugging, put, get, files, clipboard_read, clipboard_write, record_start, record_stop, audio_record or close into ${source}.`];
+ `Insert open, open_browser, open_sandbox, open_session, webview2_debugging, put, get, files, clipboard_read, clipboard_write, record_start, record_stop, audio_record, name (a window by its title) or close into ${source}.`];
}
/** A rejected request whose validation completed before native dispatch. */
export class ComputerRequestError extends Error {}
@@ -249,6 +250,12 @@ function object(value: unknown): Record<string, unknown> {
if (!value || typeof value !== "object" || Array.isArray(value)) throw new ComputerRequestError("Use a JSON command object.");
return value as Record<string, unknown>;
}
+/** A window name the agent gives: computer:<name>. */
+const NAME = /^[a-z][a-z0-9_-]{0,31}$/;
+/** Whether an Insert text is a name command, checked before the address's other commands. */
+function nameCommand(value: string): boolean {
+ try { return (JSON.parse(value) as { action?: unknown })?.action === "name"; } catch { return false; }
+}
function only(value: Record<string, unknown>, fields: readonly string[]): void {
if (Object.keys(value).some(key => !fields.includes(key))) throw new ComputerRequestError("Command contains unsupported fields.");
}
@@ -268,6 +275,14 @@ export class ComputerResources {
private readonly starting = new Map<string, Promise<OpenedMachine>>();
/** Sandbox launches and machine starts still in progress; a cancelled one finishes its own cleanup before it settles. */
private readonly opening = new Set<Promise<unknown>>();
+ /** Short aliases of this run's long addresses (computer:zinpc/w3qk). */
+ private readonly shorts = new ShortAddresses();
+ /** Window names the agent gave, with the window's title when it was named. */
+ private readonly names = new Map<string, { window_ref: string; title: string }>();
+ /** Window titles from the latest window listings, for naming by title and for listing names. */
+ private readonly titles = new Map<string, string>();
+ /** This machine's session once started; reference checks need it synchronously. */
+ private local?: ComputerSession;
/** Give an installed app of one machine an opaque reference; paths themselves are not session references. */
private appRef(machine: string, id: string): string {
@@ -287,10 +302,58 @@ export class ComputerResources {
for (const sandbox of this.sandboxes.values())
if (holds(sandbox.session)) return { session: sandbox.session, machine: sandbox.machine ?? LOCAL_MACHINE, sandbox: sandbox.ref };
for (const [machine, opened] of this.machines) if (holds(opened.session)) return { session: opened.session, machine };
- const local = await this.getSession(cwd);
+ const local = this.local = await this.getSession(cwd);
if (holds(local)) return { session: local, machine: LOCAL_MACHINE };
throw new ComputerRequestError(`${unknown} No machine or sandbox of this computer use holds it, so nothing was sent.`);
}
+ /** Whether any started session of this computer use still holds a window reference. */
+ private holdsWindow(ref: string): boolean {
+ return [...this.sandboxes.values(), ...this.machines.values()].some(environment => environment.session.hasWindow(ref)) || !!this.local?.hasWindow(ref);
+ }
+ /** Give a window a name; one name per window, and a name of a live window is not taken over. */
+ private nameWindow(name: unknown, ref: string): ComputerResult {
+ if (typeof name !== "string" || !NAME.test(name) || ADDRESS_KINDS.has(name) || name === LOCAL_MACHINE || this.machines.has(name))
+ throw new ComputerRequestError("as is a name of 1-32 lowercase letters, digits, - or _ that starts with a letter and is not an address word (session, window, machine, ...) or a machine name.");
+ const held = this.names.get(name);
+ if (held && held.window_ref !== ref && this.holdsWindow(held.window_ref))
+ throw new ComputerRequestError(`computer:${name} already names ${computerSource("window", held.window_ref)}${held.title ? ` (${held.title})` : ""}. Choose another name.`);
+ for (const [other, entry] of this.names) if (entry.window_ref === ref) this.names.delete(other);
+ const title = this.titles.get(ref) ?? "";
+ this.names.set(name, { window_ref: ref, title });
+ return { content: [{ type: "text", text: `computer:${name} now names ${computerSource("window", ref)}${title ? ` (${title})` : ""}. Use it wherever this window's address goes; it stops resolving when the window closes.` }],
+ details: { status: "delivered", mode: this.getMode(), window_ref: ref } };
+ }
+ /**
+ * Parse an address the agent sent: a long one, a short alias issued in this run (computer:zinpc/w3qk, with the
+ * observation options of the long form), or a window name (computer:game). Stale aliases and names refuse.
+ */
+ address(source: string): ComputerAddress {
+ if (!source.startsWith("computer:")) return requireComputerAddress(source);
+ const at = source.indexOf("?");
+ const base = at < 0 ? source : source.slice(0, at), query = at < 0 ? "" : source.slice(at);
+ const segments = base.slice(9).split("/");
+ if (segments.length === 1 && !ADDRESS_KINDS.has(segments[0]) && NAME.test(segments[0])) {
+ if (query) throw new ComputerRequestError("A window name takes no options. Read it for an observation and put options on that observation's address.");
+ const entry = this.names.get(segments[0]);
+ if (!entry) throw new ComputerRequestError(`No window is named ${segments[0]}. Insert {"action":"name","as":"${segments[0]}"} into a window address first; Read computer:session for the current names.`);
+ if (!this.holdsWindow(entry.window_ref)) {
+ this.names.delete(segments[0]);
+ throw new ComputerRequestError(`computer:${segments[0]} named a window that has closed or was released${entry.title ? ` (${entry.title})` : ""}. Search the machine's windows again and name the new one.`);
+ }
+ return requireComputerAddress(computerSource("window", entry.window_ref));
+ }
+ if (segments.length === 2 && !ADDRESS_KINDS.has(segments[0]) && SHORT_REFERENCE.test(segments[1])) {
+ let long: string;
+ try { long = this.shorts.resolve(segments[0], segments[1]); }
+ catch (error) { throw new ComputerRequestError(error instanceof Error ? error.message : String(error)); }
+ return requireComputerAddress(long + query);
+ }
+ return requireComputerAddress(source);
+ }
+ /** Replace the long addresses in text shown to the agent with this run's short aliases. */
+ shorten(text: string): string {
+ return this.shorts.shorten(text, (kind, ref) => this.place(requireComputerAddress(computerSource(kind, ref)))?.machine);
+ }
/** The owner of a window, or of one machine's display. */
private async route(cwd: string, target: ObservationTarget, signal?: AbortSignal): Promise<Owner> {
if (target.window_ref !== undefined)
@@ -358,7 +421,7 @@ export class ComputerResources {
}
/** The session of a machine by name: this one's, or a remote one's started on first use. */
private async machineSession(cwd: string, name: string, signal?: AbortSignal): Promise<ComputerSession> {
- return name === LOCAL_MACHINE ? this.getSession(cwd) : (await this.machine(cwd, name, signal)).session;
+ return name === LOCAL_MACHINE ? (this.local = await this.getSession(cwd)) : (await this.machine(cwd, name, signal)).session;
}
/** Forget a released session's observations and window states, and the display observations of its machine. */
private forget(session: ComputerSession, machine?: string): void {
@@ -493,9 +556,16 @@ export class ComputerResources {
}
if (address.kind === "session") {
const machines = [LOCAL_MACHINE, ...this.machines.keys()].map(name => `- ${computerSource("machine", name)}`);
+ // Names whose window closed disappear from the list and stop resolving.
+ for (const [name, entry] of this.names) if (!this.holdsWindow(entry.window_ref)) this.names.delete(name);
+ const names = [...this.names].map(([name, entry]) => `- computer:${name} → ${computerSource("window", entry.window_ref)}${entry.title ? ` | ${entry.title}` : ""}`);
+ const windows = [...this.titles].filter(([ref]) => this.holdsWindow(ref) && this.shorts.issued(computerSource("window", ref)))
+ .map(([ref, title]) => `- ${computerSource("window", ref)} | ${title}`);
const sandboxes = [...this.sandboxes.values()].map(sandbox => `- ${computerSource("sandbox", sandbox.ref)} on ${computerSource("machine", sandbox.machine ?? LOCAL_MACHINE)}`);
return ["# Computer use", "Machines (computer:machine/local is this one; a machine configured under machines in .pi/computer-use.json starts on its first use). Every window, display, observation and sequence address belongs to the machine that issued it, and every receipt names that machine:",
...machines, ...(sandboxes.length ? ["Sandboxes and isolated sessions:", ...sandboxes] : []),
+ ...(names.length ? ["Window names (Insert {\"action\":\"name\",\"as\":\"<name>\"} into a window address to add one):", ...names] : []),
+ ...(windows.length ? ["Windows listed so far:", ...windows] : []),
"Insert {\"action\":\"close\"} here to release every machine, browser, sandbox and session this computer use started; the result lists each part."].join("\n");
}
return `# Computer resource\nSource: ${address.source}\nUse Read for native observation, Search for discovery, and Insert for explicit commands. No native capture occurred during descriptor resolution.`;
@@ -691,6 +761,25 @@ export class ComputerResources {
/** Search permitted discovery metadata or the current collected UI without another native walk; the receipt names its machine. */
async search(address: ComputerAddress, cwd: string, query: string, limit?: number, signal?: AbortSignal): Promise<ComputerResult> {
+ const result = await this.searchAt(address, cwd, query, limit, signal);
+ const windows = result.details.state?.windows;
+ if (Array.isArray(windows)) {
+ const listed = new Set<string>();
+ for (const row of windows as { window_ref?: unknown; title?: unknown; name?: unknown }[])
+ if (typeof row.window_ref === "string") { listed.add(row.window_ref); this.titles.set(row.window_ref, String(row.title ?? row.name ?? "")); }
+ // A full listing shows every open window of that machine or sandbox: windows missing from it have closed,
+ // and their names and titles go. The native session keeps such references until a capture finds them gone.
+ const where = this.place(address);
+ const same = (ref: string) => { const other = this.place(requireComputerAddress(computerSource("window", ref))); return other?.machine === where?.machine && other?.sandbox === where?.sandbox; };
+ if (!query && result.details.status === "listed" && where) {
+ for (const ref of this.titles.keys()) if (!listed.has(ref) && same(ref)) this.titles.delete(ref);
+ for (const [name, entry] of this.names) if (!listed.has(entry.window_ref) && same(entry.window_ref)) this.names.delete(name);
+ }
+ }
+ while (this.titles.size > 512) this.titles.delete(this.titles.keys().next().value!);
+ return result;
+ }
+ private async searchAt(address: ComputerAddress, cwd: string, query: string, limit?: number, signal?: AbortSignal): Promise<ComputerResult> {
const place = this.place(address);
return this.stamp(place, await this.searchAddress(address, cwd, query, limit, signal));
}
@@ -723,6 +812,24 @@ export class ComputerResources {
return this.stamp(place, await this.performAt(address, cwd, value, tool, signal));
}
private async performAt(address: ComputerAddress, cwd: string, value: string, tool: "write" | "insert", signal?: AbortSignal): Promise<ComputerResult> {
+ if (tool === "insert" && (address.kind === "window" || address.kind === "machine" && !address.part) && nameCommand(value)) {
+ const command = commandObject(value);
+ if (address.kind === "window") {
+ only(command, ["action", "as"]);
+ await this.route(cwd, { window_ref: address.ref }, signal);
+ return this.nameWindow(command.as, address.ref);
+ }
+ only(command, ["action", "as", "title"]);
+ if (typeof command.title !== "string" || !command.title) throw new ComputerRequestError("Name a window of a machine by its title: {\"action\":\"name\",\"as\":\"game\",\"title\":\"<text or regex:...>\"}, or Insert the name command into the window's address.");
+ const listed = await this.search(requireComputerAddress(computerSource("machine", address.ref, "windows")), cwd, command.title, undefined, signal);
+ const rows = ((listed.details.state?.windows ?? []) as { window_ref?: string; title?: string }[]).filter(row => typeof row.window_ref === "string");
+ if (rows.length !== 1) {
+ const candidates = rows.slice(0, 20).map(row => `- ${computerSource("window", row.window_ref!)} | ${row.title ?? ""}`);
+ throw new ComputerRequestError(rows.length ? `${rows.length} windows match ${JSON.stringify(command.title)}; name one by its address or a narrower title:\n${candidates.join("\n")}`
+ : `No window of ${computerSource("machine", address.ref)} matches ${JSON.stringify(command.title)}.`);
+ }
+ return this.nameWindow(command.as, rows[0].window_ref!);
+ }
if (address.kind === "window-state") {
if (tool !== "insert") throw new ComputerRequestError("Window state grants native control through Insert, never literal Write.");
const command = commandObject(value);
diff --git a/src/config.ts b/src/config.ts
index f708ab5..80e7dc8 100644
--- a/src/config.ts
+++ b/src/config.ts
@@ -1,6 +1,7 @@
import { readFile } from "node:fs/promises";
import path from "node:path";
import { findBundledRuntime, type BundledRuntime } from "./native-runtime.ts";
+import { ADDRESS_KINDS } from "./computer-address.ts";
/** Trusted overrides and an internal verified bundle. No executable or per-window target comes from agent input. */
export interface ComputerConfig {
@@ -88,7 +89,8 @@ function parseMachines(value: unknown): Record<string, MachineConfig> {
const machines: Record<string, MachineConfig> = {};
for (const [name, raw] of Object.entries(value)) {
// "local" names this machine itself.
- if (!/^[a-z0-9][a-z0-9_-]{0,63}$/.test(name) || name === "local" || !raw || typeof raw !== "object" || Array.isArray(raw)) return invalid();
+ // Short addresses start with the machine name (computer:<name>/w3qk), so it never takes an address kind word.
+ if (!/^[a-z0-9][a-z0-9_-]{0,63}$/.test(name) || name === "local" || ADDRESS_KINDS.has(name) || !raw || typeof raw !== "object" || Array.isArray(raw)) return invalid();
const machine = raw as Record<string, unknown>;
if (Object.keys(machine).some(key => !["ssh", "command", "runtime", "node", "package"].includes(key))
|| typeof machine.ssh !== "string" || typeof machine.command !== "string" || !machine.command.startsWith("/")
diff --git a/src/provider.ts b/src/provider.ts
index f26df09..c79f5ba 100644
--- a/src/provider.ts
+++ b/src/provider.ts
@@ -19,7 +19,7 @@ const record = (value: unknown): Record<string, unknown> => value !== null && ty
const label = (value: unknown) => typeof value === "string" ? value.replace(/[\r\n\t]/g, " ").slice(0, 1024) : "";
/** Agent guidance shared by the IDE plugin and the standalone tools. */
-export const COMPUTER_PATH_HELP = "Read docs:computer for native resources. computer:session, computer:machine/<name> (local, or a configured machine) with its /windows, /apps and /displays, its /display/primary or listed /display/ref, and returned computer:window/ref, observation/id, window-state/id or sequence/id, each running on the machine that issued it. Read window overviews before input; display/detail/frames are readonly.";
+export const COMPUTER_PATH_HELP = "Read docs:computer for native resources. computer:session, computer:machine/<name> (local, or a configured machine) with its /windows, /apps and /displays, its /display/primary or listed /display/ref, and returned computer:window/ref, observation/id, window-state/id or sequence/id, each running on the machine that issued it; results show short forms such as computer:<machine>/w3qk (o observation, s sequence), and computer:<name> after Insert {\"action\":\"name\",\"as\":\"<name>\"} into a window. Read window overviews before input; display/detail/frames are readonly.";
export const COMPUTER_VIEWS_HELP = "Computer: image/ui/full; dom alone or dom:{target,boxes,depth,log} on a browser window opened by open_browser or attached with attach_browser returns a fresh Playwright aria snapshot with [ref=...] values of the active tab; log:true adds the retained console/page-error/network history; target is {ref} or locator fields role,name,label,text,placeholder,test_id,css,exact,frames. On a DOM observation: image is a page screenshot, element:crop|highlight,<ref> an element image; Search filters its lines. state alone on a window returns fresh restore or management metadata without pixels/UI, plus whether the window is hung and its process memory/CPU. ocr (alone or with capture options on a window, alone on an observation, or with region:x,y,width,height on an observation) adds Windows OCR lines with boxes in overview pixels; use maxLongEdge 3840 for small text. aria (alone or with ui capture options, on a window) returns its UI as a Playwright aria snapshot with hints as [ref=...]. changes (alone, or with ui, image or full and capture options, on a window) takes a fresh capture and lists only rows changed, added or removed since that window's previous observation, with the new observation's hints, plus changed pixel areas with before/after crops instead of the full image. regions (alone or with image/full options on a window, alone on its observation) lists icons and text areas found by Cua perception with boxes in overview pixels; click a box center with pixel input. capture:{maxLongEdge,scale,max_elements,max_depth,hints,guides}. region:x,y,width,height or element:inspect|scope|highlight|crop|text,hint on an observation; element:text returns one element's full text. sequence:{duration_ms<=60000,fps<=30,max_frames<=300,timeout_ms,maxLongEdge,scale,region} on window/display reports actual_fps and last_frame_age_ms; frames:first|last|all|endpoints|changed or frames:{indexes:[0]} / {from:0,to:2} / {select:'changed'} on sequence; add as:'sheet' (one tiled image with index/time labels, optional columns) or as:'max'|'min' (one per-pixel composite), with optional region:{x,y,width,height} in frame pixels and maxLongEdge. Detail/frames are readonly; text offset/limit select UI lines, never image cells.";
export const COMPUTER_SEARCH_HELP = "Search computer:machine/<name>/apps or computer:machine/<name>/windows (local is this machine) for installed-app/permitted-window metadata, or an observation for its collected UI/readonly DOM. Read computer:machine/<name>/displays for monitor metadata. Discovery launches nothing; observation Search performs no new native walk or DOM query. Treat missing matches in a partial projection as unknown.";
export const COMPUTER_INPUT_HELP = "Computer Write sends content literally through type_text to a fresh UI/image observation address. On a DOM observation of a browser opened with Insert {\"action\":\"open_browser\"} (YOLO: \"profile\":\"agent\" keeps the agent's own logins between sessions), or of a running Chromium-based browser attached in YOLO with Insert {\"action\":\"attach_browser\"} into its window address (Chrome or Edge through a debugging port, the chrome://inspect/#remote-debugging switch or the Playwright Extension; an Electron/CEF app started with --remote-debugging-port=0 in open's args; a WebView2 app started with open \"debugging\":true or after {\"action\":\"webview2_debugging\",\"app\":\"x.exe\",\"enabled\":true} on its machine; VS Code's integrated browser through the Pi Browser Bridge; closing the session detaches), Insert one Playwright action such as {\"action\":\"fill\",\"target\":{\"label\":\"Name\"},\"text\":\"value\"}; actions target the active tab, and tab/navigation/dialog actions are listed in docs:computer. Insert {\"action\":\"open_sandbox\"} into a machine address to work in a separate disposable Windows Sandbox that does not touch the human's desktop, or {\"action\":\"open_session\"} for an isolated agent session on the same machine (several can run at once, each with its own desktop and foreground input); use the returned computer:sandbox/... address for Search, open and close (docs:computer). Machines are computer:machine/local (this one) and computer:machine/<configured name> (another Windows machine over SSH, started on first use); each takes the same commands. Insert {\"action\":\"put\",\"from\":\"<workspace file>\"}, {\"action\":\"get\",\"name\":\"<file>\",\"to\":\"<workspace path>\"} or {\"action\":\"files\"} into a machine address to move files through the session's own folder on that machine (removed on close); point app Open/Save dialogs there. The same addresses take {\"action\":\"clipboard_write\",\"text\"|\"image\":...}, {\"action\":\"clipboard_read\",\"image\":true}, {\"action\":\"record_start\",\"seconds\":30} and {\"action\":\"record_stop\",\"to\":\"<workspace path>\"} (main-display video) and {\"action\":\"audio_record\",\"seconds\":10,\"transcribe\":true} (playback audio with a transcript) in YOLO. Insert {\"action\":\"timeline\",\"events\":[{at_ms,type,...}]} with delivery=foreground into an observation for timed key/button/move/move_relative/wheel/pen events; everything held is released at the end (docs:computer). Insert {\"action\":\"resize\",\"width\":1920,\"height\":1080} into a display address to change that display's resolution in YOLO; closing the session restores it. Only after the user explicitly allows it, Insert {\"action\":\"setup\",\"part\":\"browser|firefox|perception|mxc|vscode-bridge\"} into a machine address to install a missing optional part there (docs:computer). Insert {\"action\":\"menu\",\"path\":[\"File\",\"Save As...\"]} into an observation to invoke a menu item by its labels, and {\"action\":\"kill\"} into the window address of an app this session opened to force-close it. Insert an action with a Playwright locator target, such as {\"action\":\"click\",\"target\":\"getByRole('button', { name: 'Save' })\"} or fill/check/select, into a native window address to act without a prior Read; it waits until exactly one element is ready. Insert {\"action\":\"wait_for\"|\"verify\",\"conditions\":[...]} into a window address to check UI state with the same locators, count or an aria snapshot template; every action reports what it changed in the window: UI rows, and changed pixel areas with before/after crops after an action on an image or full observation (\"successor\":false skips it), and \"expect\" adds a postcondition; or Insert {\"action\":\"batch\",\"steps\":[...]} into an observation for a fail-stop chain (docs:computer). Use no Write or native input on a DOM observation. Use optional ?hint=...&delivery=foreground&delay_ms=0 only on input observations. No implicit select-all, submit or program execution. Computer Insert sends {\"action\":\"restore\"} to a fresh window-state address for explicit restoration and activation without keys/clicks, or one JSON action to an observation, or {\"action\":\"open\",\"app\":\"Exact installed name\"} (YOLO also {\"action\":\"open\",\"path\":\"C:\\\\...\\\\app.exe\",\"args\":[...]}) to a machine address, and {\"action\":\"close\"} to a machine address or to computer:session for every machine (the result lists each released part). Close releases runtime, not documents. Omit window_ref/observation_id in JSON. Input consumes observations even on refusal; the action's successor observation is current for the next input. With \"successor\":false, delivered pixel-only input keeps its observation until the window is resized; otherwise refresh with Read. One sequence takes up to 2000 key, click and stroke steps. Never replay unknown prefixes. Foreground input requires an observed background refusal and pauses for 10 s after the human's own keyboard or mouse input; restore is a separate explicit activation, not input delivery. Safe/YOLO is user-controlled.";
@@ -326,10 +326,11 @@ export function computerReceipt(source: string, action: string | null, outcome:
/** One computer Read: native blocks for the model, canonical blocks for scripts and the details renderers use. */
export async function readComputer(resources: ComputerResources, source: string, cwd: string,
request: { readonly views?: readonly string[]; readonly offset?: number; readonly limit?: number }, script: boolean, signal?: AbortSignal) {
- const address = requireComputerAddress(source);
+ const address = resources.address(source);
const result = await resources.read(address, cwd, request.views, signal);
const paged = request.offset !== undefined || request.limit !== undefined;
- let body = result ? presentComputerResult(result, paged) : resources.descriptor(address);
+ // The agent sees this run's short addresses; the long ones stay in structured details.
+ let body = resources.shorten(result ? presentComputerResult(result, paged) : resources.descriptor(address));
const lines = body.split("\n"), offset = request.offset ?? 1;
const start = offset < 0 ? Math.max(0, lines.length + offset) : Math.max(0, offset - 1);
if (request.limit !== undefined && (!Number.isSafeInteger(request.limit) || request.limit < 0)) throw new ComputerRequestError("limit must be a nonnegative text line count.");
@@ -359,12 +360,12 @@ export async function performComputer(resources: ComputerResources, tool: "write
const fields = tool === "write" ? ["path", "content"] : ["path", "text"];
if (Object.keys(input).some(key => !fields.includes(key))) throw new ComputerRequestError("Computer input accepts no text anchors, ranges or insertion flags; its observation address binds the target.");
if (typeof literal !== "string") throw new ComputerRequestError("Provide literal content for Write or one JSON command in Insert text.");
- address = requireComputerAddress(source);
+ address = resources.address(source);
const result = await resources.perform(address, cwd, literal, tool, signal);
const effect = computerEffect(result);
// Completion of the native request is separate from application-effect certainty.
const ok = !result.isError && ["delivered", "observed", "closed"].includes(result.details.status);
- const summary = presentComputerResult(result);
+ const summary = resources.shorten(presentComputerResult(result));
// Images of an action result, such as before/after crops of its pixel change, follow the summary for the model.
const images = result.content.filter((block): block is Extract<Content, { type: "image" }> => block.type === "image");
return { source, summary, ...(images.length ? { images } : {}), data: { kind: "computer-action", ok,
@@ -372,14 +373,20 @@ export async function performComputer(resources: ComputerResources, tool: "write
receipt: computerResultText(result),
...(!ok ? { error: { code: typeof result.details.state?.code === "string" ? result.details.state.code : `COMPUTER_${effect.toUpperCase().replace("-", "_")}`,
message: computerResultText(result) } } : {}) },
- script: { ...computerReceipt(source, action, { result, inputConsumed: !resources.grantsAuthority(address), text: summary }) } };
+ script: { ...shortReceipt(resources, computerReceipt(source, action, { result, inputConsumed: !resources.grantsAuthority(address), text: summary })) } };
} catch (error) {
- const message = error instanceof Error ? error.message : String(error);
+ const message = resources.shorten(error instanceof Error ? error.message : String(error));
return { source, summary: message, data: { kind: "computer-action", ok: false,
effect: error instanceof ComputerRequestError ? "not-applied" : "unknown", error: { message } },
- script: { ...computerReceipt(source, action, { error, inputConsumed: address ? !resources.grantsAuthority(address) : false }) } };
+ script: { ...shortReceipt(resources, computerReceipt(source, action, { error, inputConsumed: address ? !resources.grantsAuthority(address) : false })) } };
}
}
+/** A receipt whose window, sandbox and observation addresses are this run's short aliases. */
+function shortReceipt(resources: ComputerResources, receipt: ComputerReceipt): ComputerReceipt {
+ const short = (value: string | null | undefined) => value ? resources.shorten(value) : value;
+ return { ...receipt, window: short(receipt.window) ?? null, observation: short(receipt.observation) ?? null,
+ ...(receipt.sandbox ? { sandbox: short(receipt.sandbox)! } : {}), ...(receipt.reason ? { reason: resources.shorten(receipt.reason) } : {}), text: resources.shorten(receipt.text) };
+}
function nativeBlocks(body: string, result: ComputerResult | undefined, uiOnly: boolean): Content[] {
return [{ type: "text", text: body }, ...(uiOnly || !result ? [] : result.details.selected_frames
? result.content.slice(1) : result.content.filter(block => block.type === "image"))];
@@ -405,12 +412,12 @@ export async function registerComputerProvider(pi: ExtensionAPI, getSession: (cw
async tryResolve(source) {
if (!owns(source)) return { kind: "not-handled" };
try {
- const address = requireComputerAddress(source);
+ const address = resources.address(source);
return { kind: "resolved", resource: { source, skipPostEdit: true,
// An expired reference still resolves, so Write/Insert reach the handler and return a refused receipt.
read: async () => {
- try { return [{ type: "text", text: resources.descriptor(address) }]; }
- catch (error) { if (error instanceof ComputerRequestError) return [{ type: "text", text: `# Computer resource\nSource: ${source}\n${error.message}` }]; throw error; }
+ try { return [{ type: "text", text: resources.shorten(resources.descriptor(address)) }]; }
+ catch (error) { if (error instanceof ComputerRequestError) return [{ type: "text", text: resources.shorten(`# Computer resource\nSource: ${source}\n${error.message}`) }]; throw error; }
} } };
} catch (error) { return { kind: "failed", error }; }
},
@@ -440,11 +447,11 @@ export async function registerComputerProvider(pi: ExtensionAPI, getSession: (cw
try {
if (request.include !== undefined || request.exclude !== undefined || request.navigation !== undefined || request.caseSensitive || request.wholeWord)
throw new ComputerRequestError("Computer Search uses native discovery/UI text predicates, not file globs or symbol navigation.");
- const result = await resources.search(requireComputerAddress(request.path), context.cwd, request.query, request.limit, context.signal);
+ const result = await resources.search(resources.address(request.path), context.cwd, request.query, request.limit, context.signal);
return { kind: "resolved", payload: result };
} catch (error) { return { kind: "failed", error }; }
},
- format(payload) { const result = payload as ComputerResult; return { ...result, content: [{ type: "text", text: presentComputerResult(result) }] }; },
+ format(payload) { const result = payload as ComputerResult; return { ...result, content: [{ type: "text", text: resources.shorten(presentComputerResult(result)) }] }; },
toScriptData(payload) { return { kind: "custom", resolverId: "computer", value: (payload as ComputerResult).details }; },
} });
api.describe(COMPUTER_SEARCH_HELP);
diff --git a/src/short-addresses.ts b/src/short-addresses.ts
new file mode 100644
index 0000000..1918022
--- /dev/null
+++ b/src/short-addresses.ts
@@ -0,0 +1,57 @@
+import { randomInt } from "node:crypto";
+
+/** Address kinds that get a short form, by their one-letter prefix. Displays are a machine's listed displays. */
+const LETTERS = { window: "w", observation: "o", sequence: "s", "window-state": "t", app: "a", sandbox: "b", display: "d" } as const;
+export type ShortKind = keyof typeof LETTERS;
+const KINDS = Object.fromEntries(Object.entries(LETTERS).map(([kind, letter]) => [letter, kind])) as Record<string, ShortKind>;
+/** `<letter><number><run tag>`, for example w3qk. */
+export const SHORT_REFERENCE = /^([wostabd])([1-9][0-9]{0,6})([a-z]{2})$/;
+/** Long addresses this layer shortens in presented text: references, and a machine's listed displays. */
+const LONG = /computer:(window|observation|sequence|window-state|app|sandbox)\/([A-Za-z0-9_-]{1,160})|computer:machine\/([a-z0-9][a-z0-9_-]{0,63})\/display\/(d-[A-Za-z0-9_-]{1,158})/g;
+
+/**
+ * Short, session-local aliases of long computer addresses: `computer:<machine>/<letter><n><tag>`, numbered per
+ * machine and kind. The two-letter tag is drawn once per run, so an address kept from an earlier Pi run (in the
+ * conversation or a summary) is refused instead of reaching whatever window got the same number this time.
+ */
+export class ShortAddresses {
+ readonly tag = String.fromCharCode(97 + randomInt(26), 97 + randomInt(26));
+ private readonly short = new Map<string, string>();
+ private readonly long = new Map<string, string>();
+ private readonly counters = new Map<string, number>();
+
+ /** The short alias of a long address on a machine, issued on first use. */
+ alias(source: string, machine: string, kind: ShortKind): string {
+ let alias = this.short.get(source);
+ if (!alias) {
+ const key = `${machine}/${kind}`, n = (this.counters.get(key) ?? 0) + 1;
+ this.counters.set(key, n);
+ alias = `computer:${machine}/${LETTERS[kind]}${n}${this.tag}`;
+ this.short.set(source, alias); this.long.set(alias, source);
+ }
+ return alias;
+ }
+ /** The short alias already issued for a long address, if any. */
+ issued(source: string): string | undefined { return this.short.get(source); }
+
+ /** The long address of a short one, or a refusal that says why it does not resolve. */
+ resolve(machine: string, reference: string): string {
+ const match = SHORT_REFERENCE.exec(reference)!;
+ if (match[3] !== this.tag)
+ throw Error(`computer:${machine}/${reference} comes from an earlier Pi run or another session (this run's addresses end in "${this.tag}"). Search or Read again for a current address.`);
+ const source = this.long.get(`computer:${machine}/${reference}`);
+ if (!source) throw Error(`computer:${machine}/${reference} was never issued in this run. Search or Read again for a current address.`);
+ return source;
+ }
+
+ /** Replace every long address in a text with its short alias; `machineOf` names the machine of a long address. */
+ shorten(text: string, machineOf: (kind: Exclude<ShortKind, "display">, ref: string) => string | undefined): string {
+ return text.replace(LONG, (whole, kind: Exclude<ShortKind, "display"> | undefined, ref: string | undefined, displayMachine: string | undefined) => {
+ if (displayMachine) return this.alias(whole, displayMachine, "display");
+ const machine = machineOf(kind!, ref!);
+ return machine ? this.alias(whole, machine, kind!) : whole;
+ });
+ }
+ /** The kind a short reference names. */
+ static kind(reference: string): ShortKind { return KINDS[SHORT_REFERENCE.exec(reference)![1]]; }
+}
diff --git a/src/standalone-tools.ts b/src/standalone-tools.ts
index 6cd14b1..e460367 100644
--- a/src/standalone-tools.ts
+++ b/src/standalone-tools.ts
@@ -1,7 +1,7 @@
import { Type, type JsonValue } from "@earendil-works/pi-ai";
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
import { Text } from "@earendil-works/pi-tui";
-import { requireComputerAddress, type ComputerResources } from "./computer-resources.ts";
+import type { ComputerResources } from "./computer-resources.ts";
import { computerActionRenderer } from "./computer-action-renderer.ts";
import { computerReadRenderer } from "./computer-read-renderer.ts";
import {
@@ -68,8 +68,8 @@ export function registerStandaloneTools(pi: ExtensionAPI, resources: ComputerRes
annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false },
renderCall: args => new Text(`computer_search ${plain(args.path)} ${plain(JSON.stringify(args.query))}`, 0, 0),
async execute(_id, params, signal, _update, ctx) {
- const result = await resources.search(requireComputerAddress(params.path), ctx.cwd, params.query, params.limit, signal);
- return { content: [{ type: "text", text: presentComputerResult(result) }], details: result.details, ...(result.isError ? { isError: true } : {}) };
+ const result = await resources.search(resources.address(params.path), ctx.cwd, params.query, params.limit, signal);
+ return { content: [{ type: "text", text: resources.shorten(presentComputerResult(result)) }], details: result.details, ...(result.isError ? { isError: true } : {}) };
},
});
// Codemode scripts receive the receipt object for every outcome, so they branch on outcome without try/catch.
diff --git a/test/live/short-addresses.live.ts b/test/live/short-addresses.live.ts
new file mode 100644
index 0000000..88e40c6
--- /dev/null
+++ b/test/live/short-addresses.live.ts
@@ -0,0 +1,38 @@
+import { afterAll, expect, test } from "vitest";
+import { performComputer, readComputer } from "../../src/provider.ts";
+import { connectLive, nativeForm, openWindow, WINDOWS_POWERSHELL_PATH } from "./remote.ts";
+
+// LPT-932: on a configured machine, results show short addresses with the machine, and a named window is used by name.
+const live = await connectLive();
+const name = process.env.LIVE_MACHINE ?? "lab";
+afterAll(() => live.close());
+const read = async (source: string, views?: string[]) => {
+ const result = await readComputer(live.resources, source, live.cwd, { views }, false);
+ return result.content[0].type === "text" ? result.content[0].text : "";
+};
+const insert = (source: string, command: unknown) => performComputer(live.resources, "insert", source, { path: source, text: JSON.stringify(command) }, live.cwd);
+
+test("a window is read and acted on by its short address and by a name, and the name ends with the window", async () => {
+ const title = `pi-short-${Date.now()}`;
+ const long = await openWindow(live, live.machine, WINDOWS_POWERSHELL_PATH, nativeForm(title), title);
+ const named = await insert(live.machine, { action: "name", as: "form", title });
+ expect(named.script.outcome, named.summary).toBe("delivered");
+ const short = named.script.window as string;
+ expect(short).toMatch(new RegExp(`^computer:${name}/w\\d+[a-z]{2}$`));
+ const view = await read(short, ["ui"]);
+ expect(view).toMatch(new RegExp(`^Computer observed \\(yolo\\) on ${name}\\nWindow: ${short}\\nObservation: computer:${name}/o\\d+[a-z]{2}$`, "m"));
+ expect(view).not.toMatch(/computer:(window|observation)\/[wd0-9a-f-]{8}/);
+ // Act by name: a locator click on the form's counter button.
+ const clicked = await insert("computer:form", { action: "click", target: "getByRole('button', { name: 'Count 0' })" });
+ expect(clicked.script.outcome, clicked.summary).toBe("delivered");
+ expect(await read("computer:form", ["ui"])).toContain("Count 1");
+ expect(await read("computer:session")).toMatch(new RegExp(`computer:form → ${short} \\| ${title}`));
+ // Closing the window ends the name once a full listing shows it gone.
+ const state = await live.read(long, ["state"]);
+ await live.closeWindow((state.details.target as { window_id: number }).window_id);
+ for (let i = 0; i < 20 && ((await live.search(live.windows, title)).details.state?.windows as unknown[] | undefined)?.length; i++) await new Promise(resolve => setTimeout(resolve, 500));
+ await live.search(live.windows, "");
+ const gone = await insert("computer:form", { action: "click", target: "getByRole('button')" });
+ expect(gone.script.outcome).toBe("refused");
+ expect(gone.summary).toMatch(/No window is named form/);
+});
diff --git a/test/short-addresses.test.ts b/test/short-addresses.test.ts
new file mode 100644
index 0000000..426c6f7
--- /dev/null
+++ b/test/short-addresses.test.ts
@@ -0,0 +1,107 @@
+import { expect, test, vi } from "vitest";
+import { computerSource } from "../src/computer-address.ts";
+import { ComputerRequestError, ComputerResources, type OpenedMachine } from "../src/computer-resources.ts";
+import { loadComputerConfig } from "../src/config.ts";
+import { performComputer, readComputer } from "../src/provider.ts";
+import { ShortAddresses } from "../src/short-addresses.ts";
+import { ComputerSession, type Driver } from "../src/session.ts";
+import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+const cwd = "/synthetic-short-addresses";
+
+/** A native backend with two windows (titles "Game" and "Game settings"); either can be closed. */
+function backend(pid: number) {
+ const open = new Set([7, 8]);
+ const driver: Driver = {
+ identity: vi.fn(async (target: { window_id: number }) => open.has(target.window_id) ? `life-${pid}-${target.window_id}` : undefined) as Driver["identity"],
+ close: vi.fn(async () => {}),
+ call: vi.fn<Driver["call"]>(async (name, args) => {
+ if (name === "list_windows") return { content: [], structuredContent: { windows: [...open].map(id => ({ pid, window_id: id, title: id === 7 ? "Game" : "Game settings" })) } };
+ if (name === "get_window_state") return { content: [], structuredContent: { pid, window_id: (args as { window_id: number }).window_id, snapshot_id: "s", elements_complete: true, elements: [],
+ ...((args as { include_screenshot?: boolean }).include_screenshot !== false ? { screenshot_error: "No surface." } : {}), window_bounds: { x: 0, y: 0, width: 100, height: 80 } } };
+ throw new Error(`Unexpected native call ${name}`);
+ }),
+ };
+ return { driver, close: (id: number) => open.delete(id) };
+}
+
+function fixture() {
+ const host = backend(10), remote = backend(20);
+ const hostSession = new ComputerSession(host.driver, () => "yolo"), remoteSession = new ComputerSession(remote.driver, () => "yolo");
+ const machine: OpenedMachine = { ref: "lab", session: remoteSession, describe: source => source, close: () => remoteSession.close() };
+ const resources = new ComputerResources(async () => hostSession, async () => hostSession.close(), undefined, async () => machine);
+ const search = async (source: string, query = "") => (await resources.search(resources.address(source), cwd, query)).details.state!.windows as { window_ref: string; title: string }[];
+ const insert = (source: string, command: unknown) => performComputer(resources, "insert", source, { path: source, text: JSON.stringify(command) }, cwd);
+ const read = (source: string, views?: string[]) => readComputer(resources, source, cwd, { views }, false);
+ const text = (read: Awaited<ReturnType<typeof readComputer>>) => read.content[0].type === "text" ? read.content[0].text : "";
+ return { resources, host, remote, search, insert, read, text };
+}
+
+// LPT-932: the agent sees short addresses with the machine and a run tag, and can name windows.
+test("presented addresses are short, per machine and kind, and resolve back to the long ones", async () => {
+ const f = fixture();
+ const [game] = await f.search("computer:machine/lab/windows", "Game");
+ const tag = (f.resources as unknown as { shorts: ShortAddresses }).shorts.tag;
+ // Search output lists each window by its short address.
+ const listed = await f.read("computer:session");
+ expect(f.text(listed)).not.toContain("computer:window/");
+ const view = await f.read(computerSource("window", game.window_ref), ["ui"]);
+ const body = f.text(view);
+ expect(body).toMatch(new RegExp(`^Computer observed \\(yolo\\) on lab\\nWindow: computer:lab/w1${tag}\\nObservation: computer:lab/o1${tag}$`, "m"));
+ expect(body).not.toMatch(/computer:(window|observation)\//);
+ expect(f.resources.address(`computer:lab/w1${tag}`)).toMatchObject({ kind: "window", ref: game.window_ref });
+ // An observation alias keeps the long form's input options.
+ expect(f.resources.address(`computer:lab/o1${tag}?delivery=foreground`)).toMatchObject({ kind: "observation", ref: view.details.computer!.observation_id, delivery: "foreground" });
+ // The short address works for Read; long addresses still work too.
+ expect(f.text(await f.read(`computer:lab/w1${tag}`, ["ui"]))).toContain(`Observation: computer:lab/o2${tag}`);
+ // Receipts for scripts carry the short addresses as well.
+ const receipt = await f.insert(`computer:lab/w1${tag}`, { action: "name", as: "game" });
+ expect(receipt.script).toMatchObject({ outcome: "delivered", window: `computer:lab/w1${tag}` });
+});
+
+test("an alias from another run, or one never issued, refuses with the reason", () => {
+ const f = fixture();
+ const tag = (f.resources as unknown as { shorts: ShortAddresses }).shorts.tag;
+ const other = tag === "zz" ? "zy" : "zz";
+ expect(() => f.resources.address(`computer:lab/w1${other}`)).toThrow(new RegExp(`earlier Pi run.*end in "${tag}"`));
+ expect(() => f.resources.address(`computer:lab/w9${tag}`)).toThrow(/never issued in this run/);
+ expect(() => f.resources.address(`computer:lab/w1${other}`)).toThrow(ComputerRequestError);
+});
+
+test("names resolve to their window, are unique while the window lives, and stop when it closes", async () => {
+ const f = fixture();
+ const [game] = await f.search("computer:machine/lab/windows", "regex:^Game$");
+ const named = await f.insert(computerSource("window", game.window_ref), { action: "name", as: "game" });
+ expect(named.summary).toMatch(/computer:game now names computer:lab\/w1\w\w \(Game\)/);
+ expect(f.resources.address("computer:game")).toMatchObject({ kind: "window", ref: game.window_ref });
+ expect(f.text(await f.read("computer:game", ["ui"]))).toMatch(/^Computer observed \(yolo\) on lab/);
+ // Several windows match a title: the name command lists them instead of choosing.
+ const several = await f.insert("computer:machine/lab", { action: "name", as: "settings", title: "Game" });
+ expect(several.script.outcome).toBe("refused");
+ expect(several.summary).toMatch(/2 windows match "Game"[\s\S]*computer:lab\/w1\w\w \| Game\n- computer:lab\/w2\w\w \| Game settings/);
+ const settings = await f.insert("computer:machine/lab", { action: "name", as: "settings", title: "settings" });
+ expect(settings.script.outcome).toBe("delivered");
+ // A live window's name is not taken over; bad names refuse.
+ expect((await f.insert("computer:settings", { action: "name", as: "game" })).summary).toMatch(/computer:game already names computer:lab\/w1\w\w \(Game\)/);
+ for (const bad of ["window", "lab", "Game", "9x", "a b"]) expect((await f.insert("computer:game", { action: "name", as: bad })).script.outcome).toBe("refused");
+ const session = f.text(await f.read("computer:session"));
+ expect(session).toMatch(/Window names[\s\S]*- computer:game → computer:lab\/w1\w\w \| Game\n- computer:settings → computer:lab\/w2\w\w \| Game settings/);
+ // The window closes: its name disappears from the list and refuses.
+ f.remote.close(7);
+ await f.search("computer:machine/lab/windows");
+ expect(f.text(await f.read("computer:session"))).not.toContain("computer:game →");
+ expect(() => f.resources.address("computer:game")).toThrow(/No window is named game/);
+ expect(() => f.resources.address("computer:nothing")).toThrow(/No window is named nothing/);
+ expect(() => f.resources.address("computer:settings?delivery=foreground")).toThrow(/takes no options/);
+});
+
+test("machine names never take an address kind word", async () => {
+ const dir = await mkdtemp(path.join(tmpdir(), "pi-machines-"));
+ await mkdir(path.join(dir, ".pi"));
+ for (const name of ["window", "session", "display", "machine"]) {
+ await writeFile(path.join(dir, ".pi/computer-use.json"), JSON.stringify({ command: "/x/cua-driver.exe", machines: { [name]: { ssh: "a", command: "/x" } } }));
+ await expect(loadComputerConfig(dir)).rejects.toThrow(/Invalid machines/);
+ }
+});