webhand 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,331 @@
1
+ /**
2
+ * A Chrome that outlives each CLI call, plus the run state that must survive between calls.
3
+ *
4
+ * Two kinds of profile:
5
+ * - new: a temporary folder, deleted when the run ends. Nothing is signed in.
6
+ * - profile:NAME: a saved webhand profile. A person signs in once with `profile login`, and later
7
+ * runs reuse that sign-in. It is never the person's everyday Chrome profile.
8
+ *
9
+ * On WSL, Chrome can be the Windows one. It is reachable only with mirrored networking, because
10
+ * Chrome serves its debugging port on the Windows loopback.
11
+ */
12
+ import { execFileSync, spawn } from "node:child_process";
13
+ import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, } from "node:fs";
14
+ import { tmpdir } from "node:os";
15
+ import { delimiter, join } from "node:path";
16
+ import { chromium } from "playwright-core";
17
+ import { pyRepr, sleep } from "./py.js";
18
+ import * as workspace from "./workspace.js";
19
+ const STARTUP_MS = 15_000;
20
+ const PROFILE_NAME = /^[\p{L}\p{N}_-]+$/u;
21
+ export const CHROMES = ["auto", "linux", "windows"];
22
+ const WINDOWS_CHROME = [
23
+ "/mnt/c/Program Files/Google/Chrome/Application/chrome.exe",
24
+ "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",
25
+ ];
26
+ /** Chrome cannot be started as asked. */
27
+ export class SessionError extends Error {
28
+ name = "SessionError";
29
+ }
30
+ export function home() {
31
+ return join(workspace.home(), "state");
32
+ }
33
+ function path() {
34
+ return join(home(), "session.json");
35
+ }
36
+ export function load() {
37
+ return existsSync(path()) ? JSON.parse(readFileSync(path(), "utf8")) : null;
38
+ }
39
+ export function save(state) {
40
+ mkdirSync(home(), { recursive: true });
41
+ const temporary = join(home(), "session.tmp");
42
+ writeFileSync(temporary, JSON.stringify(state), { encoding: "utf8", mode: 0o600 });
43
+ renameSync(temporary, path());
44
+ }
45
+ export function clear() {
46
+ rmSync(path(), { force: true });
47
+ }
48
+ /** 'new' gives null; 'profile:NAME' gives NAME. */
49
+ export function parseSession(spec) {
50
+ if (spec === "new")
51
+ return null;
52
+ const at = spec.indexOf(":");
53
+ const kind = at < 0 ? spec : spec.slice(0, at);
54
+ const name = at < 0 ? "" : spec.slice(at + 1);
55
+ if (kind !== "profile" || !PROFILE_NAME.test(name)) {
56
+ throw new SessionError(`Expected --session new or profile:NAME, got ${pyRepr(spec)}`);
57
+ }
58
+ return name;
59
+ }
60
+ // --- Windows Chrome from WSL ---------------------------------------------------------------
61
+ function isFile(file) {
62
+ try {
63
+ return statSync(file).isFile();
64
+ }
65
+ catch {
66
+ return false;
67
+ }
68
+ }
69
+ function run(command, args, options = {}) {
70
+ return execFileSync(command, args, { ...options, stdio: ["ignore", "pipe", "ignore"] })
71
+ .toString()
72
+ .trim();
73
+ }
74
+ /** What the host looks like. Tests replace these. */
75
+ export const probes = {
76
+ onWsl() {
77
+ return Boolean(process.env.WSL_INTEROP) || existsSync("/proc/sys/fs/binfmt_misc/WSLInterop");
78
+ },
79
+ windowsChrome() {
80
+ return WINDOWS_CHROME.find(isFile) ?? null;
81
+ },
82
+ networkingMode() {
83
+ try {
84
+ return run("wslinfo", ["--networking-mode"], { timeout: 5000 }) || null;
85
+ }
86
+ catch {
87
+ return null;
88
+ }
89
+ },
90
+ toWindows(path) {
91
+ return run("wslpath", ["-w", path]);
92
+ },
93
+ };
94
+ function windowsLocalAppData() {
95
+ let folder = "";
96
+ try {
97
+ folder = run("cmd.exe", ["/c", "echo %LOCALAPPDATA%"], { cwd: "/mnt/c", timeout: 10_000 });
98
+ }
99
+ catch {
100
+ folder = "";
101
+ }
102
+ if (!folder || folder.includes("%"))
103
+ throw new SessionError("Could not read %LOCALAPPDATA% from Windows");
104
+ return run("wslpath", ["-u", folder]);
105
+ }
106
+ /** Returns ['linux' or 'windows', a note for the person when auto fell back]. */
107
+ export function chooseChrome(choice) {
108
+ if (!CHROMES.includes(choice))
109
+ throw new SessionError(`Unknown --chrome ${pyRepr(choice)}`);
110
+ if (choice === "linux")
111
+ return ["linux", null];
112
+ let reason = null;
113
+ if (!probes.onWsl())
114
+ reason = "not running on WSL";
115
+ else if (!probes.windowsChrome())
116
+ reason = "chrome.exe was not found on Windows";
117
+ else if (probes.networkingMode() !== "mirrored") {
118
+ reason =
119
+ "WSL networking is not mirrored, so the Windows Chrome debugging port is unreachable. " +
120
+ "Add networkingMode=mirrored under [wsl2] in %USERPROFILE%\\.wslconfig and run wsl --shutdown";
121
+ }
122
+ if (reason === null)
123
+ return ["windows", null];
124
+ if (choice === "windows")
125
+ throw new SessionError(`Cannot use the Windows Chrome: ${reason}`);
126
+ return ["linux", `Using the Linux Chrome: ${reason}`];
127
+ }
128
+ function profilesRoot(chrome) {
129
+ if (chrome === "windows")
130
+ return join(windowsLocalAppData(), "webhand", "profiles");
131
+ return join(home(), "profiles");
132
+ }
133
+ export function profileDir(chrome, name) {
134
+ if (!PROFILE_NAME.test(name))
135
+ throw new SessionError(`Invalid profile name: ${pyRepr(name)}`);
136
+ return join(profilesRoot(chrome), name);
137
+ }
138
+ export function listProfiles(chrome) {
139
+ const root = profilesRoot(chrome);
140
+ if (!existsSync(root))
141
+ return [];
142
+ return readdirSync(root, { withFileTypes: true })
143
+ .filter((entry) => entry.isDirectory())
144
+ .map((entry) => entry.name)
145
+ .sort();
146
+ }
147
+ /** A local file under WSL must be addressed through \\wsl.localhost for the Windows Chrome. */
148
+ export function browserUrl(url, chrome) {
149
+ if (chrome !== "windows" || !url.startsWith("file:///"))
150
+ return url;
151
+ const rest = url.slice("file://".length);
152
+ const at = rest.indexOf("?");
153
+ const local = at < 0 ? rest : rest.slice(0, at);
154
+ const query = at < 0 ? "" : rest.slice(at + 1);
155
+ const unc = probes.toWindows(local).replaceAll("\\", "/"); // //wsl.localhost/Ubuntu/...
156
+ return `file:${unc}${query ? `?${query}` : ""}`;
157
+ }
158
+ // --- Start and stop ------------------------------------------------------------------------
159
+ export function chromeArgs(executable, userDataDir, options) {
160
+ const args = [
161
+ executable,
162
+ "--remote-debugging-port=0",
163
+ `--user-data-dir=${userDataDir}`,
164
+ "--no-first-run",
165
+ "--no-default-browser-check",
166
+ "--hide-crash-restore-bubble",
167
+ "--window-size=1120,867", // The browser UI takes 87px; the page viewport is 1120x780.
168
+ "about:blank",
169
+ ];
170
+ if (!options.headed)
171
+ args.splice(1, 0, "--headless=new");
172
+ return args;
173
+ }
174
+ async function reachable(port) {
175
+ try {
176
+ const response = await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(2000) });
177
+ await response.body?.cancel();
178
+ return response.ok;
179
+ }
180
+ catch {
181
+ return false;
182
+ }
183
+ }
184
+ function which(command) {
185
+ for (const dir of (process.env.PATH ?? "").split(delimiter)) {
186
+ const file = join(dir, command);
187
+ if (dir && isFile(file))
188
+ return file;
189
+ }
190
+ return null;
191
+ }
192
+ /** Chrome processes this process started. Only these can be watched for exit directly. */
193
+ const children = new Map();
194
+ function childExited(pid) {
195
+ const child = children.get(pid);
196
+ if (!child)
197
+ return null;
198
+ return child.exitCode !== null || child.signalCode !== null;
199
+ }
200
+ /** profile=null makes a new temporary folder. A saved profile is kept when the run ends. */
201
+ export async function startChrome(options = {}) {
202
+ const headed = options.headed ?? false;
203
+ const profile = options.profile ?? null;
204
+ const chrome = options.chrome ?? "linux";
205
+ let executable;
206
+ if (chrome === "windows") {
207
+ executable = probes.windowsChrome();
208
+ if (!executable)
209
+ throw new SessionError("chrome.exe was not found on Windows");
210
+ }
211
+ else {
212
+ executable = which("google-chrome");
213
+ if (!executable)
214
+ throw new SessionError("google-chrome was not found");
215
+ }
216
+ let folder;
217
+ if (profile) {
218
+ folder = profileDir(chrome, profile);
219
+ mkdirSync(folder, { recursive: true });
220
+ rmSync(join(folder, "DevToolsActivePort"), { force: true });
221
+ }
222
+ else if (chrome === "windows") {
223
+ const temporary = join(windowsLocalAppData(), "webhand", "tmp");
224
+ mkdirSync(temporary, { recursive: true });
225
+ folder = mkdtempSync(join(temporary, "webhand-"));
226
+ }
227
+ else {
228
+ folder = mkdtempSync(join(tmpdir(), "webhand-"));
229
+ }
230
+ const userDataDir = chrome === "windows" ? probes.toWindows(folder) : folder;
231
+ const [command, ...args] = chromeArgs(executable, userDataDir, { headed });
232
+ const child = spawn(command, args, {
233
+ detached: true, // its own process group, so it outlives this CLI call and stops as a group
234
+ stdio: "ignore",
235
+ cwd: chrome === "windows" ? "/mnt/c" : undefined,
236
+ });
237
+ child.on("error", () => { });
238
+ child.unref();
239
+ const pid = child.pid;
240
+ children.set(pid, child);
241
+ const state = { pid, profile: folder, saved_profile: profile, chrome, headed };
242
+ const portFile = join(folder, "DevToolsActivePort");
243
+ const deadline = performance.now() + STARTUP_MS;
244
+ while (performance.now() < deadline) {
245
+ if (childExited(pid) && chrome === "linux")
246
+ break;
247
+ const text = isFile(portFile) ? readFileSync(portFile, "utf8") : "";
248
+ if (text.trim()) {
249
+ state.port = Number.parseInt(text.split(/\s/)[0], 10);
250
+ if (chrome === "linux" || (await reachable(state.port)))
251
+ return state;
252
+ }
253
+ await sleep(50);
254
+ }
255
+ await stopChrome(state);
256
+ if (profile && childExited(pid)) {
257
+ throw new SessionError(`Chrome exited at once. Is profile ${pyRepr(profile)} open in another Chrome window?`);
258
+ }
259
+ throw new SessionError("Chrome did not open a reachable debugging port");
260
+ }
261
+ /** The only way to close the Windows Chrome: the WSL pid is just the interop proxy. */
262
+ async function closeOverCdp(port) {
263
+ try {
264
+ const browser = await chromium.connectOverCDP(`http://127.0.0.1:${port}`, { timeout: 5000 });
265
+ try {
266
+ const cdp = await browser.newBrowserCDPSession();
267
+ await cdp.send("Browser.close").catch(() => { });
268
+ }
269
+ finally {
270
+ await browser.close().catch(() => { });
271
+ }
272
+ return true;
273
+ }
274
+ catch {
275
+ return false;
276
+ }
277
+ }
278
+ export async function stopChrome(state) {
279
+ // A saved profile closes over CDP too, so Chrome writes its cookies before it exits.
280
+ if ((state.chrome === "windows" || state.saved_profile) && state.port) {
281
+ if (await closeOverCdp(state.port))
282
+ await exited(state.pid, 10_000); // Let Chrome finish writing first.
283
+ }
284
+ try {
285
+ process.kill(-state.pid, "SIGTERM");
286
+ }
287
+ catch {
288
+ // Already gone.
289
+ }
290
+ await exited(state.pid, state.chrome === "windows" ? 5000 : 2000);
291
+ if (!state.saved_profile)
292
+ rmSync(state.profile, { recursive: true, force: true });
293
+ }
294
+ function alive(pid) {
295
+ const own = childExited(pid);
296
+ if (own !== null)
297
+ return !own;
298
+ try {
299
+ process.kill(pid, 0);
300
+ return true;
301
+ }
302
+ catch (error) {
303
+ return error.code === "EPERM";
304
+ }
305
+ }
306
+ async function exited(pid, ms) {
307
+ const deadline = performance.now() + ms;
308
+ while (performance.now() < deadline) {
309
+ if (!alive(pid))
310
+ return true;
311
+ await sleep(50);
312
+ }
313
+ return false;
314
+ }
315
+ /** For `profile login`: returns when the person closes the window, or until() is true. */
316
+ export async function waitUntilClosed(state, until) {
317
+ while (!until()) {
318
+ if (state.chrome === "windows") {
319
+ if (!(await reachable(state.port)))
320
+ return;
321
+ }
322
+ else if (childExited(state.pid) !== false) {
323
+ return;
324
+ }
325
+ await sleep(500);
326
+ }
327
+ }
328
+ /** Removes a saved profile folder. */
329
+ export function deleteProfile(folder) {
330
+ rmSync(folder, { recursive: true, force: false });
331
+ }
package/dist/tasks.js ADDED
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Research tasks: a fixed goal and an independent verify(). They live in the research repository's
3
+ * tasks/ folder, are never shipped in the package, and are the only evidence of success in experiments.
4
+ */
5
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
6
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
7
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
8
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
9
+ });
10
+ }
11
+ return path;
12
+ };
13
+ import { existsSync } from "node:fs";
14
+ import { join } from "node:path";
15
+ import { pathToFileURL } from "node:url";
16
+ /** The task cannot be loaded. */
17
+ export class TaskError extends Error {
18
+ name = "TaskError";
19
+ }
20
+ export async function loadTask(name, root = process.cwd()) {
21
+ if (!/^[\p{L}\p{N}_-]+$/u.test(name))
22
+ throw new TaskError(`Unknown task: ${name}`);
23
+ const file = join(root, "tasks", `${name}.ts`);
24
+ if (!existsSync(file)) {
25
+ if (!existsSync(join(root, "tasks"))) {
26
+ throw new TaskError(`Unknown task: ${name}. Tasks are for the research repository; run from its root`);
27
+ }
28
+ throw new TaskError(`Unknown task: ${name}`);
29
+ }
30
+ try {
31
+ return (await import(__rewriteRelativeImportExtension(pathToFileURL(file).href)));
32
+ }
33
+ catch (error) {
34
+ const message = error instanceof Error ? error.message : String(error);
35
+ throw new TaskError(`Could not load task ${name} (TypeScript tasks need Node 22.18 or later): ${message}`);
36
+ }
37
+ }
package/dist/types.js ADDED
@@ -0,0 +1,34 @@
1
+ /** Shared data shapes. Pages and actions are the plain objects produced by snapshot.js. */
2
+ /** The model gave no usable decision. Nothing was executed. */
3
+ export class PolicyError extends Error {
4
+ name = "PolicyError";
5
+ }
6
+ /** A decision no longer refers to the observed page. Nothing was executed. */
7
+ export class StalePage extends Error {
8
+ name = "StalePage";
9
+ }
10
+ /** A browser mutation may have happened. It must never be retried. */
11
+ export class MutationUncertain extends Error {
12
+ name = "MutationUncertain";
13
+ }
14
+ export function modelCall(provider, model, purpose, latency_ms, input_tokens = null, output_tokens = null) {
15
+ return { provider, model, purpose, latency_ms, input_tokens, output_tokens };
16
+ }
17
+ export class Decision {
18
+ operation;
19
+ /** null only for DONE, NEEDS_HUMAN, BLOCKED, and NOT_VISIBLE */
20
+ action;
21
+ /** Lowest confidence behind this choice, when the chooser reports one */
22
+ confidence;
23
+ /** For TYPE_TEXT: one of Claude's values, never model-written. null: no value fits */
24
+ text;
25
+ /** For NOT_VISIBLE: the operation whose target was not observed */
26
+ wanted;
27
+ constructor(operation, action = null, options = {}) {
28
+ this.operation = operation;
29
+ this.action = action;
30
+ this.confidence = options.confidence ?? null;
31
+ this.text = options.text ?? null;
32
+ this.wanted = options.wanted ?? null;
33
+ }
34
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Where webhand keeps what it learns and does, like Claude Code's ~/.claude and .claude:
3
+ *
4
+ * user $WEBHAND_HOME, or ~/.webhand
5
+ * runbooks/ service information and runbooks for every project
6
+ * runs/ run logs, which hold page text
7
+ * state/ the active session and saved profiles
8
+ * project the nearest .webhand/ from the current directory up
9
+ * runbooks/ service information and runbooks for this project; they win over the user's
10
+ *
11
+ * Sign-ins and logs never go into a project. The Jev key comes only from the environment (TYPESAFE_API_KEY).
12
+ */
13
+ import { execFileSync } from "node:child_process";
14
+ import { statSync } from "node:fs";
15
+ import { homedir } from "node:os";
16
+ import { dirname, join, resolve } from "node:path";
17
+ const FOLDER = ".webhand";
18
+ function expandUser(path) {
19
+ if (path === "~")
20
+ return homedir();
21
+ if (path.startsWith("~/"))
22
+ return join(homedir(), path.slice(2));
23
+ return path;
24
+ }
25
+ /** The user's folder: $WEBHAND_HOME, or ~/.webhand. */
26
+ export function home() {
27
+ return resolve(expandUser(process.env.WEBHAND_HOME || join(homedir(), FOLDER)));
28
+ }
29
+ function isDir(path) {
30
+ try {
31
+ return statSync(path).isDirectory();
32
+ }
33
+ catch {
34
+ return false;
35
+ }
36
+ }
37
+ /** The nearest existing .webhand/ from cwd up, stopping at the home directory. null when there is none. */
38
+ export function projectRoot(cwd = process.cwd()) {
39
+ const stop = homedir();
40
+ const user = home();
41
+ let dir = resolve(cwd);
42
+ while (dir !== stop) {
43
+ const candidate = join(dir, FOLDER);
44
+ if (candidate !== user && isDir(candidate))
45
+ return candidate;
46
+ const parent = dirname(dir);
47
+ if (parent === dir)
48
+ break;
49
+ dir = parent;
50
+ }
51
+ return null;
52
+ }
53
+ function gitRoot(cwd) {
54
+ try {
55
+ const out = execFileSync("git", ["rev-parse", "--show-toplevel"], { cwd, stdio: ["ignore", "pipe", "ignore"] });
56
+ return out.toString().trim() || null;
57
+ }
58
+ catch {
59
+ return null;
60
+ }
61
+ }
62
+ /** Where a project's .webhand/ is or will be: the nearest one, else the git root's, else the cwd's. */
63
+ export function projectWriteRoot(cwd = process.cwd()) {
64
+ return projectRoot(cwd) ?? join(gitRoot(cwd) ?? resolve(cwd), FOLDER);
65
+ }
66
+ /** The folder for a scope, whether or not it exists yet. */
67
+ export function scopeRoot(scope) {
68
+ return scope === "user" ? home() : projectWriteRoot();
69
+ }
70
+ /** Existing scopes to read, project first. */
71
+ export function roots() {
72
+ const found = [];
73
+ const project = projectRoot();
74
+ if (project)
75
+ found.push({ scope: "project", dir: project });
76
+ found.push({ scope: "user", dir: home() });
77
+ return found;
78
+ }
package/package.json CHANGED
@@ -1,6 +1,59 @@
1
1
  {
2
2
  "name": "webhand",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Claude plans, asks, checks, and replans; Jev operates the browser toward the goal.",
5
+ "license": "MIT",
6
+ "author": "sakamoto66",
7
+ "homepage": "https://github.com/sakamoto66/webhand",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/sakamoto66/webhand.git"
11
+ },
12
+ "keywords": [
13
+ "browser",
14
+ "agent",
15
+ "automation",
16
+ "runbook",
17
+ "claude-code"
18
+ ],
19
+ "type": "module",
20
+ "bin": {
21
+ "webhand": "dist/bin.js"
22
+ },
23
+ "files": [
24
+ "dist",
25
+ "assets",
26
+ "LICENSE",
27
+ "THIRD_PARTY_LICENSE_jev-ultrafast.txt",
28
+ "README.md"
29
+ ],
30
+ "engines": {
31
+ "node": ">=22"
32
+ },
33
+ "scripts": {
34
+ "build": "tsc -p tsconfig.build.json",
35
+ "lint": "biome check .",
36
+ "typecheck": "tsc --noEmit",
37
+ "knip": "knip",
38
+ "check": "npm run lint && npm run typecheck && npm run knip",
39
+ "test": "vitest run",
40
+ "test:coverage": "vitest run --coverage",
41
+ "smoke": "node src/run.ts",
42
+ "prepare": "husky",
43
+ "prepublishOnly": "npm run check && npm run build"
44
+ },
45
+ "dependencies": {
46
+ "playwright-core": "~1.64.1",
47
+ "smol-toml": "^1.9.1",
48
+ "undici": "^8.12.3"
49
+ },
50
+ "devDependencies": {
51
+ "@biomejs/biome": "^2.6.4",
52
+ "@types/node": "^24.19.2",
53
+ "@vitest/coverage-v8": "^5.1.0",
54
+ "husky": "^9.1.7",
55
+ "knip": "^6.44.1",
56
+ "typescript": "^7.0.2",
57
+ "vitest": "^5.1.0"
58
+ }
59
+ }