webhand 0.0.0-stage → 0.3.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,296 @@
1
+ /**
2
+ * What webhand has learned: service information and reviewed procedures (runbooks).
3
+ *
4
+ * Both guide Claude's plan and Jev's choices. Procedures are never replayed. They live in the project's
5
+ * .webhand/runbooks and the user's ~/.webhand/runbooks; a project file wins over a user file of the same name.
6
+ */
7
+ import { createHash } from "node:crypto";
8
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
9
+ import { dirname, join, resolve } from "node:path";
10
+ import { pathToFileURL } from "node:url";
11
+ import { parse } from "smol-toml";
12
+ import { quote, show } from "./format.js";
13
+ import { roots, scopeRoot } from "./workspace.js";
14
+ const WORD = "[\\p{L}\\p{N}_-]+";
15
+ const NAME = new RegExp(`^${WORD}(/${WORD})?$`, "u");
16
+ const SERVICE_NAME = new RegExp(`^${WORD}$`, "u");
17
+ const PARAM = /\{([A-Za-z_][\p{L}\p{N}_]*)\}/gu;
18
+ const ACTORS = new Set(["jev", "human"]);
19
+ const STATUSES = new Set(["draft", "approved"]);
20
+ const DEFAULTS = new Set(["focus", "skip"]); // A region's default in service.toml. Without one, it is observed as usual.
21
+ const SERVICE_FILE = "service"; // runbooks/<service>/service.toml holds the service information.
22
+ /** The runbook folder of a scope, whether or not it exists. */
23
+ export function root(scope = "project") {
24
+ return join(scopeRoot(scope), "runbooks");
25
+ }
26
+ /** Runbook folders that exist or may exist, project first. */
27
+ function folders() {
28
+ return roots().map(({ scope, dir }) => ({ scope, dir: join(dir, "runbooks") }));
29
+ }
30
+ /** The runbook cannot be used as written. */
31
+ export class RunbookError extends Error {
32
+ name = "RunbookError";
33
+ }
34
+ /** Checks a runbook name such as hotel/filter. */
35
+ function checkName(name) {
36
+ if (!NAME.test(name) || name.split("/").at(-1) === SERVICE_FILE) {
37
+ throw new RunbookError(`Invalid runbook name: ${quote(name)}`);
38
+ }
39
+ return name;
40
+ }
41
+ function checkService(service) {
42
+ if (!SERVICE_NAME.test(service))
43
+ throw new RunbookError(`Invalid service name: ${quote(service)}`);
44
+ return service;
45
+ }
46
+ /** Where a runbook of a scope is written. */
47
+ export function path(name, scope = "project") {
48
+ return join(root(scope), `${checkName(name)}.toml`);
49
+ }
50
+ /** Where a service's information of a scope is written. */
51
+ export function servicePath(service, scope = "project") {
52
+ return join(root(scope), checkService(service), `${SERVICE_FILE}.toml`);
53
+ }
54
+ function isFile(file) {
55
+ try {
56
+ return statSync(file).isFile();
57
+ }
58
+ catch {
59
+ return false;
60
+ }
61
+ }
62
+ /** The file that is read for a relative name: the project's if it has one, else the user's. */
63
+ function find(relative) {
64
+ for (const { scope, dir } of folders()) {
65
+ const file = join(dir, relative);
66
+ if (isFile(file))
67
+ return { file, scope, base: dirname(dirname(dir)) };
68
+ }
69
+ return null;
70
+ }
71
+ function findRunbook(name) {
72
+ return find(`${checkName(name)}.toml`);
73
+ }
74
+ function findService(service) {
75
+ return find(join(checkService(service), `${SERVICE_FILE}.toml`));
76
+ }
77
+ function readToml(file) {
78
+ const raw = readFileSync(file);
79
+ try {
80
+ return { raw, data: parse(new TextDecoder("utf-8", { fatal: true }).decode(raw)) };
81
+ }
82
+ catch (error) {
83
+ throw new RunbookError(`${file}: ${error instanceof Error ? error.message : String(error)}`);
84
+ }
85
+ }
86
+ /** Missing, false, zero, or an empty string, list, or table. */
87
+ function blank(value) {
88
+ if (value === null || value === undefined || value === false || value === 0 || value === "")
89
+ return true;
90
+ if (Array.isArray(value))
91
+ return value.length === 0;
92
+ if (typeof value === "object")
93
+ return Object.keys(value).length === 0;
94
+ return false;
95
+ }
96
+ const get = (doc, key, fallback = undefined) => (key in doc ? doc[key] : fallback);
97
+ /** Region patterns, such as "main/form:宿泊予約" or "footer". Anything else is an error. */
98
+ function patterns(file, where, value) {
99
+ if (value === null || value === undefined)
100
+ return [];
101
+ if (!Array.isArray(value) || !value.every((item) => typeof item === "string" && item.trim())) {
102
+ throw new RunbookError(`${file}: ${where} must be a list of region keys`);
103
+ }
104
+ return value.map((item) => item.trim());
105
+ }
106
+ function regions(file, page) {
107
+ const found = [];
108
+ for (const region of get(page, "regions", [])) {
109
+ const raw = get(region, "key");
110
+ const key = patterns(file, "pages.regions.key", raw !== undefined && raw !== null ? [raw] : null);
111
+ if (!key.length)
112
+ throw new RunbookError(`${file}: a region on ${get(page, "url", "?")} has no key`);
113
+ const fallback = get(region, "default", null);
114
+ if (fallback !== null && !DEFAULTS.has(fallback)) {
115
+ throw new RunbookError(`${file}: region ${quote(key[0])} has unknown default ${quote(fallback)}`);
116
+ }
117
+ found.push({ key: key[0], purpose: get(region, "purpose", ""), default: fallback });
118
+ }
119
+ return found;
120
+ }
121
+ /**
122
+ * Combines region choices. A later layer wins: learned defaults, then the runbook, then Claude.
123
+ * Focus patterns keep the later layer's order first, since the first focus is shown first.
124
+ */
125
+ export function view(...layers) {
126
+ let focus = [];
127
+ let skip = [];
128
+ for (const layer of layers) {
129
+ if (blank(layer))
130
+ continue;
131
+ const newFocus = [...(layer?.focus ?? [])];
132
+ const newSkip = [...(layer?.skip ?? [])];
133
+ const kept = (p) => !newFocus.includes(p) && !newSkip.includes(p);
134
+ focus = [...newFocus, ...focus.filter(kept)];
135
+ skip = [...skip.filter(kept), ...newSkip];
136
+ }
137
+ return { focus, skip };
138
+ }
139
+ /** What the service information says to focus on or skip on every page. */
140
+ export function serviceView(info) {
141
+ const keys = (info?.pages ?? []).flatMap((page) => page.regions);
142
+ return {
143
+ focus: keys.filter((r) => r.default === "focus").map((r) => r.key),
144
+ skip: keys.filter((r) => r.default === "skip").map((r) => r.key),
145
+ };
146
+ }
147
+ /** Service information for Claude's plan and Jev's state. null when nothing was learned. */
148
+ export function loadService(service) {
149
+ const found = findService(service);
150
+ if (!found)
151
+ return null;
152
+ const { file, scope } = found;
153
+ const { data } = readToml(file);
154
+ const missing = ["service", "description", "base_url"].filter((key) => blank(data[key]));
155
+ if (missing.length)
156
+ throw new RunbookError(`${file}: missing ${missing.join(", ")}`);
157
+ const login = get(data, "login", {});
158
+ return {
159
+ service: data.service,
160
+ description: String(data.description).trim(),
161
+ base_url: data.base_url,
162
+ login: { required: !blank(get(login, "required")), url: get(login, "url", null) },
163
+ pages: get(data, "pages", []).map((p) => ({
164
+ url: get(p, "url", ""),
165
+ purpose: get(p, "purpose", ""),
166
+ regions: regions(file, p),
167
+ })),
168
+ facts: get(data, "facts", []).map(show),
169
+ scope,
170
+ };
171
+ }
172
+ function subfolders(dir) {
173
+ if (!existsSync(dir))
174
+ return [];
175
+ return readdirSync(dir, { withFileTypes: true })
176
+ .filter((entry) => entry.isDirectory())
177
+ .map((entry) => entry.name);
178
+ }
179
+ /** Everything learned in both scopes, without filling parameters. Claude reads this to plan. */
180
+ export function catalog() {
181
+ const services = [...new Set(folders().flatMap(({ dir }) => subfolders(dir)))].sort();
182
+ return services.map((service) => {
183
+ const info = loadService(service);
184
+ const names = new Set();
185
+ for (const { dir } of folders()) {
186
+ const folder = join(dir, service);
187
+ if (!existsSync(folder))
188
+ continue;
189
+ for (const file of readdirSync(folder)) {
190
+ if (file.endsWith(".toml") && file !== `${SERVICE_FILE}.toml` && isFile(join(folder, file))) {
191
+ names.add(file.slice(0, -".toml".length));
192
+ }
193
+ }
194
+ }
195
+ const procedures = [...names].sort().map((stem) => {
196
+ const found = find(join(service, `${stem}.toml`));
197
+ if (!found)
198
+ throw new RunbookError(`${service}/${stem} disappeared while reading`);
199
+ const { data } = readToml(found.file);
200
+ return {
201
+ name: `${service}/${stem}`,
202
+ scope: found.scope,
203
+ status: get(data, "status", null),
204
+ goal: get(data, "goal", null),
205
+ start_url: get(data, "start_url", null),
206
+ params: Object.fromEntries(Object.entries(get(data, "params", {})).map(([k, v]) => [k, get(v, "description", "")])),
207
+ human_steps: get(data, "steps", []).filter((s) => get(s, "actor") === "human").length,
208
+ focus: get(data, "focus", []),
209
+ skip: get(data, "skip", []),
210
+ };
211
+ });
212
+ return { service, info, procedures };
213
+ });
214
+ }
215
+ export function parseValues(pairs) {
216
+ const values = {};
217
+ for (const pair of pairs) {
218
+ const at = pair.indexOf("=");
219
+ if (at <= 0)
220
+ throw new RunbookError(`Expected KEY=VALUE, got ${quote(pair)}`);
221
+ values[pair.slice(0, at)] = pair.slice(at + 1);
222
+ }
223
+ return values;
224
+ }
225
+ /** A URL without a scheme is a local file, relative to base (the folder that holds the scope's .webhand). */
226
+ export function resolveUrl(url, base = process.cwd()) {
227
+ if (/^[A-Za-z][A-Za-z0-9+.-]*:/.test(url))
228
+ return url;
229
+ const hash = url.indexOf("#");
230
+ const withoutFragment = hash >= 0 ? url.slice(0, hash) : url;
231
+ const at = withoutFragment.indexOf("?");
232
+ const local = at >= 0 ? withoutFragment.slice(0, at) : withoutFragment;
233
+ const query = at >= 0 ? withoutFragment.slice(at + 1) : "";
234
+ const file = resolve(base, local);
235
+ if (!isFile(file))
236
+ throw new RunbookError(`start_url file not found: ${local}`);
237
+ return pathToFileURL(file).href + (query ? `?${query}` : "");
238
+ }
239
+ /** Validates a runbook and fills in its parameters. Every problem is an error, not a guess. */
240
+ export function load(name, values = {}) {
241
+ const found = findRunbook(name);
242
+ if (!found)
243
+ throw new RunbookError(`Unknown runbook: ${name}`);
244
+ return loadFile(found.file, name, found.scope, values, found.base);
245
+ }
246
+ export function loadFile(file, name, scope, values = {}, base = process.cwd()) {
247
+ const { raw, data } = readToml(file);
248
+ const required = ["service", "name", "goal", "start_url", "status", "steps"];
249
+ const missing = required.filter((key) => blank(data[key]));
250
+ if (missing.length)
251
+ throw new RunbookError(`${file}: missing ${missing.join(", ")}`);
252
+ if (!STATUSES.has(data.status))
253
+ throw new RunbookError(`${file}: unknown status ${quote(data.status)}`);
254
+ const declared = get(data, "params", {});
255
+ const unknown = Object.keys(values)
256
+ .filter((key) => !(key in declared))
257
+ .sort();
258
+ if (unknown.length)
259
+ throw new RunbookError(`${file}: unknown parameters ${quote(unknown)}`);
260
+ const filled = {};
261
+ for (const [key, spec] of Object.entries(declared))
262
+ filled[key] = key in values ? values[key] : get(spec, "default");
263
+ const fill = (text) => String(text).replace(PARAM, (_match, param) => {
264
+ const value = filled[param];
265
+ if (value === null || value === undefined) {
266
+ throw new RunbookError(`${file}: parameter ${quote(param)} has no value. Pass --param ${param}=VALUE`);
267
+ }
268
+ return show(value);
269
+ });
270
+ const steps = data.steps.map((step, i) => {
271
+ const number = i + 1;
272
+ const actor = get(step, "actor", "jev");
273
+ if (!ACTORS.has(actor))
274
+ throw new RunbookError(`${file}: step ${number} has unknown actor ${quote(actor)}`);
275
+ if (blank(step.instruction))
276
+ throw new RunbookError(`${file}: step ${number} has no instruction`);
277
+ return {
278
+ actor,
279
+ instruction: fill(step.instruction),
280
+ hints: get(step, "hints", []).map(fill),
281
+ done_when: blank(step.done_when) ? null : fill(step.done_when),
282
+ };
283
+ });
284
+ return {
285
+ name,
286
+ scope,
287
+ service: data.service,
288
+ status: data.status,
289
+ digest: createHash("sha256").update(raw).digest("hex").slice(0, 16),
290
+ goal: fill(data.goal),
291
+ start_url: resolveUrl(fill(data.start_url), base),
292
+ steps,
293
+ focus: patterns(file, "focus", get(data, "focus")),
294
+ skip: patterns(file, "skip", get(data, "skip")),
295
+ };
296
+ }
@@ -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 { quote, sleep } from "./format.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 ${quote(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 ${quote(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: ${quote(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 ${quote(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/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
+ }