webhand 0.2.0 → 0.4.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.
package/dist/py.js DELETED
@@ -1,141 +0,0 @@
1
- /**
2
- * Python-compatible formatting. What the CLI prints is measured (handoff chars) and read by Claude,
3
- * so it stays exactly as the Python implementation printed it.
4
- */
5
- // Python's str.isprintable() is false for these: other (Cc, Cf, Cs, Co, Cn) and separators except the space.
6
- const NOT_PRINTABLE = /[\p{C}\p{Z}]/u;
7
- function escapeChar(char, quote) {
8
- if (char === "\\")
9
- return "\\\\";
10
- if (char === quote)
11
- return `\\${quote}`;
12
- if (char === "\n")
13
- return "\\n";
14
- if (char === "\r")
15
- return "\\r";
16
- if (char === "\t")
17
- return "\\t";
18
- if (char !== " " && NOT_PRINTABLE.test(char)) {
19
- const code = char.codePointAt(0) ?? 0;
20
- if (code < 0x100)
21
- return `\\x${code.toString(16).padStart(2, "0")}`;
22
- if (code < 0x10000)
23
- return `\\u${code.toString(16).padStart(4, "0")}`;
24
- return `\\U${code.toString(16).padStart(8, "0")}`;
25
- }
26
- return char;
27
- }
28
- function reprString(text) {
29
- const quote = text.includes("'") && !text.includes('"') ? '"' : "'";
30
- let body = "";
31
- for (const char of text)
32
- body += escapeChar(char, quote);
33
- return quote + body + quote;
34
- }
35
- function reprNumber(value) {
36
- if (Number.isNaN(value))
37
- return "nan";
38
- if (!Number.isFinite(value))
39
- return value > 0 ? "inf" : "-inf";
40
- return String(value);
41
- }
42
- /** repr() of a JSON-like value. */
43
- export function pyRepr(value) {
44
- if (value === null || value === undefined)
45
- return "None";
46
- if (value === true)
47
- return "True";
48
- if (value === false)
49
- return "False";
50
- if (typeof value === "string")
51
- return reprString(value);
52
- if (typeof value === "number")
53
- return reprNumber(value);
54
- if (Array.isArray(value))
55
- return `[${value.map(pyRepr).join(", ")}]`;
56
- if (value instanceof Map) {
57
- return `{${[...value].map(([k, v]) => `${pyRepr(k)}: ${pyRepr(v)}`).join(", ")}}`;
58
- }
59
- if (typeof value === "object") {
60
- return `{${Object.entries(value)
61
- .map(([k, v]) => `${pyRepr(k)}: ${pyRepr(v)}`)
62
- .join(", ")}}`;
63
- }
64
- return String(value);
65
- }
66
- /** str() of a JSON-like value, as an f-string prints it. */
67
- export function pyStr(value) {
68
- if (typeof value === "string")
69
- return value;
70
- return pyRepr(value);
71
- }
72
- /**
73
- * json.dumps(value, ensure_ascii=False). Maps keep their order, which a plain object would not keep
74
- * for keys like "2" and "1". compact gives the separators httpx uses for a request body.
75
- */
76
- export function pyJson(value, compact = false) {
77
- const comma = compact ? "," : ", ";
78
- const colon = compact ? ":" : ": ";
79
- const encode = (item) => {
80
- if (item === null || item === undefined)
81
- return "null";
82
- if (typeof item === "number")
83
- return Number.isFinite(item) ? JSON.stringify(item) : "null";
84
- if (typeof item === "string" || typeof item === "boolean")
85
- return JSON.stringify(item);
86
- if (Array.isArray(item))
87
- return `[${item.map(encode).join(comma)}]`;
88
- const entries = item instanceof Map ? [...item] : Object.entries(item);
89
- return `{${entries
90
- .filter(([, v]) => v !== undefined)
91
- .map(([k, v]) => `${JSON.stringify(String(k))}${colon}${encode(v)}`)
92
- .join(comma)}}`;
93
- };
94
- return encode(value);
95
- }
96
- /** round() to an int: halves go to the even neighbour. */
97
- export function pyRound(value) {
98
- const floor = Math.floor(value);
99
- const diff = value - floor;
100
- if (diff > 0.5)
101
- return floor + 1;
102
- if (diff < 0.5)
103
- return floor;
104
- return floor % 2 === 0 ? floor : floor + 1;
105
- }
106
- /** Python truthiness: None, False, 0, "", [] and {} are false. */
107
- export function pyTruthy(value) {
108
- if (value === null || value === undefined || value === false || value === 0 || value === "")
109
- return false;
110
- if (Array.isArray(value))
111
- return value.length > 0;
112
- if (value instanceof Map)
113
- return value.size > 0;
114
- if (typeof value === "object")
115
- return Object.keys(value).length > 0;
116
- return true;
117
- }
118
- /** time.strftime("%Y%m%dT%H%M%S") in local time. */
119
- export function stamp(date = new Date()) {
120
- const pad = (n) => String(n).padStart(2, "0");
121
- return (`${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}` +
122
- `T${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}`);
123
- }
124
- /** datetime.now(timezone.utc).isoformat(). */
125
- export function utcIso(date = new Date()) {
126
- return `${date.toISOString().slice(0, 23)}000+00:00`;
127
- }
128
- /** The length Python reports for a str: code points, not UTF-16 units. */
129
- export function pyLen(text) {
130
- let count = 0;
131
- for (const _ of text)
132
- count++;
133
- return count;
134
- }
135
- /** type(error).__name__: error, as Python formats an exception for a log. */
136
- export function describeError(error) {
137
- if (error instanceof Error)
138
- return `${error.name}: ${error.message}`;
139
- return `Error: ${String(error)}`;
140
- }
141
- export const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
package/dist/run.js DELETED
@@ -1,80 +0,0 @@
1
- /** Harness smoke test: the fixed script, no model. Agent runs go through the webhand CLI. */
2
- import { join } from "node:path";
3
- import { parseArgs } from "node:util";
4
- import { Budget, GOAL_REPORTED, runAgent } from "./agent.js";
5
- import { Browser } from "./browser.js";
6
- import { gitState, Recorder, summarize } from "./metrics.js";
7
- import { ScriptedPolicy } from "./policies/scripted.js";
8
- import { describeError, pyStr, stamp, utcIso } from "./py.js";
9
- import { loadTask } from "./tasks.js";
10
- const ROOT = process.cwd();
11
- async function runOnce(taskName, task, repeat, folder, options) {
12
- const recorder = new Recorder(join(folder, `${taskName}-scripted-${repeat}.jsonl`));
13
- let browser = null;
14
- let result = { status: "error", reason: null };
15
- let verdict = { success: false, evidence: null };
16
- try {
17
- const policy = new ScriptedPolicy(task.SCRIPT);
18
- browser = await Browser.open(task.startUrl(ROOT), { headless: !options.headed });
19
- recorder.event("run_start", {
20
- task: taskName,
21
- goal: task.GOAL,
22
- policy: "scripted",
23
- repeat,
24
- config: policy.config(),
25
- chrome: browser.version,
26
- git: gitState(),
27
- started_at: utcIso(),
28
- });
29
- const plan = { goal: task.GOAL, steps: [], values: [] };
30
- const { page: _page, ...outcome } = await runAgent(browser, policy, plan, recorder, new Budget(options.maxActions, options.maxDecisions));
31
- result = { ...outcome, status: outcome.outcome === GOAL_REPORTED ? "done" : "blocked" };
32
- verdict = await task.verify(browser);
33
- }
34
- catch (error) {
35
- // A failed run is data: keep it and move to the next one.
36
- result = { ...result, reason: describeError(error) };
37
- }
38
- finally {
39
- await browser?.close();
40
- }
41
- const summary = summarize(recorder.calls);
42
- recorder.event("run_end", { ...result, verified: verdict.success, evidence: verdict.evidence, ...summary });
43
- recorder.close();
44
- const reason = result.reason || result.detail || null;
45
- console.log(`${taskName}#${repeat}: ${result.status} verified=${pyStr(verdict.success)} reason=${pyStr(reason)}`);
46
- return verdict.success === true;
47
- }
48
- export async function main(argv = process.argv.slice(2)) {
49
- const { values } = parseArgs({
50
- args: argv,
51
- options: {
52
- task: { type: "string" },
53
- repeat: { type: "string", default: "1" },
54
- headed: { type: "boolean", default: false },
55
- "max-actions": { type: "string", default: String(Budget.MAX_ACTIONS) },
56
- "max-decisions": { type: "string", default: String(Budget.MAX_DECISIONS) },
57
- },
58
- });
59
- if (!values.task)
60
- throw new Error("--task is required");
61
- const task = await loadTask(values.task);
62
- const folder = join(ROOT, "runs", stamp());
63
- const options = {
64
- headed: values.headed ?? false,
65
- maxActions: Number(values["max-actions"]),
66
- maxDecisions: Number(values["max-decisions"]),
67
- };
68
- const passed = [];
69
- for (let repeat = 1; repeat <= Number(values.repeat); repeat++) {
70
- passed.push(await runOnce(values.task, task, repeat, folder, options));
71
- }
72
- console.log(`${passed.filter(Boolean).length}/${passed.length} verified. Logs: ${folder}`);
73
- return passed.every(Boolean) ? 0 : 1;
74
- }
75
- if (import.meta.url === `file://${process.argv[1]}`) {
76
- main().then((code) => process.exit(code), (error) => {
77
- console.error(error instanceof Error ? error.message : error);
78
- process.exit(1);
79
- });
80
- }
package/dist/tasks.js DELETED
@@ -1,37 +0,0 @@
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
- }