@weavetab/plugin-gamer 0.1.0 → 1.0.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/README.md CHANGED
@@ -6,6 +6,8 @@ Splits real-time interactive control into two tiers:
6
6
  - **AI Agent (LLM Planner)**: Sets mission goals, defines custom `when -> do` Playbooks, reads compact transition timelines and optional final screenshots, and re-plans between bursts.
7
7
  - **Gate v2.0 (Local Actor, ~8–12 Hz CPU)**: Captures fast CDP JPEG frames (full viewport, pixel/normalized rect, or selector crop) or HUD text, scores choices/guards locally on CPU with zero LLM tokens, and dispatches keyboard, mouse, drag, or pointer-lock camera inputs across browser tabs and Electron apps.
8
8
 
9
+ > **Local Execution & Model Notice:** Installing `@weavetab/plugin-gamer` installs **`@weavetab/gate`** (native Rust + ONNX Runtime binding) and runs decision inference **locally on your computer's CPU**. On first use per modality, `@weavetab/gate` lazily downloads and caches quantized INT8 ONNX weights (`~24.7 MB` vision, `~61.3 MB` text; `~86 MB` combined, Apache-2.0 / MIT derived weights) to `~/.cache/weavetab-gate/` (or `%LOCALAPPDATA%\weavetab-gate`, overridable via `WEAVETAB_GATE_CACHE`). All screenshots, text, and decisions stay local on your machine. Uses Chrome DevTools Protocol (`cdp.screenshot`, `cdp.input`, `cdp.evaluate`) — use only on sites, games, or apps you own or have permission to automate.
10
+
9
11
  ## Install
10
12
 
11
13
  ```bash
@@ -16,20 +18,23 @@ Requires Node.js `>=20.19.0` and `@weavetab/sdk ^2.6.4`.
16
18
 
17
19
  ## CLI Commands (Recommended for Live Streaming)
18
20
 
19
- `weavetab plugin use gamer run` prints one compact line only when the active state or action changes (plus a 2 s heartbeat when unchanged), avoiding context bloat:
21
+ `weavetab plugin use gamer run` prints one compact line only when the active state or action changes (plus a 2 s heartbeat when unchanged), avoiding context bloat. Both compact shell-safe DSL shorthand and `--rules_file` / JSON work out of the box:
20
22
 
21
23
  ```bash
22
24
  weavetab plugin use gamer run \
23
- --rules '[{"when":"clear path ahead","do":{"type":"hold","keys":["w"]}},{"when":"obstacle directly ahead","do":{"type":"tap","keys":["Space"]}}]' \
25
+ --rules "clear green field => hold:w ; red warning box => tap:Space" \
24
26
  --clip canvas \
25
27
  --steps 40 \
26
- --stop_if "a pause menu or round-over screen is visible"
28
+ --stop_if "white pause menu"
29
+
30
+ # or load from JSON file:
31
+ weavetab plugin use gamer run --rules_file playbook.json --clip canvas --save_frame last.jpg
27
32
  ```
28
33
 
29
34
  Single-frame calibration & direct input:
30
35
 
31
36
  ```bash
32
- weavetab plugin use gamer decide --choices '["ready to act","waiting","menu open"]' --clip canvas
37
+ weavetab plugin use gamer decide --choices "ready to act,waiting,menu open" --clip canvas
33
38
  weavetab plugin use gamer act --type drag --x1 0.35 --y1 0.72 --x2 0.35 --y2 0.52
