@weavetab/plugin-gamer 0.0.0-stage → 0.1.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/index.js ADDED
@@ -0,0 +1,318 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { defineCommand, definePlugin, definePrompt, defineTool, z } from "@weavetab/sdk";
4
+ import { captureFrame, getGate, getViewport, readSelectorText } from "./gate.js";
5
+ import { focusTarget, InputController } from "./input.js";
6
+ import { parseRules, runPlaybook } from "./loop.js";
7
+ export function sessOf(ctx) {
8
+ return ctx?.tab?.session || ctx?.session || ctx;
9
+ }
10
+ function parseListArg(val) {
11
+ if (val === undefined)
12
+ return undefined;
13
+ if (Array.isArray(val))
14
+ return val.map(String);
15
+ if (typeof val === "string") {
16
+ const trimmed = val.trim();
17
+ if (!trimmed)
18
+ return undefined;
19
+ if (trimmed.startsWith("[")) {
20
+ const parsed = JSON.parse(trimmed);
21
+ if (Array.isArray(parsed))
22
+ return parsed.map(String);
23
+ }
24
+ return trimmed.split(",").map((s) => s.trim()).filter(Boolean);
25
+ }
26
+ return undefined;
27
+ }
28
+ const ClipSchema = z
29
+ .union([
30
+ z.string(),
31
+ z.object({ x: z.number(), y: z.number(), w: z.number(), h: z.number() }),
32
+ ])
33
+ .optional()
34
+ .describe("CSS selector (e.g. 'canvas') or {x,y,w,h} crop rect (pixels or 0..1 normalized).");
35
+ const RuleSchema = z.object({
36
+ when: z.string(),
37
+ do: z.record(z.any()),
38
+ min_conf: z.number().optional(),
39
+ yield: z.boolean().optional(),
40
+ cooldown_ms: z.number().optional(),
41
+ });
42
+ const PlayShape = {
43
+ rules: z.union([z.array(RuleSchema), z.string()]).describe("Playbook rules array or JSON string mapping 'when' to 'do'."),
44
+ steps: z.number().optional().describe("Max decision ticks (1-200, default 30)."),
45
+ max_ms: z.number().optional().describe("Max burst duration in ms (200-30000, default 6000)."),
46
+ interval_ms: z.number().optional().describe("Loop interval in ms (50-2000, default 100)."),
47
+ min_conf: z.number().optional().describe("Minimum Gate confidence (0-1, default 0.45)."),
48
+ yield_on_low_conf: z.number().optional().describe("Stop after N consecutive low-confidence ticks."),
49
+ stop_if: z.string().optional().describe("Optional Gate yes/no interrupt condition."),
50
+ stop_conf: z.number().optional().describe("Confidence threshold for stop_if (default 0.65)."),
51
+ stop_check_every: z.number().optional().describe("Evaluate stop_if every N ticks (default 1)."),
52
+ clip: ClipSchema,
53
+ text_selector: z.string().optional().describe("Optional DOM selector to evaluate via Gate text NLI instead of vision."),
54
+ focus: z.union([z.string(), z.boolean()]).optional().describe("Selector to focus before burst, or false to skip."),
55
+ quality: z.number().optional().describe("JPEG quality (25-95, default 65)."),
56
+ };
57
+ const DecideShape = {
58
+ choices: z.union([z.array(z.string()), z.string()]).optional().describe("2-64 candidate labels."),
59
+ ask: z.string().optional().describe("Declarative statement for Gate yesNo."),
60
+ levels: z.union([z.array(z.string()), z.string()]).optional().describe("2-64 ordered rubric levels."),
61
+ clip: ClipSchema,
62
+ text_selector: z.string().optional().describe("Optional DOM selector for text NLI instead of vision."),
63
+ quality: z.number().optional().describe("JPEG quality (25-95, default 65)."),
64
+ };
65
+ const ActShape = {
66
+ type: z.enum(["hold", "tap", "click", "mouse_hold", "drag", "look", "idle", "yield"]).describe("Input action kind."),
67
+ keys: z.union([z.array(z.string()), z.string()]).optional().describe("Keys for tap/hold."),
68
+ button: z.enum(["left", "right", "middle"]).optional(),
69
+ x: z.number().optional(),
70
+ y: z.number().optional(),
71
+ x1: z.number().optional(),
72
+ y1: z.number().optional(),
73
+ x2: z.number().optional(),
74
+ y2: z.number().optional(),
75
+ dx: z.number().optional(),
76
+ dy: z.number().optional(),
77
+ steps: z.number().optional(),
78
+ hold_ms: z.number().optional(),
79
+ focus: z.union([z.string(), z.boolean()]).optional(),
80
+ };
81
+ function buildAction(a) {
82
+ const keys = parseListArg(a.keys) ?? [];
83
+ switch (a.type) {
84
+ case "hold":
85
+ if (!keys.length)
86
+ throw new Error("hold action requires non-empty keys");
87
+ return { type: "hold", keys };
88
+ case "tap":
89
+ if (!keys.length)
90
+ throw new Error("tap action requires non-empty keys");
91
+ return { type: "tap", keys, hold_ms: a.hold_ms };
92
+ case "click":
93
+ return { type: "click", button: a.button, x: a.x, y: a.y, hold_ms: a.hold_ms };
94
+ case "mouse_hold":
95
+ return { type: "mouse_hold", button: a.button, x: a.x, y: a.y };
96
+ case "drag":
97
+ if (a.x1 == null || a.y1 == null || a.x2 == null || a.y2 == null) {
98
+ throw new Error("drag requires x1, y1, x2, y2");
99
+ }
100
+ return { type: "drag", x1: a.x1, y1: a.y1, x2: a.x2, y2: a.y2, button: a.button, steps: a.steps };
101
+ case "look":
102
+ if (a.dx == null || a.dy == null)
103
+ throw new Error("look requires dx and dy");
104
+ return { type: "look", dx: a.dx, dy: a.dy, steps: a.steps };
105
+ case "idle":
106
+ return { type: "idle" };
107
+ case "yield":
108
+ return { type: "yield" };
109
+ default:
110
+ throw new Error(`unsupported action type: ${a.type}`);
111
+ }
112
+ }
113
+ async function runDecide(sess, args, defaultQuality) {
114
+ const gate = await getGate();
115
+ let frame = null;
116
+ let payload;
117
+ if (args.text_selector) {
118
+ payload = await readSelectorText(sess, args.text_selector);
119
+ }
120
+ else {
121
+ frame = await captureFrame(sess, { quality: args.quality ?? defaultQuality, clip: args.clip });
122
+ payload = frame.buffer;
123
+ }
124
+ let result;
125
+ const choices = parseListArg(args.choices);
126
+ const levels = parseListArg(args.levels);
127
+ if (args.ask) {
128
+ result = { mode: "yes_no", ...gate.yesNo(payload, args.ask) };
129
+ }
130
+ else if (levels?.length) {
131
+ result = { mode: "score", ...gate.score(payload, levels) };
132
+ }
133
+ else if (choices?.length) {
134
+ result = { mode: "decide", ...gate.decide(payload, choices) };
135
+ }
136
+ else {
137
+ throw new Error("provide one of: choices, ask, or levels");
138
+ }
139
+ return { result, frame };
140
+ }
141
+ async function runSingleAction(sess, args) {
142
+ const vp = await getViewport(sess);
143
+ await focusTarget(sess, args.focus);
144
+ const act = buildAction(args);
145
+ const input = new InputController();
146
+ try {
147
+ await input.exec(sess, act, vp);
148
+ // standalone single hold/mouse_hold holds briefly then releases so keys never stay stuck
149
+ if (act.type === "hold" || act.type === "mouse_hold") {
150
+ await new Promise((r) => setTimeout(r, Math.min(5000, Math.max(20, args.hold_ms ?? 300))));
151
+ }
152
+ }
153
+ finally {
154
+ await input.releaseAll(sess).catch(() => { });
155
+ }
156
+ return { ok: true, action: act.type, viewport: vp };
157
+ }
158
+ const runCommand = defineCommand({
159
+ name: "run",
160
+ description: "Run a bounded real-time Gate v2.0 vision/NLI playbook loop and stream transition-only progress lines to stdout.",
161
+ usage: "weavetab plugin use gamer run --rules '[{\"when\":\"...\",\"do\":{\"type\":\"hold\",\"keys\":[\"w\"]}}]' [--steps 30] [--clip canvas]",
162
+ requiresSession: true,
163
+ schema: {
164
+ ...PlayShape,
165
+ save_frame: z.string().optional().describe("Optional path to save the final JPEG frame."),
166
+ },
167
+ handler: async (args, ctx) => {
168
+ const res = await runPlaybook(sessOf(ctx), { ...args, rules: parseRules(args.rules), return_frame: false }, {
169
+ attachSigint: true,
170
+ defaultConfig: ctx?.config,
171
+ onLine: (line) => process.stdout.write(line + "\n"),
172
+ });
173
+ return res;
174
+ },
175
+ });
176
+ const decideCommand = defineCommand({
177
+ name: "decide",
178
+ description: "Capture a single frame (or selector text) and evaluate Gate v2.0 decide, yes/no, or ordered score.",
179
+ usage: "weavetab plugin use gamer decide --choices '[\"a\",\"b\"]' | --ask \"...\" | --levels '[\"low\",\"high\"]' [--clip canvas]",
180
+ requiresSession: true,
181
+ schema: {
182
+ ...DecideShape,
183
+ save_frame: z.string().optional().describe("Optional path to write the captured JPEG frame."),
184
+ },
185
+ handler: async (args, ctx) => {
186
+ const { result, frame } = await runDecide(sessOf(ctx), args, ctx?.config?.jpegQuality);
187
+ if (args.save_frame && frame) {
188
+ const abs = path.resolve(args.save_frame);
189
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
190
+ fs.writeFileSync(abs, frame.buffer);
191
+ result.saved_frame = abs;
192
+ }
193
+ return result;
194
+ },
195
+ });
196
+ const actCommand = defineCommand({
197
+ name: "act",
198
+ description: "Dispatch an immediate CDP keyboard, mouse, drag, or camera-look action on the active tab or Electron window.",
199
+ usage: "weavetab plugin use gamer act --type tap|hold|click|mouse_hold|drag|look --keys '[\"w\"]'",
200
+ requiresSession: true,
201
+ schema: ActShape,
202
+ handler: async (args, ctx) => runSingleAction(sessOf(ctx), args),
203
+ });
204
+ export const gamerPlugin = definePlugin({
205
+ name: "@weavetab/plugin-gamer",
206
+ version: "0.1.0",
207
+ description: "Local-vision real-time controller powered by Weavetab Gate v2.0 — CLI-first bounded burst playbooks, MCP parity, and universal CDP inputs.",
208
+ instructions: "Two-tier Planner-Actor control via Gate v2.0 local ONNX:\n" +
209
+ "1. Prefer CLI `weavetab plugin use gamer run --rules '[...]'` for real-time transition streaming without context bloat.\n" +
210
+ "2. Use MCP `gamer_play` when you want the final JPEG frame returned inline to re-plan.\n" +
211
+ "3. Calibrate labels with `gamer_decide` / `decide`; dispatch manual inputs with `gamer_act` / `act`.",
212
+ defaultConfig: {
213
+ defaultIntervalMs: 100,
214
+ defaultSteps: 30,
215
+ minConfidence: 0.45,
216
+ jpegQuality: 65,
217
+ },
218
+ permissions: {
219
+ cdp: {
220
+ evaluate: true,
221
+ screenshot: true,
222
+ input: true,
223
+ reason: "Captures fast viewport/selector screenshots, reads optional HUD text or canvas focus/pointer-lock state, and dispatches keyboard/mouse/drag/camera inputs.",
224
+ },
225
+ tools: {
226
+ add: true,
227
+ reason: "Registers gamer_play, gamer_decide, and gamer_act MCP tools.",
228
+ },
229
+ commands: {
230
+ add: true,
231
+ reason: "Registers run, decide, and act CLI commands with live transition streaming.",
232
+ },
233
+ prompts: {
234
+ add: true,
235
+ reason: "Registers the /gamer_playbook prompt utility.",
236
+ },
237
+ config: {
238
+ read: true,
239
+ write: true,
240
+ reason: "Reads default burst interval, step budget, confidence threshold, and JPEG quality.",
241
+ },
242
+ },
243
+ commands: [runCommand, decideCommand, actCommand],
244
+ async onLoad(ctx) {
245
+ const defaultCfg = ctx.config;
246
+ ctx.mcp.registerTool(defineTool({
247
+ name: "gamer_play",
248
+ description: "Runs a bounded ~8-12 Hz local Gate v2.0 vision/NLI playbook loop and returns compacted transitions plus an optional final JPEG frame for re-planning.",
249
+ requiresSession: true,
250
+ schema: {
251
+ ...PlayShape,
252
+ return_frame: z.boolean().optional().describe("Attach final JPEG frame inline (default true)."),
253
+ },
254
+ handler: async (args, rawCtx) => {
255
+ const returnFrame = args.return_frame !== false;
256
+ const res = await runPlaybook(sessOf(rawCtx), { ...args, rules: parseRules(args.rules), return_frame: returnFrame }, { defaultConfig: rawCtx?.config ?? defaultCfg });
257
+ const { last_frame_base64, ...summary } = res;
258
+ const content = [
259
+ { type: "text", text: JSON.stringify(summary, null, 2) },
260
+ ];
261
+ if (returnFrame && last_frame_base64) {
262
+ content.push({ type: "image", data: last_frame_base64, mimeType: "image/jpeg" });
263
+ }
264
+ return { content };
265
+ },
266
+ }));
267
+ ctx.mcp.registerTool(defineTool({
268
+ name: "gamer_decide",
269
+ description: "Evaluates a single live frame (or selector text) using Gate v2.0 decide, yesNo, or score without burning LLM vision tokens.",
270
+ requiresSession: true,
271
+ schema: {
272
+ ...DecideShape,
273
+ return_frame: z.boolean().optional().describe("Attach captured JPEG frame inline (default false)."),
274
+ },
275
+ handler: async (args, rawCtx) => {
276
+ const { result, frame } = await runDecide(sessOf(rawCtx), args, rawCtx?.config?.jpegQuality ?? defaultCfg?.jpegQuality);
277
+ const content = [
278
+ { type: "text", text: JSON.stringify(result, null, 2) },
279
+ ];
280
+ if (args.return_frame && frame) {
281
+ content.push({ type: "image", data: frame.base64, mimeType: "image/jpeg" });
282
+ }
283
+ return { content };
284
+ },
285
+ }));
286
+ ctx.mcp.registerTool(defineTool({
287
+ name: "gamer_act",
288
+ description: "Dispatches an immediate keyboard, mouse click/hold, drag, or pointer-lock look input via CDP.",
289
+ requiresSession: true,
290
+ schema: ActShape,
291
+ handler: async (args, rawCtx) => {
292
+ const out = await runSingleAction(sessOf(rawCtx), args);
293
+ return { content: [{ type: "text", text: JSON.stringify(out, null, 2) }] };
294
+ },
295
+ }));
296
+ ctx.mcp.registerPrompt(definePrompt({
297
+ name: "gamer_playbook",
298
+ description: "Inspect viewport dimensions and active canvas bounds, then guide writing a Playbook rule set for CLI `run` or MCP `gamer_play`.",
299
+ arguments: {
300
+ goal: z.string().optional().describe("Short description of the interactive task or mission"),
301
+ },
302
+ handler: async (args, rawCtx) => {
303
+ const sess = sessOf(rawCtx);
304
+ const vp = await getViewport(sess);
305
+ return [
306
+ `Goal: ${args.goal || "interactive control"}`,
307
+ `Viewport: ${vp.width}x${vp.height}`,
308
+ `1. Calibrate visual labels first with gamer_decide (or \`weavetab plugin use gamer decide --clip canvas\`).`,
309
+ `2. Run live bursts via CLI \`weavetab plugin use gamer run --rules '[...]' --clip canvas\` for real-time transition logs, or MCP \`gamer_play\` for an inline end-of-burst screenshot.`,
310
+ `3. Supported do.type values: hold, tap, click, mouse_hold, drag, look, idle, yield.`,
311
+ ].join("\n");
312
+ },
313
+ }));
314
+ ctx.logger?.info("@weavetab/plugin-gamer v0.1.0 loaded");
315
+ },
316
+ });
317
+ export default gamerPlugin;
318
+ export const plugin = gamerPlugin;
@@ -0,0 +1,66 @@
1
+ import type { Viewport } from "./gate.js";
2
+ export type MouseButton = "left" | "right" | "middle";
3
+ export type GameAction = {
4
+ type: "hold";
5
+ keys: string[];
6
+ } | {
7
+ type: "tap";
8
+ keys: string[];
9
+ hold_ms?: number;
10
+ } | {
11
+ type: "click";
12
+ button?: MouseButton;
13
+ x?: number;
14
+ y?: number;
15
+ hold_ms?: number;
16
+ } | {
17
+ type: "mouse_hold";
18
+ button?: MouseButton;
19
+ x?: number;
20
+ y?: number;
21
+ } | {
22
+ type: "drag";
23
+ x1: number;
24
+ y1: number;
25
+ x2: number;
26
+ y2: number;
27
+ button?: MouseButton;
28
+ steps?: number;
29
+ } | {
30
+ type: "look";
31
+ dx: number;
32
+ dy: number;
33
+ steps?: number;
34
+ } | {
35
+ type: "idle";
36
+ } | {
37
+ type: "yield";
38
+ };
39
+ interface KeySpec {
40
+ key: string;
41
+ code: string;
42
+ keyCode: number;
43
+ text?: string;
44
+ }
45
+ export declare function resolveKey(raw: string): KeySpec;
46
+ export declare function resolvePoint(x: number | undefined, y: number | undefined, vp: Viewport): {
47
+ x: number;
48
+ y: number;
49
+ };
50
+ export declare function focusTarget(sess: any, focus?: string | boolean): Promise<void>;
51
+ export declare function describeAction(a: GameAction): string;
52
+ export declare class InputController {
53
+ private heldKeys;
54
+ private heldMouse;
55
+ private cursor;
56
+ get activeKeys(): string[];
57
+ syncHoldKeys(sess: any, targetKeys: string[]): Promise<void>;
58
+ syncMouseHold(sess: any, target: {
59
+ button: MouseButton;
60
+ x: number;
61
+ y: number;
62
+ } | null): Promise<void>;
63
+ releaseAll(sess: any): Promise<void>;
64
+ exec(sess: any, action: GameAction, vp: Viewport): Promise<void>;
65
+ }
66
+ export {};
package/dist/input.js ADDED
@@ -0,0 +1,244 @@
1
+ const NAMED_KEYS = {
2
+ space: { key: " ", code: "Space", keyCode: 32, text: " " },
3
+ " ": { key: " ", code: "Space", keyCode: 32, text: " " },
4
+ enter: { key: "Enter", code: "Enter", keyCode: 13 },
5
+ return: { key: "Enter", code: "Enter", keyCode: 13 },
6
+ escape: { key: "Escape", code: "Escape", keyCode: 27 },
7
+ esc: { key: "Escape", code: "Escape", keyCode: 27 },
8
+ tab: { key: "Tab", code: "Tab", keyCode: 9 },
9
+ backspace: { key: "Backspace", code: "Backspace", keyCode: 8 },
10
+ shift: { key: "Shift", code: "ShiftLeft", keyCode: 16 },
11
+ control: { key: "Control", code: "ControlLeft", keyCode: 17 },
12
+ ctrl: { key: "Control", code: "ControlLeft", keyCode: 17 },
13
+ alt: { key: "Alt", code: "AltLeft", keyCode: 18 },
14
+ arrowleft: { key: "ArrowLeft", code: "ArrowLeft", keyCode: 37 },
15
+ left: { key: "ArrowLeft", code: "ArrowLeft", keyCode: 37 },
16
+ arrowup: { key: "ArrowUp", code: "ArrowUp", keyCode: 38 },
17
+ up: { key: "ArrowUp", code: "ArrowUp", keyCode: 38 },
18
+ arrowright: { key: "ArrowRight", code: "ArrowRight", keyCode: 39 },
19
+ right: { key: "ArrowRight", code: "ArrowRight", keyCode: 39 },
20
+ arrowdown: { key: "ArrowDown", code: "ArrowDown", keyCode: 40 },
21
+ down: { key: "ArrowDown", code: "ArrowDown", keyCode: 40 },
22
+ };
23
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
24
+ export function resolveKey(raw) {
25
+ const s = String(raw || "").trim();
26
+ const named = NAMED_KEYS[s.toLowerCase()];
27
+ if (named)
28
+ return named;
29
+ if (/^[a-z]$/i.test(s)) {
30
+ const up = s.toUpperCase();
31
+ return { key: s, code: `Key${up}`, keyCode: up.charCodeAt(0), text: s };
32
+ }
33
+ if (/^[0-9]$/.test(s)) {
34
+ return { key: s, code: `Digit${s}`, keyCode: s.charCodeAt(0), text: s };
35
+ }
36
+ const fMatch = /^f([1-9]|1[0-2])$/i.exec(s);
37
+ if (fMatch) {
38
+ const n = parseInt(fMatch[1], 10);
39
+ return { key: `F${n}`, code: `F${n}`, keyCode: 111 + n };
40
+ }
41
+ return { key: s, code: s, keyCode: s.length === 1 ? s.charCodeAt(0) : 0 };
42
+ }
43
+ export function resolvePoint(x, y, vp) {
44
+ const rx = x === undefined ? vp.width * 0.5 : x >= 0 && x <= 1 ? x * vp.width : x;
45
+ const ry = y === undefined ? vp.height * 0.5 : y >= 0 && y <= 1 ? y * vp.height : y;
46
+ return {
47
+ x: Math.round(Math.max(0, Math.min(Math.max(0, vp.width - 1), rx))),
48
+ y: Math.round(Math.max(0, Math.min(Math.max(0, vp.height - 1), ry))),
49
+ };
50
+ }
51
+ export async function focusTarget(sess, focus) {
52
+ if (focus === false || !sess?.Runtime?.evaluate)
53
+ return;
54
+ const sel = typeof focus === "string" && focus.trim() ? focus.trim() : null;
55
+ await sess.Runtime.evaluate({
56
+ expression: `((sel) => {
57
+ let el = null;
58
+ if (sel) {
59
+ el = document.querySelector(sel);
60
+ } else if (!document.activeElement || document.activeElement === document.body) {
61
+ let best = 0;
62
+ for (const c of document.querySelectorAll('canvas')) {
63
+ const r = c.getBoundingClientRect();
64
+ if (r.width * r.height > best) { best = r.width * r.height; el = c; }
65
+ }
66
+ }
67
+ if (el) {
68
+ if (!el.hasAttribute('tabindex')) el.setAttribute('tabindex', '-1');
69
+ if (typeof el.focus === 'function') el.focus();
70
+ }
71
+ })(${JSON.stringify(sel)})`,
72
+ returnByValue: true,
73
+ }).catch(() => { });
74
+ }
75
+ export function describeAction(a) {
76
+ switch (a.type) {
77
+ case "hold":
78
+ return `hold [${a.keys.join(",")}]`;
79
+ case "tap":
80
+ return `tap [${a.keys.join(",")}]`;
81
+ case "click":
82
+ return `click ${a.button || "left"}${a.x != null ? `(${a.x},${a.y ?? 0.5})` : ""}`;
83
+ case "mouse_hold":
84
+ return `mouse_hold ${a.button || "left"}`;
85
+ case "drag":
86
+ return `drag (${a.x1},${a.y1})->(${a.x2},${a.y2})`;
87
+ case "look":
88
+ return `look (${a.dx},${a.dy})`;
89
+ case "idle":
90
+ return "idle";
91
+ case "yield":
92
+ return "yield";
93
+ }
94
+ }
95
+ async function sendKey(sess, type, spec) {
96
+ await sess.Input.dispatchKeyEvent({
97
+ type: type === "keyDown" && !spec.text ? "rawKeyDown" : type,
98
+ key: spec.key,
99
+ code: spec.code,
100
+ windowsVirtualKeyCode: spec.keyCode,
101
+ nativeVirtualKeyCode: spec.keyCode,
102
+ ...(type === "keyDown" && spec.text ? { text: spec.text } : {}),
103
+ });
104
+ }
105
+ async function sendMouse(sess, type, x, y, button = "none", clickCount = 0) {
106
+ await sess.Input.dispatchMouseEvent({ type, x, y, button, clickCount });
107
+ }
108
+ export class InputController {
109
+ heldKeys = new Map();
110
+ heldMouse = null;
111
+ cursor = null;
112
+ get activeKeys() {
113
+ return [...this.heldKeys.keys()];
114
+ }
115
+ async syncHoldKeys(sess, targetKeys) {
116
+ const next = new Map();
117
+ for (const raw of targetKeys) {
118
+ const spec = resolveKey(raw);
119
+ next.set(spec.code, spec);
120
+ }
121
+ for (const [code, spec] of [...this.heldKeys.entries()]) {
122
+ if (!next.has(code)) {
123
+ await sendKey(sess, "keyUp", spec).catch(() => { });
124
+ this.heldKeys.delete(code);
125
+ }
126
+ }
127
+ for (const [code, spec] of next.entries()) {
128
+ if (!this.heldKeys.has(code)) {
129
+ await sendKey(sess, "keyDown", spec);
130
+ this.heldKeys.set(code, spec);
131
+ }
132
+ }
133
+ }
134
+ async syncMouseHold(sess, target) {
135
+ if (this.heldMouse &&
136
+ (!target ||
137
+ this.heldMouse.button !== target.button ||
138
+ Math.hypot(this.heldMouse.x - target.x, this.heldMouse.y - target.y) > 4)) {
139
+ const prev = this.heldMouse;
140
+ this.heldMouse = null;
141
+ await sendMouse(sess, "mouseReleased", prev.x, prev.y, prev.button, 1).catch(() => { });
142
+ }
143
+ if (target && !this.heldMouse) {
144
+ await sendMouse(sess, "mouseMoved", target.x, target.y, "none", 0);
145
+ await sendMouse(sess, "mousePressed", target.x, target.y, target.button, 1);
146
+ this.heldMouse = target;
147
+ this.cursor = { x: target.x, y: target.y };
148
+ }
149
+ }
150
+ async releaseAll(sess) {
151
+ await this.syncMouseHold(sess, null);
152
+ await this.syncHoldKeys(sess, []);
153
+ }
154
+ async exec(sess, action, vp) {
155
+ if (!sess?.Input) {
156
+ throw new Error("active CDP session does not expose Input domain");
157
+ }
158
+ if (action.type === "idle" || action.type === "yield") {
159
+ await this.releaseAll(sess);
160
+ return;
161
+ }
162
+ if (action.type === "hold") {
163
+ await this.syncMouseHold(sess, null);
164
+ await this.syncHoldKeys(sess, action.keys);
165
+ return;
166
+ }
167
+ if (action.type === "mouse_hold") {
168
+ await this.syncHoldKeys(sess, []);
169
+ const pt = resolvePoint(action.x, action.y, vp);
170
+ await this.syncMouseHold(sess, { button: action.button || "left", x: pt.x, y: pt.y });
171
+ return;
172
+ }
173
+ await this.releaseAll(sess);
174
+ if (action.type === "tap") {
175
+ const specs = action.keys.map(resolveKey);
176
+ for (const spec of specs)
177
+ await sendKey(sess, "keyDown", spec);
178
+ await sleep(Math.min(2000, Math.max(10, action.hold_ms ?? 50)));
179
+ for (let i = specs.length - 1; i >= 0; i--)
180
+ await sendKey(sess, "keyUp", specs[i]).catch(() => { });
181
+ return;
182
+ }
183
+ if (action.type === "click") {
184
+ const btn = action.button || "left";
185
+ const pt = resolvePoint(action.x, action.y, vp);
186
+ await sendMouse(sess, "mouseMoved", pt.x, pt.y, "none", 0);
187
+ await sendMouse(sess, "mousePressed", pt.x, pt.y, btn, 1);
188
+ await sleep(Math.min(2000, Math.max(10, action.hold_ms ?? 35)));
189
+ await sendMouse(sess, "mouseReleased", pt.x, pt.y, btn, 1);
190
+ this.cursor = pt;
191
+ return;
192
+ }
193
+ if (action.type === "drag") {
194
+ const btn = action.button || "left";
195
+ const p1 = resolvePoint(action.x1, action.y1, vp);
196
+ const p2 = resolvePoint(action.x2, action.y2, vp);
197
+ const steps = Math.min(20, Math.max(2, Math.round(action.steps ?? 6)));
198
+ await sendMouse(sess, "mouseMoved", p1.x, p1.y, "none", 0);
199
+ await sendMouse(sess, "mousePressed", p1.x, p1.y, btn, 1);
200
+ for (let i = 1; i <= steps; i++) {
201
+ const ix = Math.round(p1.x + ((p2.x - p1.x) * i) / steps);
202
+ const iy = Math.round(p1.y + ((p2.y - p1.y) * i) / steps);
203
+ await sendMouse(sess, "mouseMoved", ix, iy, btn, 0);
204
+ await sleep(10);
205
+ }
206
+ await sendMouse(sess, "mouseReleased", p2.x, p2.y, btn, 1);
207
+ this.cursor = p2;
208
+ return;
209
+ }
210
+ if (action.type === "look") {
211
+ const steps = Math.min(16, Math.max(1, Math.round(action.steps ?? 4)));
212
+ const sx = action.dx / steps;
213
+ const sy = action.dy / steps;
214
+ const locked = sess.Runtime?.evaluate
215
+ ? await sess.Runtime.evaluate({
216
+ expression: "Boolean(document.pointerLockElement)",
217
+ returnByValue: true,
218
+ })
219
+ .then((r) => Boolean(r?.result?.value))
220
+ .catch(() => false)
221
+ : false;
222
+ if (locked) {
223
+ for (let i = 0; i < steps; i++) {
224
+ await sess.Runtime.evaluate({
225
+ expression: `(document.pointerLockElement || document).dispatchEvent(new MouseEvent('mousemove', { bubbles: true, cancelable: true, movementX: ${sx}, movementY: ${sy} }))`,
226
+ returnByValue: false,
227
+ }).catch(() => { });
228
+ await sleep(8);
229
+ }
230
+ return;
231
+ }
232
+ let cur = this.cursor ?? resolvePoint(0.5, 0.5, vp);
233
+ for (let i = 0; i < steps; i++) {
234
+ cur = {
235
+ x: Math.round(Math.max(0, Math.min(Math.max(0, vp.width - 1), cur.x + sx))),
236
+ y: Math.round(Math.max(0, Math.min(Math.max(0, vp.height - 1), cur.y + sy))),
237
+ };
238
+ await sendMouse(sess, "mouseMoved", cur.x, cur.y, "none", 0);
239
+ await sleep(8);
240
+ }
241
+ this.cursor = cur;
242
+ }
243
+ }
244
+ }
package/dist/loop.d.ts ADDED
@@ -0,0 +1,62 @@
1
+ import { type ClipSpec, type GateLike } from "./gate.js";
2
+ import { type GameAction } from "./input.js";
3
+ export interface PlayRule {
4
+ when: string;
5
+ do: GameAction;
6
+ min_conf?: number;
7
+ yield?: boolean;
8
+ cooldown_ms?: number;
9
+ }
10
+ export interface PlaybookArgs {
11
+ rules: PlayRule[] | string;
12
+ steps?: number;
13
+ max_ms?: number;
14
+ interval_ms?: number;
15
+ min_conf?: number;
16
+ yield_on_low_conf?: number;
17
+ stop_if?: string;
18
+ stop_conf?: number;
19
+ stop_check_every?: number;
20
+ clip?: ClipSpec;
21
+ text_selector?: string;
22
+ focus?: string | boolean;
23
+ quality?: number;
24
+ return_frame?: boolean;
25
+ save_frame?: string;
26
+ }
27
+ export interface TransitionSpan {
28
+ from_ms: number;
29
+ to_ms: number;
30
+ ticks: number;
31
+ when: string;
32
+ action: string;
33
+ avg_conf: number;
34
+ }
35
+ export interface PlaybookResult {
36
+ stopped_reason: "steps" | "max_ms" | "rule_yield" | "stop_if" | "low_confidence" | "aborted";
37
+ ticks: number;
38
+ elapsed_ms: number;
39
+ hz: number;
40
+ transitions: TransitionSpan[];
41
+ truncated_transitions?: boolean;
42
+ last_decision: {
43
+ when: string;
44
+ action: string;
45
+ confidence: number;
46
+ } | null;
47
+ saved_frame?: string;
48
+ last_frame_base64?: string;
49
+ }
50
+ export declare function parseRules(raw: PlayRule[] | string): PlayRule[];
51
+ export declare function runPlaybook(sess: any, args: PlaybookArgs, opts?: {
52
+ gate?: GateLike;
53
+ onLine?: (line: string) => void;
54
+ signal?: AbortSignal;
55
+ attachSigint?: boolean;
56
+ defaultConfig?: {
57
+ defaultIntervalMs?: number;
58
+ defaultSteps?: number;
59
+ minConfidence?: number;
60
+ jpegQuality?: number;
61
+ };
62
+ }): Promise<PlaybookResult>;