@weavetab/plugin-gamer 0.0.0-stage → 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/dist/loop.d.ts ADDED
@@ -0,0 +1,63 @@
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
+ rules_file?: string;
13
+ steps?: number;
14
+ max_ms?: number;
15
+ interval_ms?: number;
16
+ min_conf?: number;
17
+ yield_on_low_conf?: number;
18
+ stop_if?: string;
19
+ stop_conf?: number;
20
+ stop_check_every?: number;
21
+ clip?: ClipSpec;
22
+ text_selector?: string;
23
+ focus?: string | boolean;
24
+ quality?: number;
25
+ return_frame?: boolean;
26
+ save_frame?: string;
27
+ }
28
+ export interface TransitionSpan {
29
+ from_ms: number;
30
+ to_ms: number;
31
+ ticks: number;
32
+ when: string;
33
+ action: string;
34
+ avg_conf: number;
35
+ }
36
+ export interface PlaybookResult {
37
+ stopped_reason: "steps" | "max_ms" | "rule_yield" | "stop_if" | "low_confidence" | "aborted";
38
+ ticks: number;
39
+ elapsed_ms: number;
40
+ hz: number;
41
+ transitions: TransitionSpan[];
42
+ truncated_transitions?: boolean;
43
+ last_decision: {
44
+ when: string;
45
+ action: string;
46
+ confidence: number;
47
+ } | null;
48
+ saved_frame?: string;
49
+ last_frame_base64?: string;
50
+ }
51
+ export declare function parseRules(raw?: PlayRule[] | string, rulesFile?: string): PlayRule[];
52
+ export declare function runPlaybook(sess: any, args: PlaybookArgs, opts?: {
53
+ gate?: GateLike;
54
+ onLine?: (line: string) => void;
55
+ signal?: AbortSignal;
56
+ attachSigint?: boolean;
57
+ defaultConfig?: {
58
+ defaultIntervalMs?: number;
59
+ defaultSteps?: number;
60
+ minConfidence?: number;
61
+ jpegQuality?: number;
62
+ };
63
+ }): Promise<PlaybookResult>;
package/dist/loop.js ADDED
@@ -0,0 +1,328 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { captureFrame, getGate, getViewport, readSelectorText, resolveClip, } from "./gate.js";
4
+ import { describeAction, focusTarget, InputController } from "./input.js";
5
+ const VALID_ACTIONS = new Set(["hold", "tap", "click", "mouse_hold", "drag", "look", "idle", "yield"]);
6
+ const MAX_SPANS = 60;
7
+ const HEARTBEAT_MS = 2000;
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) {
75
+ let list = 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
+ }
93
+ }
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");
99
+ }
100
+ }
101
+ if (!Array.isArray(list) || list.length < 1 || list.length > 32) {
102
+ throw new Error("rules must contain between 1 and 32 entries");
103
+ }
104
+ return list.map((r, idx) => {
105
+ if (!r || typeof r.when !== "string" || !r.when.trim()) {
106
+ throw new Error(`rules[${idx}].when must be a non-empty string`);
107
+ }
108
+ if (!r.do || typeof r.do !== "object" || !VALID_ACTIONS.has(r.do.type)) {
109
+ throw new Error(`rules[${idx}].do.type is invalid`);
110
+ }
111
+ return {
112
+ when: r.when.trim(),
113
+ do: r.do,
114
+ min_conf: r.min_conf,
115
+ yield: Boolean(r.yield || r.do.type === "yield"),
116
+ cooldown_ms: r.cooldown_ms,
117
+ };
118
+ });
119
+ }
120
+ function clamp(n, lo, hi) {
121
+ return Math.min(hi, Math.max(lo, n));
122
+ }
123
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
124
+ export async function runPlaybook(sess, args, opts = {}) {
125
+ const rules = parseRules(args.rules, args.rules_file);
126
+ const gate = opts.gate ?? (await getGate());
127
+ const cfg = opts.defaultConfig ?? {};
128
+ const maxSteps = Math.round(clamp(args.steps ?? cfg.defaultSteps ?? 30, 1, 200));
129
+ const maxMs = Math.round(clamp(args.max_ms ?? 6000, 200, 30000));
130
+ const intervalMs = Math.round(clamp(args.interval_ms ?? cfg.defaultIntervalMs ?? 100, 50, 2000));
131
+ const baseMinConf = clamp(args.min_conf ?? cfg.minConfidence ?? 0.45, 0, 1);
132
+ const stopConf = clamp(args.stop_conf ?? 0.65, 0, 1);
133
+ const stopCheckEvery = Math.round(clamp(args.stop_check_every ?? 1, 1, 20));
134
+ const quality = Math.round(clamp(args.quality ?? cfg.jpegQuality ?? 65, 25, 95));
135
+ const vp = await getViewport(sess);
136
+ const resolvedClip = args.clip ? await resolveClip(sess, args.clip, vp) : undefined;
137
+ await focusTarget(sess, args.focus);
138
+ const input = new InputController();
139
+ const transitions = [];
140
+ let truncated = false;
141
+ const lastFired = new Map();
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;
146
+ let ticks = 0;
147
+ let lowConfStreak = 0;
148
+ let stoppedReason = "steps";
149
+ let lastDecision = null;
150
+ let aborted = false;
151
+ let prevEmittedKey = "";
152
+ let prevEmitMs = -HEARTBEAT_MS;
153
+ let repeatCount = 0;
154
+ const sigintHandler = () => {
155
+ aborted = true;
156
+ };
157
+ if (opts.attachSigint)
158
+ process.once("SIGINT", sigintHandler);
159
+ const t0 = Date.now();
160
+ const recordSpan = (nowMs, when, action, conf) => {
161
+ const last = transitions[transitions.length - 1];
162
+ if (last && last.when === when && last.action === action) {
163
+ const nextTicks = last.ticks + 1;
164
+ last.avg_conf = Math.round(((last.avg_conf * last.ticks + conf) / nextTicks) * 1000) / 1000;
165
+ last.ticks = nextTicks;
166
+ last.to_ms = nowMs;
167
+ repeatCount++;
168
+ }
169
+ else {
170
+ repeatCount = 1;
171
+ if (transitions.length < MAX_SPANS) {
172
+ transitions.push({
173
+ from_ms: nowMs,
174
+ to_ms: nowMs,
175
+ ticks: 1,
176
+ when,
177
+ action,
178
+ avg_conf: Math.round(conf * 1000) / 1000,
179
+ });
180
+ }
181
+ else {
182
+ truncated = true;
183
+ }
184
+ }
185
+ lastDecision = { when, action, confidence: Math.round(conf * 1000) / 1000 };
186
+ if (opts.onLine) {
187
+ const key = `${when}\0${action}`;
188
+ const sec = (nowMs / 1000).toFixed(1);
189
+ if (key !== prevEmittedKey) {
190
+ opts.onLine(`[+${sec}s] "${when}" (${conf.toFixed(2)}) -> ${action}`);
191
+ prevEmittedKey = key;
192
+ prevEmitMs = nowMs;
193
+ }
194
+ else if (nowMs - prevEmitMs >= HEARTBEAT_MS) {
195
+ opts.onLine(`[+${sec}s] (still x${repeatCount}) "${when}" (${conf.toFixed(2)}) -> ${action}`);
196
+ prevEmitMs = nowMs;
197
+ }
198
+ }
199
+ };
200
+ try {
201
+ while (ticks < maxSteps) {
202
+ if (aborted || opts.signal?.aborted) {
203
+ stoppedReason = "aborted";
204
+ break;
205
+ }
206
+ const tickStart = Date.now();
207
+ const elapsed = tickStart - t0;
208
+ if (ticks > 0 && elapsed >= maxMs) {
209
+ stoppedReason = "max_ms";
210
+ break;
211
+ }
212
+ const payload = args.text_selector
213
+ ? await readSelectorText(sess, args.text_selector)
214
+ : (await captureFrame(sess, { quality, resolvedClip, viewport: vp })).buffer;
215
+ ticks++;
216
+ const nowRel = Date.now() - t0;
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);
220
+ if (guard.answer && guard.confidence >= stopConf) {
221
+ recordSpan(nowRel, `stop_if: ${stopIf}`, "yield", guard.confidence);
222
+ stoppedReason = "stop_if";
223
+ break;
224
+ }
225
+ }
226
+ let matchedIdx = -1;
227
+ let conf = 0;
228
+ if (!visionStopFolded && rules.length === 1) {
229
+ const yn = gate.yesNo(payload, rules[0].when);
230
+ conf = yn.probability;
231
+ if (yn.answer)
232
+ matchedIdx = 0;
233
+ }
234
+ else {
235
+ const evalChoices = visionStopFolded ? visionChoices : choices;
236
+ const dec = gate.decide(payload, evalChoices);
237
+ conf = dec.confidence;
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
+ }
254
+ }
255
+ const rule = matchedIdx >= 0 ? rules[matchedIdx] : undefined;
256
+ const neededConf = rule?.min_conf ?? baseMinConf;
257
+ if (!rule || conf < neededConf) {
258
+ lowConfStreak++;
259
+ await input.releaseAll(sess);
260
+ recordSpan(nowRel, "(low_conf)", "idle", conf);
261
+ if (args.yield_on_low_conf && lowConfStreak >= args.yield_on_low_conf) {
262
+ stoppedReason = "low_confidence";
263
+ break;
264
+ }
265
+ }
266
+ else {
267
+ lowConfStreak = 0;
268
+ const prevFire = lastFired.get(matchedIdx) ?? -1e9;
269
+ if (rule.cooldown_ms && Date.now() - prevFire < rule.cooldown_ms) {
270
+ recordSpan(nowRel, rule.when, "cooldown", conf);
271
+ }
272
+ else {
273
+ lastFired.set(matchedIdx, Date.now());
274
+ const actLabel = describeAction(rule.do);
275
+ if (rule.yield || rule.do.type === "yield") {
276
+ if (rule.do.type !== "yield") {
277
+ await input.exec(sess, rule.do, vp);
278
+ }
279
+ else {
280
+ await input.releaseAll(sess);
281
+ }
282
+ recordSpan(nowRel, rule.when, actLabel, conf);
283
+ stoppedReason = "rule_yield";
284
+ break;
285
+ }
286
+ await input.exec(sess, rule.do, vp);
287
+ recordSpan(nowRel, rule.when, actLabel, conf);
288
+ }
289
+ }
290
+ const spent = Date.now() - tickStart;
291
+ if (ticks < maxSteps && spent < intervalMs) {
292
+ await sleep(intervalMs - spent);
293
+ }
294
+ }
295
+ }
296
+ finally {
297
+ await input.releaseAll(sess).catch(() => { });
298
+ if (opts.attachSigint)
299
+ process.removeListener("SIGINT", sigintHandler);
300
+ }
301
+ let savedFramePath;
302
+ let lastFrameBase64;
303
+ if (args.return_frame || args.save_frame) {
304
+ const snap = await captureFrame(sess, { quality, resolvedClip, viewport: vp }).catch(() => null);
305
+ if (snap) {
306
+ if (args.return_frame)
307
+ lastFrameBase64 = snap.base64;
308
+ if (args.save_frame) {
309
+ const abs = path.resolve(args.save_frame);
310
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
311
+ fs.writeFileSync(abs, snap.buffer);
312
+ savedFramePath = abs;
313
+ }
314
+ }
315
+ }
316
+ const totalMs = Math.max(1, Date.now() - t0);
317
+ return {
318
+ stopped_reason: stoppedReason,
319
+ ticks,
320
+ elapsed_ms: totalMs,
321
+ hz: Math.round((ticks * 1000 * 10) / totalMs) / 10,
322
+ transitions,
323
+ ...(truncated ? { truncated_transitions: true } : {}),
324
+ last_decision: lastDecision,
325
+ ...(savedFramePath ? { saved_frame: savedFramePath } : {}),
326
+ ...(lastFrameBase64 ? { last_frame_base64: lastFrameBase64 } : {}),
327
+ };
328
+ }
package/package.json CHANGED
@@ -1,6 +1,65 @@
1
1
  {
2
2
  "name": "@weavetab/plugin-gamer",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
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
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "import": "./dist/index.js",
11
+ "types": "./dist/index.d.ts"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist",
16
+ "weavetab.json",
17
+ "README.md",
18
+ "LICENSE"
19
+ ],
20
+ "scripts": {
21
+ "build": "tsc",
22
+ "typecheck": "tsc --noEmit",
23
+ "preflight": "weavetab-sdk preflight",
24
+ "test": "node --test test/*.test.mjs",
25
+ "prepublishOnly": "npm run build && npm run preflight"
26
+ },
27
+ "dependencies": {
28
+ "@weavetab/gate": "^2.0.0",
29
+ "@weavetab/sdk": "^2.6.4"
30
+ },
31
+ "devDependencies": {
32
+ "@types/node": "^22.10.0",
33
+ "typescript": "^5.5.0"
34
+ },
35
+ "keywords": [
36
+ "weavetab",
37
+ "weavetab-plugin",
38
+ "weavetab-official",
39
+ "gate",
40
+ "vision",
41
+ "realtime",
42
+ "cdp",
43
+ "electron",
44
+ "automation"
45
+ ],
46
+ "author": {
47
+ "name": "Weavetab",
48
+ "url": "https://weavetab.dev"
49
+ },
50
+ "license": "Apache-2.0",
51
+ "repository": {
52
+ "type": "git",
53
+ "url": "git+https://github.com/Weavetab/Gamer.git"
54
+ },
55
+ "bugs": {
56
+ "url": "https://github.com/Weavetab/Gamer/issues"
57
+ },
58
+ "homepage": "https://github.com/Weavetab/Gamer#readme",
59
+ "engines": {
60
+ "node": ">=20.19.0"
61
+ },
62
+ "publishConfig": {
63
+ "access": "public"
64
+ }
65
+ }