34
39
  ```
35
40
 
package/dist/gate.d.ts CHANGED
@@ -7,6 +7,7 @@ export interface GateLike {
7
7
  export interface Viewport {
8
8
  width: number;
9
9
  height: number;
10
+ zoom: number;
10
11
  }
11
12
  export interface ClipRect {
12
13
  x: number;
@@ -15,19 +16,21 @@ export interface ClipRect {
15
16
  h: number;
16
17
  }
17
18
  export type ClipSpec = string | ClipRect;
18
- /** Lazily loads @weavetab/gate so schema inspection and unit tests avoid eager .node loading. */
19
- export declare function getGate(cfg?: GateConfig): Promise<GateLike>;
20
- export declare function getViewport(sess: any): Promise<Viewport>;
21
- export declare function resolveClip(sess: any, clip: ClipSpec | undefined, vp: Viewport): Promise<{
19
+ export interface CdpClip {
22
20
  x: number;
23
21
  y: number;
24
22
  width: number;
25
23
  height: number;
26
24
  scale: number;
27
- } | undefined>;
25
+ }
26
+ /** Lazily loads @weavetab/gate so schema inspection and unit tests avoid eager .node loading. */
27
+ export declare function getGate(cfg?: GateConfig): Promise<GateLike>;
28
+ export declare function getViewport(sess: any): Promise<Viewport>;
29
+ export declare function resolveClip(sess: any, clip: ClipSpec | undefined, vp: Viewport): Promise<CdpClip | undefined>;
28
30
  export declare function captureFrame(sess: any, opts?: {
29
31
  quality?: number;
30
32
  clip?: ClipSpec;
33
+ resolvedClip?: CdpClip;
31
34
  viewport?: Viewport;
32
35
  }): Promise<{
33
36
  buffer: Buffer;
package/dist/gate.js CHANGED
@@ -13,26 +13,31 @@ export async function getGate(cfg) {
13
13
  }
14
14
  export async function getViewport(sess) {
15
15
  const layout = await sess?.Page?.getLayoutMetrics?.().catch(() => null);
16
+ const zoom = Number(layout?.cssVisualViewport?.zoom) || 1;
16
17
  const vp = layout?.cssLayoutViewport || layout?.layoutViewport || layout?.visualViewport;
17
18
  if (vp?.clientWidth > 0 && vp?.clientHeight > 0) {
18
- return { width: Math.round(vp.clientWidth), height: Math.round(vp.clientHeight) };
19
+ return { width: Math.round(vp.clientWidth), height: Math.round(vp.clientHeight), zoom };
19
20
  }
20
21
  if (sess?.Runtime?.evaluate) {
21
22
  const out = await sess.Runtime.evaluate({
22
- expression: "({w: window.innerWidth || 1280, h: window.innerHeight || 720})",
23
+ expression: "({w: window.innerWidth || 1280, h: window.innerHeight || 720, z: window.devicePixelRatio || 1})",
23
24
  returnByValue: true,
24
25
  }).catch(() => null);
25
26
  const val = out?.result?.value;
26
- if (val?.w > 0 && val?.h > 0)
27
- return { width: Math.round(val.w), height: Math.round(val.h) };
27
+ if (val?.w > 0 && val?.h > 0) {
28
+ return { width: Math.round(val.w), height: Math.round(val.h), zoom: Number(val.z) || 1 };
29
+ }
28
30
  }
29
- return { width: 1280, height: 720 };
31
+ return { width: 1280, height: 720, zoom: 1 };
30
32
  }
31
- function clampRect(x, y, w, h, vp) {
32
- const cx = Math.max(0, Math.min(vp.width - 1, Math.round(x)));
33
- const cy = Math.max(0, Math.min(vp.height - 1, Math.round(y)));
34
- const cw = Math.max(8, Math.min(vp.width - cx, Math.round(w)));
35
- const ch = Math.max(8, Math.min(vp.height - cy, Math.round(h)));
33
+ function clampRect(x, y, w, h, vp, useZoom) {
34
+ const z = useZoom ? vp.zoom || 1 : 1;
35
+ const maxW = Math.max(16, Math.round(vp.width * z));
36
+ const maxH = Math.max(16, Math.round(vp.height * z));
37
+ const cx = Math.max(0, Math.min(maxW - 8, Math.round(x * z)));
38
+ const cy = Math.max(0, Math.min(maxH - 8, Math.round(y * z)));
39
+ const cw = Math.max(8, Math.min(maxW - cx, Math.round(w * z)));
40
+ const ch = Math.max(8, Math.min(maxH - cy, Math.round(h * z)));
36
41
  return { x: cx, y: cy, width: cw, height: ch, scale: 1 };
37
42
  }
38
43
  export async function resolveClip(sess, clip, vp) {
@@ -55,26 +60,31 @@ export async function resolveClip(sess, clip, vp) {
55
60
  }
56
61
  if (!el) return null;
57
62
  const r = el.getBoundingClientRect();
58
- return (r.width >= 8 && r.height >= 8) ? { x: r.left, y: r.top, w: r.width, h: r.height } : null;
63
+ return (r.width >= 8 && r.height >= 8)
64
+ ? { x: r.left + (window.scrollX || 0), y: r.top + (window.scrollY || 0), w: r.width, h: r.height }
65
+ : null;
59
66
  })(${JSON.stringify(clip)})`;
60
67
  const out = await sess.Runtime.evaluate({ expression: expr, returnByValue: true }).catch(() => null);
61
68
  const r = out?.result?.value;
62
- return r ? clampRect(r.x, r.y, r.w, r.h, vp) : undefined;
69
+ return r ? clampRect(r.x, r.y, r.w, r.h, vp, true) : undefined;
63
70
  }
64
71
  const normalized = clip.x >= 0 && clip.y >= 0 && clip.x <= 1 && clip.y <= 1 && clip.w <= 1 && clip.h <= 1;
65
72
  const x = normalized ? clip.x * vp.width : clip.x;
66
73
  const y = normalized ? clip.y * vp.height : clip.y;
67
74
  const w = normalized ? clip.w * vp.width : clip.w;
68
75
  const h = normalized ? clip.h * vp.height : clip.h;
69
- return clampRect(x, y, w, h, vp);
76
+ return clampRect(x, y, w, h, vp, true);
70
77
  }
71
78
  export async function captureFrame(sess, opts = {}) {
72
79
  if (!sess?.Page?.captureScreenshot) {
73
80
  throw new Error("active CDP session does not expose Page.captureScreenshot");
74
81
  }
75
- const vp = opts.viewport ?? (await getViewport(sess));
76
82
  const quality = Math.min(95, Math.max(25, Math.round(opts.quality ?? 65)));
77
- const cdpClip = await resolveClip(sess, opts.clip, vp);
83
+ let cdpClip = opts.resolvedClip;
84
+ if (!cdpClip && opts.clip) {
85
+ const vp = opts.viewport ?? (await getViewport(sess));
86
+ cdpClip = await resolveClip(sess, opts.clip, vp);
87
+ }
78
88
  const res = await sess.Page.captureScreenshot({
79
89
  format: "jpeg",
80
90
  quality,
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export declare function sessOf(ctx: any): any;
2
+ export declare function parseListArg(val: unknown): string[] | undefined;
2
3
  export declare const gamerPlugin: import("@weavetab/sdk").WeavetabPluginDefinition;
3
4
  export default gamerPlugin;
4
5
  export declare const plugin: import("@weavetab/sdk").WeavetabPluginDefinition;
package/dist/index.js CHANGED
@@ -7,21 +7,30 @@ import { parseRules, runPlaybook } from "./loop.js";
7
7
  export function sessOf(ctx) {
8
8
  return ctx?.tab?.session || ctx?.session || ctx;
9
9
  }
10
- function parseListArg(val) {
10
+ export function parseListArg(val) {
11
11
  if (val === undefined)
12
12
  return undefined;
13
13
  if (Array.isArray(val))
14
- return val.map(String);
14
+ return val.map((x) => String(x).trim()).filter(Boolean);
15
15
  if (typeof val === "string") {
16
- const trimmed = val.trim();
16
+ let trimmed = val.trim();
17
17
  if (!trimmed)
18
18
  return undefined;
19
19
  if (trimmed.startsWith("[")) {
20
- const parsed = JSON.parse(trimmed);
21
- if (Array.isArray(parsed))
22
- return parsed.map(String);
20
+ try {
21
+ const parsed = JSON.parse(trimmed);
22
+ if (Array.isArray(parsed))
23
+ return parsed.map((x) => String(x).trim()).filter(Boolean);
24
+ }
25
+ catch {
26
+ // Recover from Windows cmd/PowerShell stripping inner double quotes inside `[a, b, c]`
27
+ trimmed = trimmed.slice(1, trimmed.endsWith("]") ? -1 : undefined);
28
+ }
23
29
  }
24
- return trimmed.split(",").map((s) => s.trim()).filter(Boolean);
30
+ return trimmed
31
+ .split(",")
32
+ .map((s) => s.trim().replace(/^["']|["']$/g, "").trim())
33
+ .filter(Boolean);
25
34
  }
26
35
  return undefined;
27
36
  }
@@ -40,15 +49,19 @@ const RuleSchema = z.object({
40
49
  cooldown_ms: z.number().optional(),
41
50
  });
42
51
  const PlayShape = {
43
- rules: z.union([z.array(RuleSchema), z.string()]).describe("Playbook rules array or JSON string mapping 'when' to 'do'."),
52
+ rules: z
53
+ .union([z.array(RuleSchema), z.string()])
54
+ .optional()
55
+ .describe("Playbook rules array, '@file' path, JSON string, or DSL ('<when> => hold:w ; <when2> => yield')."),
56
+ rules_file: z.string().optional().describe("Path to a JSON playbook file containing a rules array."),
44
57
  steps: z.number().optional().describe("Max decision ticks (1-200, default 30)."),
45
58
  max_ms: z.number().optional().describe("Max burst duration in ms (200-30000, default 6000)."),
46
59
  interval_ms: z.number().optional().describe("Loop interval in ms (50-2000, default 100)."),
47
60
  min_conf: z.number().optional().describe("Minimum Gate confidence (0-1, default 0.45)."),
48
61
  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."),
62
+ stop_if: z.string().optional().describe("Visual label (vision) or declarative statement (text_selector) that stops the burst."),
50
63
  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)."),
64
+ stop_check_every: z.number().optional().describe("Evaluate text stop_if every N ticks (default 1)."),
52
65
  clip: ClipSchema,
53
66
  text_selector: z.string().optional().describe("Optional DOM selector to evaluate via Gate text NLI instead of vision."),
54
67
  focus: z.union([z.string(), z.boolean()]).optional().describe("Selector to focus before burst, or false to skip."),
@@ -56,7 +69,7 @@ const PlayShape = {
56
69
  };
57
70
  const DecideShape = {
58
71
  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."),
72
+ ask: z.string().optional().describe("Declarative claim (text_selector) or visual phrase (vision) for Gate yesNo."),
60
73
  levels: z.union([z.array(z.string()), z.string()]).optional().describe("2-64 ordered rubric levels."),
61
74
  clip: ClipSchema,
62
75
  text_selector: z.string().optional().describe("Optional DOM selector for text NLI instead of vision."),
@@ -145,7 +158,6 @@ async function runSingleAction(sess, args) {
145
158
  const input = new InputController();
146
159
  try {
147
160
  await input.exec(sess, act, vp);
148
- // standalone single hold/mouse_hold holds briefly then releases so keys never stay stuck
149
161
  if (act.type === "hold" || act.type === "mouse_hold") {
150
162
  await new Promise((r) => setTimeout(r, Math.min(5000, Math.max(20, args.hold_ms ?? 300))));
151
163
  }
@@ -153,19 +165,19 @@ async function runSingleAction(sess, args) {
153
165
  finally {
154
166
  await input.releaseAll(sess).catch(() => { });
155
167
  }
156
- return { ok: true, action: act.type, viewport: vp };
168
+ return { ok: true, action: act.type, viewport: { width: vp.width, height: vp.height } };
157
169
  }
158
170
  const runCommand = defineCommand({
159
171
  name: "run",
160
172
  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]",
173
+ usage: "weavetab plugin use gamer run --rules \"clear path => hold:w ; menu visible => yield\" [--clip canvas] [--steps 30] [--stop_if \"pause menu\"]",
162
174
  requiresSession: true,
163
175
  schema: {
164
176
  ...PlayShape,
165
177
  save_frame: z.string().optional().describe("Optional path to save the final JPEG frame."),
166
178
  },
167
179
  handler: async (args, ctx) => {
168
- const res = await runPlaybook(sessOf(ctx), { ...args, rules: parseRules(args.rules), return_frame: false }, {
180
+ const res = await runPlaybook(sessOf(ctx), { ...args, rules: parseRules(args.rules, args.rules_file), return_frame: false }, {
169
181
  attachSigint: true,
170
182
  defaultConfig: ctx?.config,
171
183
  onLine: (line) => process.stdout.write(line + "\n"),
@@ -176,7 +188,7 @@ const runCommand = defineCommand({
176
188
  const decideCommand = defineCommand({
177
189
  name: "decide",
178
190
  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]",
191
+ usage: "weavetab plugin use gamer decide --choices \"label1,label2\" | --ask \"declarative claim\" | --levels \"low,high\" [--clip canvas]",
180
192
  requiresSession: true,
181
193
  schema: {
182
194
  ...DecideShape,
@@ -196,19 +208,19 @@ const decideCommand = defineCommand({
196
208
  const actCommand = defineCommand({
197
209
  name: "act",
198
210
  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\"]'",
211
+ usage: "weavetab plugin use gamer act --type tap|hold|click|mouse_hold|drag|look --keys \"w\"",
200
212
  requiresSession: true,
201
213
  schema: ActShape,
202
214
  handler: async (args, ctx) => runSingleAction(sessOf(ctx), args),
203
215
  });
204
216
  export const gamerPlugin = definePlugin({
205
217
  name: "@weavetab/plugin-gamer",
206
- version: "0.1.0",
218
+ version: "1.0.0",
207
219
  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`.",
220
+ instructions: "Two-tier Planner-Actor control via Gate v2.0 local ONNX (~8-12 Hz CPU, zero tokens):\n" +
221
+ "1. Prefer CLI `weavetab plugin use gamer run --rules \"when1 => hold:w ; when2 => yield\"` (or `--rules_file playbook.json`) for live stdout streaming without context bloat. Use MCP `gamer_play` when you want the final JPEG frame inline.\n" +
222
+ "2. Keep vision `when`/`stop_if` labels short & visual (e.g. 'red warning box', 'white pause menu'); use declarative statements for `text_selector` NLI (`ask`/`stop_if`).\n" +
223
+ "3. Calibrate labels with `gamer_decide` / `decide`; dispatch manual inputs (`hold`, `tap`, `click`, `drag`, `look`) with `gamer_act` / `act`.",
212
224
  defaultConfig: {
213
225
  defaultIntervalMs: 100,
214
226
  defaultSteps: 30,
@@ -253,7 +265,7 @@ export const gamerPlugin = definePlugin({
253
265
  },
254
266
  handler: async (args, rawCtx) => {
255
267
  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 });
268
+ const res = await runPlaybook(sessOf(rawCtx), { ...args, rules: parseRules(args.rules, args.rules_file), return_frame: returnFrame }, { defaultConfig: rawCtx?.config ?? defaultCfg });
257
269
  const { last_frame_base64, ...summary } = res;
258
270
  const content = [
259
271
  { type: "text", text: JSON.stringify(summary, null, 2) },
@@ -305,13 +317,13 @@ export const gamerPlugin = definePlugin({
305
317
  return [
306
318
  `Goal: ${args.goal || "interactive control"}`,
307
319
  `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.`,
320
+ `1. Calibrate short visual labels with gamer_decide (or \`weavetab plugin use gamer decide --clip canvas --choices "a,b"\`).`,
321
+ `2. Run live bursts via CLI \`weavetab plugin use gamer run --rules "a => hold:w ; b => yield" --clip canvas\` or MCP \`gamer_play\`.`,
310
322
  `3. Supported do.type values: hold, tap, click, mouse_hold, drag, look, idle, yield.`,
311
323
  ].join("\n");
312
324
  },
313
325
  }));
314
- ctx.logger?.info("@weavetab/plugin-gamer v0.1.0 loaded");
326
+ ctx.logger?.info("@weavetab/plugin-gamer v1.0.0 loaded");
315
327
  },
316
328
  });
317
329
  export default gamerPlugin;
package/dist/loop.d.ts CHANGED
@@ -8,7 +8,8 @@ export interface PlayRule {
8
8
  cooldown_ms?: number;
9
9
  }
10
10
  export interface PlaybookArgs {
11
- rules: PlayRule[] | string;
11
+ rules?: PlayRule[] | string;
12
+ rules_file?: string;
12
13
  steps?: number;
13
14
  max_ms?: number;
14
15
  interval_ms?: number;
@@ -47,7 +48,7 @@ export interface PlaybookResult {
47
48
  saved_frame?: string;
48
49
  last_frame_base64?: string;
49
50
  }
50
- export declare function parseRules(raw: PlayRule[] | string): PlayRule[];
51
+ export declare function parseRules(raw?: PlayRule[] | string, rulesFile?: string): PlayRule[];
51
52
  export declare function runPlaybook(sess: any, args: PlaybookArgs, opts?: {
52
53
  gate?: GateLike;
53
54
  onLine?: (line: string) => void;
package/dist/loop.js CHANGED
@@ -1,18 +1,101 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
- import { captureFrame, getGate, getViewport, readSelectorText, } from "./gate.js";
3
+ import { captureFrame, getGate, getViewport, readSelectorText, resolveClip, } from "./gate.js";
4
4
  import { describeAction, focusTarget, InputController } from "./input.js";
5
5
  const VALID_ACTIONS = new Set(["hold", "tap", "click", "mouse_hold", "drag", "look", "idle", "yield"]);
6
6
  const MAX_SPANS = 60;
7
7
  const HEARTBEAT_MS = 2000;
8
- export function parseRules(raw) {
8
+ function parseDslAction(spec) {
9
+ const s = spec.trim();
10
+ const [rawKind, p1 = "", p2 = ""] = s.split(":").map((x) => x.trim());
11
+ const kind = rawKind.toLowerCase();
12
+ const splitKeys = (k) => k.split(/[+,]/).map((x) => x.trim()).filter(Boolean);
13
+ const parsePair = (p) => p.split(",").map((x) => Number(x.trim()));
14
+ const asBtn = (v) => v === "left" || v === "right" || v === "middle" ? v : undefined;
15
+ if (kind === "idle")
16
+ return { type: "idle" };
17
+ if (kind === "yield")
18
+ return { type: "yield" };
19
+ if (kind === "hold") {
20
+ const keys = splitKeys(p1);
21
+ if (!keys.length)
22
+ throw new Error(`DSL hold requires keys: "${s}"`);
23
+ return { type: "hold", keys };
24
+ }
25
+ if (kind === "tap") {
26
+ const keys = splitKeys(p1);
27
+ if (!keys.length)
28
+ throw new Error(`DSL tap requires keys: "${s}"`);
29
+ const hold_ms = p2 ? Number(p2) : undefined;
30
+ return { type: "tap", keys, ...(hold_ms && Number.isFinite(hold_ms) ? { hold_ms } : {}) };
31
+ }
32
+ if (kind === "click" || kind === "mouse_hold") {
33
+ let button = asBtn(p1);
34
+ let coords = button ? p2 : p1;
35
+ let x;
36
+ let y;
37
+ if (coords && coords.includes(",")) {
38
+ const [nx, ny] = parsePair(coords);
39
+ if (Number.isFinite(nx) && Number.isFinite(ny)) {
40
+ x = nx;
41
+ y = ny;
42
+ }
43
+ }
44
+ return kind === "mouse_hold" ? { type: "mouse_hold", button, x, y } : { type: "click", button, x, y };
45
+ }
46
+ if (kind === "drag") {
47
+ const [a, b] = p1.split("->").map((x) => x.trim());
48
+ const [x1, y1] = parsePair(a || "");
49
+ const [x2, y2] = parsePair(b || "");
50
+ if (![x1, y1, x2, y2].every(Number.isFinite))
51
+ throw new Error(`DSL drag expects x1,y1->x2,y2: "${s}"`);
52
+ const btn = asBtn(p2);
53
+ return { type: "drag", x1, y1, x2, y2, ...(btn && btn !== "middle" ? { button: btn } : {}) };
54
+ }
55
+ if (kind === "look") {
56
+ const [dx, dy] = parsePair(p1);
57
+ if (!Number.isFinite(dx) || !Number.isFinite(dy))
58
+ throw new Error(`DSL look expects dx,dy: "${s}"`);
59
+ const steps = p2 ? Number(p2) : undefined;
60
+ return { type: "look", dx, dy, ...(steps && Number.isFinite(steps) ? { steps } : {}) };
61
+ }
62
+ throw new Error(`unsupported DSL action "${s}"`);
63
+ }
64
+ function parseDslRules(src) {
65
+ const parts = src.split(/[;|]/).map((s) => s.trim()).filter(Boolean);
66
+ return parts.map((part, idx) => {
67
+ const m = /^(.+?)(?:=>|->)(.+)$/.exec(part);
68
+ if (!m)
69
+ throw new Error(`DSL rule #${idx + 1} must use '<when> => <action>': "${part}"`);
70
+ const doAct = parseDslAction(m[2]);
71
+ return { when: m[1].trim(), do: doAct, yield: doAct.type === "yield" };
72
+ });
73
+ }
74
+ export function parseRules(raw, rulesFile) {
9
75
  let list = raw;
10
- if (typeof raw === "string") {
11
- try {
12
- list = JSON.parse(raw);
76
+ const fileRef = rulesFile?.trim() ||
77
+ (typeof raw === "string" && raw.trim().startsWith("@") ? raw.trim().slice(1).trim() : "");
78
+ if (fileRef) {
79
+ const abs = path.resolve(fileRef);
80
+ const content = fs.readFileSync(abs, "utf8");
81
+ const parsed = JSON.parse(content);
82
+ list = Array.isArray(parsed) ? parsed : parsed?.rules;
83
+ }
84
+ else if (typeof raw === "string") {
85
+ const trimmed = raw.trim();
86
+ if (trimmed.startsWith("[")) {
87
+ try {
88
+ list = JSON.parse(trimmed);
89
+ }
90
+ catch (e) {
91
+ throw new Error(`invalid rules JSON: ${e?.message || e}`);
92
+ }
13
93
  }
14
- catch (e) {
15
- throw new Error(`invalid rules JSON: ${e?.message || e}`);
94
+ else if (trimmed.includes("=>") || trimmed.includes("->")) {
95
+ list = parseDslRules(trimmed);
96
+ }
97
+ else {
98
+ throw new Error("rules string must be JSON array, @file path, or '<when> => <action>' DSL");
16
99
  }
17
100
  }
18
101
  if (!Array.isArray(list) || list.length < 1 || list.length > 32) {
@@ -29,7 +112,7 @@ export function parseRules(raw) {
29
112
  when: r.when.trim(),
30
113
  do: r.do,
31
114
  min_conf: r.min_conf,
32
- yield: Boolean(r.yield),
115
+ yield: Boolean(r.yield || r.do.type === "yield"),
33
116
  cooldown_ms: r.cooldown_ms,
34
117
  };
35
118
  });
@@ -39,7 +122,7 @@ function clamp(n, lo, hi) {
39
122
  }
40
123
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
41
124
  export async function runPlaybook(sess, args, opts = {}) {
42
- const rules = parseRules(args.rules);
125
+ const rules = parseRules(args.rules, args.rules_file);
43
126
  const gate = opts.gate ?? (await getGate());
44
127
  const cfg = opts.defaultConfig ?? {};
45
128
  const maxSteps = Math.round(clamp(args.steps ?? cfg.defaultSteps ?? 30, 1, 200));
@@ -50,12 +133,16 @@ export async function runPlaybook(sess, args, opts = {}) {
50
133
  const stopCheckEvery = Math.round(clamp(args.stop_check_every ?? 1, 1, 20));
51
134
  const quality = Math.round(clamp(args.quality ?? cfg.jpegQuality ?? 65, 25, 95));
52
135
  const vp = await getViewport(sess);
136
+ const resolvedClip = args.clip ? await resolveClip(sess, args.clip, vp) : undefined;
53
137
  await focusTarget(sess, args.focus);
54
138
  const input = new InputController();
55
139
  const transitions = [];
56
140
  let truncated = false;
57
141
  const lastFired = new Map();
58
142
  const choices = rules.map((r) => r.when);
143
+ const stopIf = args.stop_if?.trim() || "";
144
+ const visionStopFolded = Boolean(!args.text_selector && stopIf);
145
+ const visionChoices = visionStopFolded && !choices.includes(stopIf) ? [...choices, stopIf] : choices;
59
146
  let ticks = 0;
60
147
  let lowConfStreak = 0;
61
148
  let stoppedReason = "steps";
@@ -124,29 +211,46 @@ export async function runPlaybook(sess, args, opts = {}) {
124
211
  }
125
212
  const payload = args.text_selector
126
213
  ? await readSelectorText(sess, args.text_selector)
127
- : (await captureFrame(sess, { quality, clip: args.clip, viewport: vp })).buffer;
214
+ : (await captureFrame(sess, { quality, resolvedClip, viewport: vp })).buffer;
128
215
  ticks++;
129
216
  const nowRel = Date.now() - t0;
130
- if (args.stop_if && ticks % stopCheckEvery === 0) {
131
- const guard = gate.yesNo(payload, args.stop_if);
217
+ // In text mode use calibrated NLI yesNo(); in vision mode stop_if folds into decide() below for speed & accuracy.
218
+ if (args.text_selector && stopIf && ticks % stopCheckEvery === 0) {
219
+ const guard = gate.yesNo(payload, stopIf);
132
220
  if (guard.answer && guard.confidence >= stopConf) {
133
- recordSpan(nowRel, `stop_if: ${args.stop_if}`, "yield", guard.confidence);
221
+ recordSpan(nowRel, `stop_if: ${stopIf}`, "yield", guard.confidence);
134
222
  stoppedReason = "stop_if";
135
223
  break;
136
224
  }
137
225
  }
138
226
  let matchedIdx = -1;
139
227
  let conf = 0;
140
- if (rules.length === 1) {
228
+ if (!visionStopFolded && rules.length === 1) {
141
229
  const yn = gate.yesNo(payload, rules[0].when);
142
230
  conf = yn.probability;
143
231
  if (yn.answer)
144
232
  matchedIdx = 0;
145
233
  }
146
234
  else {
147
- const dec = gate.decide(payload, choices);
235
+ const evalChoices = visionStopFolded ? visionChoices : choices;
236
+ const dec = gate.decide(payload, evalChoices);
148
237
  conf = dec.confidence;
149
- matchedIdx = rules.findIndex((r) => r.when === dec.choice);
238
+ if (visionStopFolded && dec.choice === stopIf) {
239
+ if (conf >= stopConf) {
240
+ recordSpan(nowRel, `stop_if: ${stopIf}`, "yield", conf);
241
+ stoppedReason = "stop_if";
242
+ break;
243
+ }
244
+ // Fall back to highest-scoring real rule if stop_if won below stopConf
245
+ const nextBest = dec.scores?.find((s) => s.label !== stopIf && choices.includes(s.label));
246
+ if (nextBest) {
247
+ conf = nextBest.score;
248
+ matchedIdx = rules.findIndex((r) => r.when === nextBest.label);
249
+ }
250
+ }
251
+ else {
252
+ matchedIdx = rules.findIndex((r) => r.when === dec.choice);
253
+ }
150
254
  }
151
255
  const rule = matchedIdx >= 0 ? rules[matchedIdx] : undefined;
152
256
  const neededConf = rule?.min_conf ?? baseMinConf;
@@ -197,7 +301,7 @@ export async function runPlaybook(sess, args, opts = {}) {
197
301
  let savedFramePath;
198
302
  let lastFrameBase64;
199
303
  if (args.return_frame || args.save_frame) {
200
- const snap = await captureFrame(sess, { quality, clip: args.clip, viewport: vp }).catch(() => null);
304
+ const snap = await captureFrame(sess, { quality, resolvedClip, viewport: vp }).catch(() => null);
201
305
  if (snap) {
202
306
  if (args.return_frame)
203
307
  lastFrameBase64 = snap.base64;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@weavetab/plugin-gamer",
3
- "version": "0.1.0",
3
+ "version": "1.0.0",
4
4
  "description": "Official Weavetab local-vision real-time controller plugin powered by Weavetab Gate v2.0 — CLI-first bounded burst playbooks, MCP parity, and universal CDP input for browser and Electron apps.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
package/weavetab.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "displayName": "Gamer",
5
5
  "description": "Local-vision real-time controller powered by Weavetab Gate v2.0 — CLI-first bounded burst playbooks, MCP parity, and universal CDP inputs for 2D/3D/turn-based browser and Electron sessions.",
6
6
  "entry": "dist/index.js",
7
- "instructions": "Two-tier Planner-Actor control using Weavetab Gate v2.0 local ONNX vision/NLI (~8-12 Hz CPU, zero tokens):\n1. You are the strategic planner; Gate is the fast local actor. Write concise visual/text rules ('when' -> 'do') for each bounded burst.\n2. Prefer CLI `weavetab plugin use gamer run --rules '[...]'` for live transition-only stdout streaming without context bloat. Use MCP `gamer_play` when you want the final JPEG frame attached inline to re-plan.\n3. Calibrate labels before bursting with `gamer_decide` (or `weavetab plugin use gamer decide --choices ...`). Use `gamer_act` / `act` for single holds, clicks, drags, or camera turns.\n4. Supports browser tabs and Electron apps, pixel or 0..1 normalized coordinates, selector `clip` (e.g. 'canvas' or '#board'), optional `text_selector` for HUD/DOM NLI, `stop_if` interrupts, and `yield` rules.",
7
+ "instructions": "Two-tier Planner-Actor control via Gate v2.0 local ONNX (~8-12 Hz CPU, zero tokens):\n1. Prefer CLI `weavetab plugin use gamer run --rules \"when1 => hold:w ; when2 => yield\"` (or `--rules_file playbook.json`) for live stdout streaming without context bloat. Use MCP `gamer_play` when you want the final JPEG frame inline.\n2. Keep vision `when`/`stop_if` labels short & visual (e.g. 'red warning box', 'white pause menu'); use declarative statements for `text_selector` NLI (`ask`/`stop_if`).\n3. Calibrate labels with `gamer_decide` / `decide`; dispatch manual inputs (`hold`, `tap`, `click`, `drag`, `look`) with `gamer_act` / `act`.",
8
8
  "tags": [
9
9
  "Gamer",
10
10
  "Vision",
@@ -53,14 +53,17 @@
53
53
  {
54
54
  "name": "run",
55
55
  "description": "Run a bounded real-time Gate v2.0 vision/NLI playbook loop and stream transition-only progress lines to stdout.",
56
- "usage": "weavetab plugin use gamer run --rules '[{\"when\":\"...\",\"do\":{\"type\":\"hold\",\"keys\":[\"w\"]}}]' [--steps 30] [--interval_ms 100] [--clip canvas] [--stop_if \"...\"] [--save_frame out.jpg]",
56
+ "usage": "weavetab plugin use gamer run --rules \"clear path => hold:w ; menu visible => yield\" [--clip canvas] [--steps 30] [--stop_if \"pause menu\"]",
57
57
  "requiresSession": true,
58
58
  "parameters": {
59
59
  "type": "object",
60
- "required": ["rules"],
61
60
  "properties": {
62
61
  "rules": {
63
- "description": "Playbook rules array (or JSON string) mapping 'when' conditions to 'do' actions."
62
+ "description": "Playbook rules array, '@file' path, JSON string, or DSL ('<when> => hold:w ; <when2> => yield')."
63
+ },
64
+ "rules_file": {
65
+ "type": "string",
66
+ "description": "Path to a JSON playbook file containing a rules array."
64
67
  },
65
68
  "steps": {
66
69
  "type": "number",
@@ -84,7 +87,7 @@
84
87
  },
85
88
  "stop_if": {
86
89
  "type": "string",
87
- "description": "Optional Gate yes/no interrupt condition evaluated during the burst."
90
+ "description": "Visual label (vision) or declarative statement (text_selector) that stops the burst."
88
91
  },
89
92
  "stop_conf": {
90
93
  "type": "number",
@@ -118,7 +121,7 @@
118
121
  {
119
122
  "name": "decide",
120
123
  "description": "Capture a single frame (or selector text) and evaluate Gate v2.0 decide, yes/no, or ordered score.",
121
- "usage": "weavetab plugin use gamer decide --choices '[\"a\",\"b\"]' | --ask \"...\" | --levels '[\"low\",\"high\"]' [--clip canvas]",
124
+ "usage": "weavetab plugin use gamer decide --choices \"label1,label2\" | --ask \"declarative claim\" | --levels \"low,high\" [--clip canvas]",
122
125
  "requiresSession": true,
123
126
  "parameters": {
124
127
  "type": "object",
@@ -128,7 +131,7 @@
128
131
  },
129
132
  "ask": {
130
133
  "type": "string",
131
- "description": "Declarative statement for Gate yesNo."
134
+ "description": "Declarative claim (text_selector) or visual phrase (vision) for Gate yesNo."
132
135
  },
133
136
  "levels": {
134
137
  "description": "2-64 ordered rubric levels (array or JSON string) for Gate score."
@@ -154,7 +157,7 @@
154
157
  {
155
158
  "name": "act",
156
159
  "description": "Dispatch an immediate CDP keyboard, mouse, drag, or camera-look action on the active tab or Electron window.",
157
- "usage": "weavetab plugin use gamer act --type tap|hold|click|mouse_hold|drag|look --keys '[\"w\"]' [--x 0.5] [--y 0.5]",
160
+ "usage": "weavetab plugin use gamer act --type tap|hold|click|mouse_hold|drag|look --keys \"w\"",
158
161
  "requiresSession": true,
159
162
  "parameters": {
160
163
  "type": "object",
@@ -210,7 +213,6 @@
210
213
  "requiresSession": true,
211
214
  "inputSchema": {
212
215
  "type": "object",
213
- "required": ["rules"],
214
216
  "properties": {
215
217
  "rules": {
216
218
  "type": "array",
@@ -227,6 +229,7 @@
227
229
  }
228
230
  }
229
231
  },
232
+ "rules_file": { "type": "string", "description": "Optional path to a JSON playbook file." },
230
233
  "steps": { "type": "number", "description": "Max decision ticks (1-200, default 30)." },
231
234
  "max_ms": { "type": "number", "description": "Max burst duration in ms (200-30000, default 6000)." },
232
235
  "interval_ms": { "type": "number", "description": "Loop interval in ms (50-2000, default 100)." },