@tea-agent/loop-agent 0.55.0-next.2 → 0.55.0-next.4
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/CHANGELOG.md +9 -1
- package/dist/build-stamp.json +3 -3
- package/dist/worker/console/chat/browser-automation.js +497 -23
- package/dist/worker/console/chat/browser-cdp.js +145 -0
- package/dist/worker/console/chat/browser-evaluation.js +26 -25
- package/dist/worker/console/chat/browser-exposure.js +7 -6
- package/dist/worker/console/chat/browser-la.js +266 -0
- package/dist/worker/console/chat/browser-policy.js +5 -4
- package/dist/worker/console/chat/browser-preload.js +119 -0
- package/dist/worker/console/chat/browser-preloads/vcp.js +417 -0
- package/dist/worker/console/chat/browser-region-fingerprint.js +36 -0
- package/dist/worker/console/chat/browser-run.js +97 -0
- package/dist/worker/console/chat/browser-screenshot-result.js +2 -2
- package/dist/worker/console/chat/browser-scripts.js +42 -4
- package/dist/worker/console/chat/browser-timeline.js +4 -0
- package/dist/worker/console/chat/pi-runtime/custom-tools/browser-tools.js +72 -9
- package/dist/worker/console/chat/pi-runtime/sdk-bindings.js +70 -0
- package/dist/worker/console/chat/pi-runtime.js +24 -3
- package/dist/worker/console/chat/png-fingerprint.js +189 -0
- package/dist/worker/console/chat/repo-browser.js +4 -1
- package/dist/worker/console/chat/routes.js +30 -38
- package/dist/worker/console/chat/session-store.js +7 -21
- package/dist/worker/console/chat/terminal-sessions.js +1 -1
- package/dist/worker/console/chat/terminal-tools.js +1 -0
- package/dist/worker/console/chat/tool-exposure-catalog.js +2 -2
- package/dist/worker/console/chat/tools.js +2 -0
- package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-C29lbS0T.js → abnfDiagram-N423BO3Z-DorTQneS.js} +1 -1
- package/dist/worker/console/static/assets/{arc--Vi-BzUR.js → arc-C9C1QC-T.js} +1 -1
- package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-DwdFPJd-.js → architectureDiagram-T3A2C74G-BjUOrgf8.js} +1 -1
- package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-BFuPq4yu.js → blockDiagram-VBNYF7ZC-BAGMZaHb.js} +1 -1
- package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-oKn9EfQa.js → c4Diagram-5PPSVZJV-CySIZtrC.js} +1 -1
- package/dist/worker/console/static/assets/channel-BG_uDZNA.js +1 -0
- package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-TwXtrEhU.js → chunk-2GRJ4B5K-BkmWz795.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-Cc3zFHjT.js → chunk-2Q5K7J3B-CRmOCK3j.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-5RXB4S5H-xJfu4YKo.js → chunk-5RXB4S5H-B8niEWUo.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-5VM5RSS4-VBNdtRqb.js → chunk-5VM5RSS4-Y8foS4t5.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-DxhJidW7.js → chunk-6Q2QTUOP-DJF0Bubr.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-GF5L2VYU-P6N3qPX5.js → chunk-GF5L2VYU-EKpddtbq.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-JWPE2WC7-LE21hHhq.js → chunk-JWPE2WC7-CIgPpaGU.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-KBJHAD2P-CZmtvzKZ.js → chunk-KBJHAD2P-DYMTSX0m.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-RYQCIY6F-BQrw57-q.js → chunk-RYQCIY6F-4Rc5-0f5.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-XXDRQBXY-DSNQHlxO.js → chunk-XXDRQBXY-CEy2M6-D.js} +1 -1
- package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-jTs8Eyzt.js +1 -0
- package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-jTs8Eyzt.js +1 -0
- package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-Ckm2oC4s.js → cose-bilkent-JH36ORCC-C51nJqVR.js} +1 -1
- package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-B7ecDXon.js → cynefinDiagram-MW4NZA55-DPQzOJZA.js} +1 -1
- package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-Cx_kCtwr.js → dagre-VZM6K2ZE-CG8IAqCo.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-7IWD3JNH-DTqfz-9k.js → diagram-7IWD3JNH-BG3tT1MS.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-BH8nNNYl.js → diagram-B4RE2ZJO-DKOhR49M.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-LBJQPF4R-mwUmtiIR.js → diagram-LBJQPF4R--nGLO7eB.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-Q27KOJAE-B6_cW-cc.js → diagram-Q27KOJAE-CNDuz0fc.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-UB23O5K3-D1sGiHf5.js → diagram-UB23O5K3-BvEiy0I0.js} +1 -1
- package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-C07tYieV.js → ebnfDiagram-BXEA7PRR-BvjtUlUv.js} +1 -1
- package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-eHwocxI1.js → erDiagram-JOGREHBK-B-r_PRCK.js} +1 -1
- package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-B1B-mb0t.js → flowDiagram-UKHOOZJN-DlGW_rBu.js} +1 -1
- package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-B2fpno6f.js → ganttDiagram-PKOTCBZU-CcJKXiNh.js} +1 -1
- package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-DcM98HR9.js → gitGraphDiagram-DS77QQ5N-BXWxDYEd.js} +1 -1
- package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-edHmAaaC.js → infoDiagram-6WML65LV-asY8RPy4.js} +1 -1
- package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-Df_rsjoZ.js → ishikawaDiagram-WSZJBQD7-6yhDpeCu.js} +1 -1
- package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-BqK30536.js → journeyDiagram-NVQOT4AX-KybqaztS.js} +1 -1
- package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-DCvcYw-F.js → kanban-definition-27J2QSJJ-BUdunoPK.js} +1 -1
- package/dist/worker/console/static/assets/{linear-4rMK0UAe.js → linear-BAwJ_AJw.js} +1 -1
- package/dist/worker/console/static/assets/main-CIG4h5Yv.css +1 -0
- package/dist/worker/console/static/assets/{main-CBjwyx0a.js → main-CoWJVNrX.js} +141 -141
- package/dist/worker/console/static/assets/{mermaid.core-CIeuqFlz.js → mermaid.core-BwGdPtCr.js} +4 -4
- package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-isklXv_u.js → mindmap-definition-FAOFIHXS-wo8SEwby.js} +1 -1
- package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-DufJ3B32.js → pegDiagram-VL7TDLO6-DeuXnF7o.js} +1 -1
- package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-e-dscJOX.js → pieDiagram-7S7Q4E2Y-Hn7SpOAL.js} +1 -1
- package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-BMXdwlfZ.js → quadrantDiagram-CIZ2JOQS-WZ9z9PP1.js} +1 -1
- package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-BkLHnA2m.js → railroadDiagram-AXF67PYL-Dl4Y5VeR.js} +1 -1
- package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-BzXmvm6l.js → requirementDiagram-LRYGKXZP-B-3z0VEC.js} +1 -1
- package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-BZuur-BM.js → sankeyDiagram-W5VNT64P-D5LDd4et.js} +1 -1
- package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-DbZxmtRn.js → sequenceDiagram-SI44F4Z6-CeeqbPrw.js} +1 -1
- package/dist/worker/console/static/assets/{sheet-workbook-D_6Enbgn.js → sheet-workbook-BVfUI4fR.js} +1 -1
- package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-BHbP5ADt.js → sizeCapture-X5ZJPWSS-DdhhZwAv.js} +1 -1
- package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-CGNrvQQV.js → stateDiagram-OKZ733FA-DNTAm9ba.js} +1 -1
- package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-B5Xi7PDb.js +1 -0
- package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-BWNaMfHj.js → swimlanes-SLNWSIFB-D8Jdwx7C.js} +2 -2
- package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-DaLAC9v3.js +8 -0
- package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-BhI167N4.js → timeline-definition-Z64GVDOM-BaI43sL9.js} +1 -1
- package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-BFHqLPNk.js → vennDiagram-T6HMQDX7-D5uEn-T3.js} +1 -1
- package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-D-ThxcCm.js → wardleyDiagram-T6FBY63Y-D76Tmp1x.js} +1 -1
- package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-CeUzoGed.js → xychartDiagram-ELKLHX3M-Bv8QF2pr.js} +1 -1
- package/dist/worker/console/static/index.html +2 -2
- package/dist/worker/console/static-src/operator-chat/useChatSessions.js +140 -34
- package/dist/worker/console/static-src/operator-chat/useChatStream.js +6 -0
- package/dist/worker/console/static-src/operator-chat/useChatThread.js +5 -0
- package/docs/architecture/runtime-boundaries.md +5 -0
- package/package.json +3 -3
- package/dist/worker/console/static/assets/channel-o_uspxIc.js +0 -1
- package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-BAMhQfS-.js +0 -1
- package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-BAMhQfS-.js +0 -1
- package/dist/worker/console/static/assets/main-CGnkpKqw.css +0 -1
- package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-Oa0mw2RA.js +0 -1
- package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-CylkK52a.js +0 -8
|
@@ -0,0 +1,417 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Built-in "vcp" preload for the Ping An SPICE web client.
|
|
3
|
+
*
|
|
4
|
+
* Findings, protocol layout and the "why" behind every default here:
|
|
5
|
+
* `docs/design/active/2026-11-20-browser-preload-injection.md`.
|
|
6
|
+
*
|
|
7
|
+
* The client keeps its protocol socket on the page (a native WebSocket at
|
|
8
|
+
* `wss://cag-dcloud.pingan.com.cn:8899/`), so the wire tap lives in the page,
|
|
9
|
+
* not in a Worker. Worker rewriting is therefore OFF by default: running a
|
|
10
|
+
* worker from a blob URL changes its base URL and breaks streaming workers,
|
|
11
|
+
* which shows up as the desktop hanging on "正在连接".
|
|
12
|
+
*
|
|
13
|
+
* The client keeps its protocol socket inside a module Worker
|
|
14
|
+
* (`dist/webcodecs.worker.js`), so a page-level patch can neither see inbound
|
|
15
|
+
* agent messages nor answer them. This preload runs at document-start, wraps
|
|
16
|
+
* `window.Worker`, and re-creates each worker from a blob that first imports
|
|
17
|
+
* the original script and then installs a tap inside the worker.
|
|
18
|
+
*
|
|
19
|
+
* The tap is deliberately passive: frames are appended to IndexedDB instead of
|
|
20
|
+
* being forwarded through `postMessage`, so the client's own message handler
|
|
21
|
+
* never sees an unexpected message and cannot break.
|
|
22
|
+
*
|
|
23
|
+
* Usage: LOOP_BROWSER_PRELOAD=builtin:vcp
|
|
24
|
+
*
|
|
25
|
+
* Known limit: the clipboard encoder below sends correctly formed agent frames
|
|
26
|
+
* but the portal proxy does not forward the agent channel to browser sessions
|
|
27
|
+
* (`clipboard.probe()` returns verdict `guest-silent`), so paste over the web
|
|
28
|
+
* client does not work. Keep it for diagnostics and for the day the proxy
|
|
29
|
+
* starts forwarding; do not build product features on it.
|
|
30
|
+
*/
|
|
31
|
+
/** Token accepted in LOOP_BROWSER_PRELOAD. */
|
|
32
|
+
export const VCP_PRELOAD_ID = "builtin:vcp";
|
|
33
|
+
/** Runs inside the worker: taps WebSocket traffic into IndexedDB. */
|
|
34
|
+
const WORKER_TAP = `(function () {
|
|
35
|
+
try {
|
|
36
|
+
var DB = 'vcp-tap', STORE = 'frames', LIMIT = 500;
|
|
37
|
+
var db = null; function open() {
|
|
38
|
+
return new Promise(function (resolve, reject) {
|
|
39
|
+
var request = indexedDB.open(DB, 1);
|
|
40
|
+
request.onupgradeneeded = function () {
|
|
41
|
+
if (!request.result.objectStoreNames.contains(STORE)) request.result.createObjectStore(STORE, { autoIncrement: true });
|
|
42
|
+
};
|
|
43
|
+
request.onsuccess = function () { resolve(request.result); };
|
|
44
|
+
request.onerror = function () { reject(request.error); };
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
function push(record) {
|
|
48
|
+
if (!db) return;
|
|
49
|
+
try { db.transaction(STORE, 'readwrite').objectStore(STORE).add(record); } catch (e) {}
|
|
50
|
+
}
|
|
51
|
+
function sizeOf(data) {
|
|
52
|
+
if (!data) return 0;
|
|
53
|
+
if (typeof data === 'string') return data.length;
|
|
54
|
+
if (typeof data.byteLength === 'number') return data.byteLength;
|
|
55
|
+
return 0;
|
|
56
|
+
}
|
|
57
|
+
open().then(function (handle) {
|
|
58
|
+
db = handle;
|
|
59
|
+
push({ kind: 'patched', at: Date.now() });
|
|
60
|
+
}).catch(function () {});
|
|
61
|
+
var Native = globalThis.WebSocket;
|
|
62
|
+
if (Native && !Native.__vcpTapped) {
|
|
63
|
+
var Tap = function (url, protocols) {
|
|
64
|
+
var socket = protocols === undefined ? new Native(url) : new Native(url, protocols);
|
|
65
|
+
try {
|
|
66
|
+
push({ kind: 'open', url: String(url), at: Date.now() });
|
|
67
|
+
socket.addEventListener('message', function (event) { push({ kind: 'in', size: sizeOf(event.data), at: Date.now() }); });
|
|
68
|
+
var send = socket.send.bind(socket);
|
|
69
|
+
socket.send = function (data) { push({ kind: 'out', size: sizeOf(data), at: Date.now() }); return send(data); };
|
|
70
|
+
} catch (e) {}
|
|
71
|
+
return socket;
|
|
72
|
+
};
|
|
73
|
+
Tap.prototype = Native.prototype;
|
|
74
|
+
Tap.CONNECTING = 0; Tap.OPEN = 1; Tap.CLOSING = 2; Tap.CLOSED = 3;
|
|
75
|
+
Tap.__vcpTapped = true;
|
|
76
|
+
globalThis.WebSocket = Tap;
|
|
77
|
+
}
|
|
78
|
+
} catch (error) {
|
|
79
|
+
try { console.error('[vcp] worker tap failed', error); } catch (e) {}
|
|
80
|
+
}
|
|
81
|
+
})();
|
|
82
|
+
`;
|
|
83
|
+
/**
|
|
84
|
+
* Sits in front of the dynamic import so that messages posted immediately
|
|
85
|
+
* after `new Worker(...)` are not lost while the original script is still
|
|
86
|
+
* loading. The client posts its bootstrap message right after construction, so
|
|
87
|
+
* a dropped message means a dead connection.
|
|
88
|
+
*/
|
|
89
|
+
const WORKER_QUEUE_SHIM = `(function () {
|
|
90
|
+
try {
|
|
91
|
+
var queued = [];
|
|
92
|
+
var handler = null;
|
|
93
|
+
var flush = function () {
|
|
94
|
+
while (handler && queued.length) {
|
|
95
|
+
var payload = queued.shift();
|
|
96
|
+
try { handler({ data: payload }); } catch (e) {}
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
self.addEventListener('message', function (event) {
|
|
100
|
+
if (handler) return;
|
|
101
|
+
if (queued.length < 64) queued.push(event.data);
|
|
102
|
+
});
|
|
103
|
+
var existing = Object.getOwnPropertyDescriptor(self, 'onmessage');
|
|
104
|
+
Object.defineProperty(self, 'onmessage', {
|
|
105
|
+
configurable: true,
|
|
106
|
+
enumerable: true,
|
|
107
|
+
get: function () { return handler; },
|
|
108
|
+
set: function (fn) { handler = typeof fn === 'function' ? fn : null; flush(); },
|
|
109
|
+
});
|
|
110
|
+
void existing;
|
|
111
|
+
} catch (error) {
|
|
112
|
+
try { console.error('[vcp] queue shim failed', error); } catch (e) {}
|
|
113
|
+
}
|
|
114
|
+
})();
|
|
115
|
+
`;
|
|
116
|
+
const PAGE_SIDE = `(function () {
|
|
117
|
+
if (window.__vcpPreload) return;
|
|
118
|
+
var NativeWorker = window.Worker;
|
|
119
|
+
|
|
120
|
+
// The SPICE client opens its protocol socket on the page (not in a worker),
|
|
121
|
+
// so the wire tap has to live here as well.
|
|
122
|
+
(function tapPageSocket() {
|
|
123
|
+
var NativeSocket = window.WebSocket;
|
|
124
|
+
if (typeof NativeSocket !== 'function' || NativeSocket.__vcpTapped) return;
|
|
125
|
+
function record(record) {
|
|
126
|
+
try {
|
|
127
|
+
var request = indexedDB.open('vcp-tap', 1);
|
|
128
|
+
request.onupgradeneeded = function () {
|
|
129
|
+
if (!request.result.objectStoreNames.contains('frames')) request.result.createObjectStore('frames', { autoIncrement: true });
|
|
130
|
+
};
|
|
131
|
+
request.onsuccess = function () {
|
|
132
|
+
try { request.result.transaction('frames', 'readwrite').objectStore('frames').add(record); } catch (e) {}
|
|
133
|
+
};
|
|
134
|
+
} catch (e) {}
|
|
135
|
+
}
|
|
136
|
+
function sizeOf(data) {
|
|
137
|
+
if (!data) return 0;
|
|
138
|
+
if (typeof data === 'string') return data.length;
|
|
139
|
+
if (typeof data.byteLength === 'number') return data.byteLength;
|
|
140
|
+
return 0;
|
|
141
|
+
}
|
|
142
|
+
function headOf(data) {
|
|
143
|
+
try {
|
|
144
|
+
var bytes = null;
|
|
145
|
+
if (data instanceof ArrayBuffer) bytes = new Uint8Array(data);
|
|
146
|
+
else if (data && data.buffer) bytes = new Uint8Array(data.buffer, data.byteOffset || 0, data.byteLength);
|
|
147
|
+
if (!bytes) return null;
|
|
148
|
+
var head = [];
|
|
149
|
+
for (var i = 0; i < Math.min(32, bytes.length); i += 1) head.push(bytes[i].toString(16).padStart(2, '0'));
|
|
150
|
+
return head.join('');
|
|
151
|
+
} catch (e) { return null; }
|
|
152
|
+
}
|
|
153
|
+
var Tap = function (url, protocols) {
|
|
154
|
+
var socket = protocols === undefined ? new NativeSocket(url) : new NativeSocket(url, protocols);
|
|
155
|
+
try {
|
|
156
|
+
record({ kind: 'page-open', url: String(url), at: Date.now() });
|
|
157
|
+
socket.addEventListener('message', function (event) {
|
|
158
|
+
record({ kind: 'page-in', size: sizeOf(event.data), head: headOf(event.data), at: Date.now() });
|
|
159
|
+
});
|
|
160
|
+
var send = socket.send.bind(socket);
|
|
161
|
+
socket.send = function (data) {
|
|
162
|
+
record({ kind: 'page-out', size: sizeOf(data), head: headOf(data), at: Date.now() });
|
|
163
|
+
return send(data);
|
|
164
|
+
};
|
|
165
|
+
} catch (e) {}
|
|
166
|
+
return socket;
|
|
167
|
+
};
|
|
168
|
+
Tap.prototype = NativeSocket.prototype;
|
|
169
|
+
Tap.CONNECTING = 0; Tap.OPEN = 1; Tap.CLOSING = 2; Tap.CLOSED = 3;
|
|
170
|
+
Tap.__vcpTapped = true;
|
|
171
|
+
window.WebSocket = Tap;
|
|
172
|
+
})();
|
|
173
|
+
if (typeof NativeWorker !== 'function') return;
|
|
174
|
+
var TAP = ${JSON.stringify(WORKER_TAP)};
|
|
175
|
+
var QUEUE = ${JSON.stringify(WORKER_QUEUE_SHIM)};
|
|
176
|
+
var stats = { wrapped: 0, passthrough: 0 };
|
|
177
|
+
var urls = [];
|
|
178
|
+
|
|
179
|
+
function shimUrl(url, options) {
|
|
180
|
+
var absolute = new URL(String(url), location.href).href;
|
|
181
|
+
var isModule = !!(options && options.type === 'module');
|
|
182
|
+
var code = isModule
|
|
183
|
+
? 'import(' + JSON.stringify(absolute) + ').catch(function (e) { try { console.error("[vcp] import failed", e); } catch (_) {} });\\n' + QUEUE + '\\n' + TAP
|
|
184
|
+
: 'try { importScripts(' + JSON.stringify(absolute) + '); } catch (e) {}\\n' + TAP;
|
|
185
|
+
return URL.createObjectURL(new Blob([code], { type: 'text/javascript' }));
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// Rewriting a worker runs it from a blob: URL, which changes its base URL:
|
|
189
|
+
// self.location, import.meta.url and relative fetch() calls all move. That is
|
|
190
|
+
// enough to break a streaming worker, and the SPICE protocol socket lives on
|
|
191
|
+
// the page anyway, so wrapping is off unless a script is named explicitly.
|
|
192
|
+
var WORKER_ALLOW = [];
|
|
193
|
+
|
|
194
|
+
function workerAllowed(url) {
|
|
195
|
+
try {
|
|
196
|
+
var name = String(url).split('?')[0].split('/').pop();
|
|
197
|
+
return WORKER_ALLOW.indexOf(name) >= 0 || WORKER_ALLOW.indexOf(String(url)) >= 0;
|
|
198
|
+
} catch (error) { return false; }
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
window.Worker = class VcpWorker extends NativeWorker {
|
|
202
|
+
constructor(url, options) {
|
|
203
|
+
var target = url;
|
|
204
|
+
if (workerAllowed(url)) {
|
|
205
|
+
try {
|
|
206
|
+
target = shimUrl(url, options);
|
|
207
|
+
stats.wrapped += 1;
|
|
208
|
+
if (urls.length < 10) urls.push(String(url));
|
|
209
|
+
} catch (error) {
|
|
210
|
+
stats.passthrough += 1;
|
|
211
|
+
target = url;
|
|
212
|
+
}
|
|
213
|
+
} else {
|
|
214
|
+
stats.passthrough += 1;
|
|
215
|
+
}
|
|
216
|
+
super(target, options);
|
|
217
|
+
}
|
|
218
|
+
};
|
|
219
|
+
|
|
220
|
+
function readFrames(limit) {
|
|
221
|
+
return new Promise(function (resolve) {
|
|
222
|
+
var fail = function (error) { resolve({ frames: [], error: String(error && error.message || error) }); };
|
|
223
|
+
var request;
|
|
224
|
+
try { request = indexedDB.open('vcp-tap', 1); } catch (error) { fail(error); return; }
|
|
225
|
+
request.onupgradeneeded = function () {
|
|
226
|
+
if (!request.result.objectStoreNames.contains('frames')) request.result.createObjectStore('frames', { autoIncrement: true });
|
|
227
|
+
};
|
|
228
|
+
request.onerror = function () { fail(request.error); };
|
|
229
|
+
request.onsuccess = function () {
|
|
230
|
+
try {
|
|
231
|
+
var store = request.result.transaction('frames', 'readonly').objectStore('frames');
|
|
232
|
+
var get = store.getAll();
|
|
233
|
+
get.onsuccess = function () { resolve({ frames: (get.result || []).slice(-(limit || 40)), error: null }); };
|
|
234
|
+
get.onerror = function () { fail(get.error); };
|
|
235
|
+
} catch (error) { fail(error); }
|
|
236
|
+
};
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// --- Clipboard over the SPICE agent channel ---------------------------
|
|
241
|
+
// The client ships no clipboard support at all (enums only), so the frames
|
|
242
|
+
// are built here. send_agent_message already wraps and chunks them into
|
|
243
|
+
// SPICE_MSGC_MAIN_AGENT_DATA (type 107) on the main channel.
|
|
244
|
+
var AGENT = { CLIPBOARD: 4, CAPS: 6, GRAB: 7, REQUEST: 8, RELEASE: 9 };
|
|
245
|
+
var MIME_UTF8_TEXT = 1;
|
|
246
|
+
var clipboardEvents = [];
|
|
247
|
+
var pendingText = null;
|
|
248
|
+
|
|
249
|
+
function bodyOf(size, write) {
|
|
250
|
+
return { buffer_size: function () { return size; }, to_buffer: write };
|
|
251
|
+
}
|
|
252
|
+
function u32Body(values) {
|
|
253
|
+
return bodyOf(4 * values.length, function (buffer, at) {
|
|
254
|
+
var view = new DataView(buffer);
|
|
255
|
+
for (var i = 0; i < values.length; i += 1) view.setUint32(at + i * 4, values[i], true);
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
function clipboardDataBody(mime, bytes) {
|
|
259
|
+
return bodyOf(4 + bytes.length, function (buffer, at) {
|
|
260
|
+
var view = new DataView(buffer);
|
|
261
|
+
view.setUint32(at, mime, true);
|
|
262
|
+
var out = new Uint8Array(buffer, at + 4);
|
|
263
|
+
out.set(bytes);
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
function agentClient() {
|
|
267
|
+
var client = window.spice_connection;
|
|
268
|
+
if (!client || typeof client.send_agent_message !== 'function') throw new Error('spice client not ready');
|
|
269
|
+
return client;
|
|
270
|
+
}
|
|
271
|
+
function announceClipboardCaps() {
|
|
272
|
+
// bit 3 = CLIPBOARD, bit 5 = CLIPBOARD_BY_DEMAND, bit 6 = SELECTION, bit 10 = MAX_CLIPBOARD
|
|
273
|
+
var caps = (1 << 3) | (1 << 5) | (1 << 6) | (1 << 10);
|
|
274
|
+
agentClient().send_agent_message(AGENT.CAPS, u32Body([0, caps]));
|
|
275
|
+
}
|
|
276
|
+
function answerClipboardRequest(mime) {
|
|
277
|
+
if (!pendingText) return false;
|
|
278
|
+
agentClient().send_agent_message(AGENT.CLIPBOARD, clipboardDataBody(mime || MIME_UTF8_TEXT, new TextEncoder().encode(pendingText)));
|
|
279
|
+
clipboardEvents.push({ kind: 'served', at: Date.now(), bytes: pendingText.length });
|
|
280
|
+
return true;
|
|
281
|
+
}
|
|
282
|
+
// Wire layout observed on this client: [0x0a][channel][size u32]…[type u16 @12].
|
|
283
|
+
// The agent payload offset is not documented for this fork, so inbound frames
|
|
284
|
+
// are both scanned at the plausible offsets and kept verbatim for calibration.
|
|
285
|
+
var inboundAgentFrames = [];
|
|
286
|
+
function recordInbound(bytes) {
|
|
287
|
+
if (inboundAgentFrames.length >= 20) inboundAgentFrames.shift();
|
|
288
|
+
inboundAgentFrames.push({
|
|
289
|
+
at: Date.now(),
|
|
290
|
+
len: bytes.length,
|
|
291
|
+
hex: Array.prototype.map.call(bytes.slice(0, 56), function (x) { return x.toString(16).padStart(2, '0'); }).join(''),
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
function installAgentListener() {
|
|
295
|
+
var client = window.spice_connection;
|
|
296
|
+
var socket = client && client.ws;
|
|
297
|
+
if (!socket || socket.__vcpAgentTap) return false;
|
|
298
|
+
socket.__vcpAgentTap = true;
|
|
299
|
+
socket.addEventListener('message', function (event) {
|
|
300
|
+
try {
|
|
301
|
+
var bytes = new Uint8Array(event.data);
|
|
302
|
+
if (bytes[0] !== 0x0a || bytes[1] !== 1) return;
|
|
303
|
+
var type = bytes[12] | (bytes[13] << 8);
|
|
304
|
+
if (type !== 107) return;
|
|
305
|
+
recordInbound(bytes);
|
|
306
|
+
var view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
307
|
+
var found = null;
|
|
308
|
+
for (var offset = 14; offset <= 26; offset += 4) {
|
|
309
|
+
var agentType = view.getUint32(offset + 4, true);
|
|
310
|
+
if (agentType === AGENT.REQUEST || agentType === AGENT.RELEASE) { found = { agentType: agentType, at: offset }; break; }
|
|
311
|
+
}
|
|
312
|
+
if (!found) return;
|
|
313
|
+
if (found.agentType === AGENT.RELEASE) {
|
|
314
|
+
clipboardEvents.push({ kind: 'release', at: Date.now() });
|
|
315
|
+
return;
|
|
316
|
+
}
|
|
317
|
+
var mime = view.getUint32(found.at + 16, true);
|
|
318
|
+
clipboardEvents.push({ kind: 'request', at: Date.now(), mime: mime });
|
|
319
|
+
answerClipboardRequest(mime === 0 ? MIME_UTF8_TEXT : mime);
|
|
320
|
+
} catch (error) {}
|
|
321
|
+
});
|
|
322
|
+
return true;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
window.__vcpPreload = {
|
|
326
|
+
version: '0.6.0',
|
|
327
|
+
stats: function () { return { wrapped: stats.wrapped, passthrough: stats.passthrough, urls: urls.slice() }; },
|
|
328
|
+
readFrames: readFrames,
|
|
329
|
+
clipboard: {
|
|
330
|
+
// Stage text and grab clipboard ownership with the normal handshake.
|
|
331
|
+
push: function (text) {
|
|
332
|
+
pendingText = String(text);
|
|
333
|
+
announceClipboardCaps();
|
|
334
|
+
agentClient().send_agent_message(AGENT.GRAB, u32Body([1, MIME_UTF8_TEXT]));
|
|
335
|
+
installAgentListener();
|
|
336
|
+
clipboardEvents.push({ kind: 'grab', at: Date.now(), chars: pendingText.length });
|
|
337
|
+
return { staged: true, chars: pendingText.length };
|
|
338
|
+
},
|
|
339
|
+
// Push data without waiting for a request. Some guest agents accept it,
|
|
340
|
+
// and it is also the cheapest way to prove the data path end to end.
|
|
341
|
+
pushUnsolicited: function (text) {
|
|
342
|
+
pendingText = String(text);
|
|
343
|
+
installAgentListener();
|
|
344
|
+
agentClient().send_agent_message(
|
|
345
|
+
AGENT.CLIPBOARD,
|
|
346
|
+
clipboardDataBody(MIME_UTF8_TEXT, new TextEncoder().encode(pendingText)),
|
|
347
|
+
);
|
|
348
|
+
clipboardEvents.push({ kind: 'unsolicited', at: Date.now(), chars: pendingText.length });
|
|
349
|
+
return { sent: true, chars: pendingText.length };
|
|
350
|
+
},
|
|
351
|
+
// Runs every strategy in order and reports what the guest actually did.
|
|
352
|
+
// One call answers: did the guest ask for data, and what did it send back.
|
|
353
|
+
probe: async function (text) {
|
|
354
|
+
pendingText = String(text || 'vcp-clipboard-probe');
|
|
355
|
+
clipboardEvents.length = 0;
|
|
356
|
+
inboundAgentFrames.length = 0;
|
|
357
|
+
installAgentListener();
|
|
358
|
+
var wait = function (ms) { return new Promise(function (resolve) { setTimeout(resolve, ms); }); };
|
|
359
|
+
var steps = [];
|
|
360
|
+
var client = agentClient();
|
|
361
|
+
|
|
362
|
+
// 1) ask the guest for its own capabilities
|
|
363
|
+
client.send_agent_message(AGENT.CAPS, u32Body([1, 0]));
|
|
364
|
+
await wait(500);
|
|
365
|
+
steps.push({ step: 'caps-request', inbound: inboundAgentFrames.length });
|
|
366
|
+
|
|
367
|
+
// 2) announce our clipboard caps, then grab
|
|
368
|
+
announceClipboardCaps();
|
|
369
|
+
client.send_agent_message(AGENT.GRAB, u32Body([1, MIME_UTF8_TEXT]));
|
|
370
|
+
await wait(1200);
|
|
371
|
+
steps.push({
|
|
372
|
+
step: 'grab',
|
|
373
|
+
requests: clipboardEvents.filter(function (e) { return e.kind === 'request'; }).length,
|
|
374
|
+
inbound: inboundAgentFrames.length,
|
|
375
|
+
});
|
|
376
|
+
|
|
377
|
+
// 3) grab again in case the first one raced the caps announcement
|
|
378
|
+
client.send_agent_message(AGENT.GRAB, u32Body([1, MIME_UTF8_TEXT]));
|
|
379
|
+
await wait(800);
|
|
380
|
+
steps.push({
|
|
381
|
+
step: 'grab-retry',
|
|
382
|
+
requests: clipboardEvents.filter(function (e) { return e.kind === 'request'; }).length,
|
|
383
|
+
});
|
|
384
|
+
|
|
385
|
+
// 4) last resort: push the bytes without being asked
|
|
386
|
+
client.send_agent_message(AGENT.CLIPBOARD, clipboardDataBody(MIME_UTF8_TEXT, new TextEncoder().encode(pendingText)));
|
|
387
|
+
await wait(600);
|
|
388
|
+
steps.push({ step: 'unsolicited', served: clipboardEvents.filter(function (e) { return e.kind === 'served'; }).length });
|
|
389
|
+
|
|
390
|
+
return {
|
|
391
|
+
chars: pendingText.length,
|
|
392
|
+
steps: steps,
|
|
393
|
+
events: clipboardEvents.slice(),
|
|
394
|
+
inboundAgentFrames: inboundAgentFrames.slice(),
|
|
395
|
+
verdict: clipboardEvents.some(function (e) { return e.kind === 'request'; })
|
|
396
|
+
? 'guest-requested-data'
|
|
397
|
+
: (inboundAgentFrames.length ? 'guest-spoke-but-not-clipboard' : 'guest-silent'),
|
|
398
|
+
};
|
|
399
|
+
},
|
|
400
|
+
events: function () { return clipboardEvents.slice(-20); },
|
|
401
|
+
inbound: function () { return inboundAgentFrames.slice(); },
|
|
402
|
+
},
|
|
403
|
+
clearFrames: function () {
|
|
404
|
+
return new Promise(function (resolve) {
|
|
405
|
+
var request = indexedDB.open('vcp-tap', 1);
|
|
406
|
+
request.onsuccess = function () {
|
|
407
|
+
try { request.result.transaction('frames', 'readwrite').objectStore('frames').clear(); } catch (e) {}
|
|
408
|
+
resolve(true);
|
|
409
|
+
};
|
|
410
|
+
request.onerror = function () { resolve(false); };
|
|
411
|
+
});
|
|
412
|
+
},
|
|
413
|
+
};
|
|
414
|
+
})();
|
|
415
|
+
`;
|
|
416
|
+
/** The preload body registered on the browser context. */
|
|
417
|
+
export const VCP_PRELOAD = PAGE_SIDE;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/** Shared caret-ignore limits and the pixel half of a region fingerprint. */
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { pngPixelFingerprint, PngFingerprintError } from "./png-fingerprint.js";
|
|
4
|
+
export const MAX_BROWSER_IGNORE_RECTS = 2;
|
|
5
|
+
export const MAX_BROWSER_IGNORE_WIDTH = 16;
|
|
6
|
+
export const MAX_BROWSER_IGNORE_HEIGHT = 64;
|
|
7
|
+
export class RegionFingerprintError extends Error {
|
|
8
|
+
code;
|
|
9
|
+
constructor(code, message) {
|
|
10
|
+
super(message);
|
|
11
|
+
this.code = code;
|
|
12
|
+
this.name = "RegionFingerprintError";
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
export function checkedIgnoreRects(ignore, region) {
|
|
16
|
+
const rects = ignore.map((rect) => ({ x: rect.x, y: rect.y, width: rect.width, height: rect.height }));
|
|
17
|
+
const valid = rects.length <= MAX_BROWSER_IGNORE_RECTS && rects.every((rect) => [rect.x, rect.y, rect.width, rect.height].every(Number.isSafeInteger) && rect.x >= 0 && rect.y >= 0 && rect.width >= 1 && rect.height >= 1
|
|
18
|
+
&& rect.width <= MAX_BROWSER_IGNORE_WIDTH && rect.height <= MAX_BROWSER_IGNORE_HEIGHT && rect.x + rect.width <= region.width && rect.y + rect.height <= region.height)
|
|
19
|
+
&& rects.reduce((area, rect) => area + rect.width * rect.height, 0) * 4 <= region.width * region.height;
|
|
20
|
+
if (!valid) {
|
|
21
|
+
throw new RegionFingerprintError("INVALID_IGNORE", `expected up to ${MAX_BROWSER_IGNORE_RECTS} caret-sized rectangles (≤${MAX_BROWSER_IGNORE_WIDTH}×${MAX_BROWSER_IGNORE_HEIGHT}) relative to the region, covering at most a quarter of it`);
|
|
22
|
+
}
|
|
23
|
+
return rects;
|
|
24
|
+
}
|
|
25
|
+
/** Pixel digest only. Viewport HMAC scope stays with the screenshot that owns the document. */
|
|
26
|
+
export function fingerprintRegionPng(png, ignore, region) {
|
|
27
|
+
try {
|
|
28
|
+
return ignore.length > 0 ? pngPixelFingerprint(png, ignore, region) : createHash("sha256").update(png).digest("hex");
|
|
29
|
+
}
|
|
30
|
+
catch (error) {
|
|
31
|
+
if (error instanceof PngFingerprintError || error instanceof RegionFingerprintError) {
|
|
32
|
+
throw new RegionFingerprintError("IGNORE_UNSUPPORTED", `cannot apply ignore rectangles; capture without ignore (${error.message})`);
|
|
33
|
+
}
|
|
34
|
+
throw error;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/** Runs an async function body in the Console process. The operation lock is held by the caller. */
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { createBrowserLa } from "./browser-la.js";
|
|
4
|
+
export const BROWSER_RUN_CODE_MAX = 200_000;
|
|
5
|
+
export const BROWSER_RUN_TIMEOUT_DEFAULT_MS = 60_000;
|
|
6
|
+
export const BROWSER_RUN_TIMEOUT_MAX_MS = 600_000;
|
|
7
|
+
const LOG_LIMIT = 500;
|
|
8
|
+
const LOG_CHARS = 2_000;
|
|
9
|
+
export function createRunLog() {
|
|
10
|
+
const entries = [];
|
|
11
|
+
return { entries, log(message) {
|
|
12
|
+
if (entries.length >= LOG_LIMIT)
|
|
13
|
+
return;
|
|
14
|
+
const text = typeof message === "string" ? message : JSON.stringify(message);
|
|
15
|
+
entries.push((text ?? String(message)).slice(0, LOG_CHARS));
|
|
16
|
+
} };
|
|
17
|
+
}
|
|
18
|
+
export function clipRunText(value) {
|
|
19
|
+
return (value instanceof Error ? value.message : String(value)).slice(0, 4000);
|
|
20
|
+
}
|
|
21
|
+
export function clipRunStack(value) {
|
|
22
|
+
const stack = value instanceof Error ? value.stack : undefined;
|
|
23
|
+
return stack ? stack.slice(0, 4000) : undefined;
|
|
24
|
+
}
|
|
25
|
+
/** `result` may time out while `settled` waits for the function body to finish. */
|
|
26
|
+
export function invokeBrowserCode(code, ctx, userSignal) {
|
|
27
|
+
let compiled;
|
|
28
|
+
try {
|
|
29
|
+
const AsyncFunction = Object.getPrototypeOf(async function () { }).constructor;
|
|
30
|
+
compiled = new AsyncFunction("ctx", code);
|
|
31
|
+
}
|
|
32
|
+
catch (error) {
|
|
33
|
+
return {
|
|
34
|
+
result: Promise.resolve({ ok: false, code: "RUN_ERROR", error: clipRunText(error), stack: clipRunStack(error), logs: [], artifacts: [] }),
|
|
35
|
+
settled: Promise.resolve(),
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
let settle;
|
|
39
|
+
const settled = new Promise((resolve) => { settle = resolve; });
|
|
40
|
+
const work = Promise.resolve(compiled(ctx)).finally(() => settle());
|
|
41
|
+
const result = new Promise((resolve) => {
|
|
42
|
+
let done = false;
|
|
43
|
+
const finish = (outcome) => {
|
|
44
|
+
if (done)
|
|
45
|
+
return;
|
|
46
|
+
done = true;
|
|
47
|
+
resolve(outcome);
|
|
48
|
+
};
|
|
49
|
+
const abort = () => {
|
|
50
|
+
const code = userSignal.aborted ? "RUN_CANCELLED" : "RUN_TIMEOUT";
|
|
51
|
+
finish({ ok: false, code, error: code === "RUN_CANCELLED" ? "run cancelled" : "run timed out", logs: [], artifacts: [], unknownEffects: true });
|
|
52
|
+
};
|
|
53
|
+
if (ctx.signal.aborted) {
|
|
54
|
+
abort();
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
ctx.signal.addEventListener("abort", abort, { once: true });
|
|
58
|
+
work.then((value) => finish({ ok: true, value }), (error) => {
|
|
59
|
+
const code = error instanceof Error && "code" in error ? String(error.code) : "RUN_ERROR";
|
|
60
|
+
if (ctx.signal.aborted || code === "RUN_TIMEOUT" || code === "RUN_CANCELLED") {
|
|
61
|
+
const settledCode = userSignal.aborted ? "RUN_CANCELLED" : "RUN_TIMEOUT";
|
|
62
|
+
finish({ ok: false, code: settledCode, error: settledCode === "RUN_CANCELLED" ? "run cancelled" : "run timed out", logs: [], artifacts: [], unknownEffects: true });
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
finish({ ok: false, code: "RUN_ERROR", error: clipRunText(error), stack: clipRunStack(error), logs: [], artifacts: [] });
|
|
66
|
+
});
|
|
67
|
+
});
|
|
68
|
+
return { result, settled };
|
|
69
|
+
}
|
|
70
|
+
export function materializeRunValue(value, write, images) {
|
|
71
|
+
if (Buffer.isBuffer(value)) {
|
|
72
|
+
const path = write(`run-${Date.now()}-${randomUUID().slice(0, 8)}.bin`, value);
|
|
73
|
+
return { path, bytes: value.length };
|
|
74
|
+
}
|
|
75
|
+
if (Array.isArray(value))
|
|
76
|
+
return value.map((item) => materializeRunValue(item, write, images));
|
|
77
|
+
if (!value || typeof value !== "object")
|
|
78
|
+
return value;
|
|
79
|
+
const record = value;
|
|
80
|
+
if (Buffer.isBuffer(record.png) && typeof record.fingerprint === "string") {
|
|
81
|
+
const path = write(`run-${Date.now()}-${randomUUID().slice(0, 8)}.png`, record.png);
|
|
82
|
+
images.push({ path, data: record.png.toString("base64") });
|
|
83
|
+
const copy = { ...record, png: path };
|
|
84
|
+
for (const [key, item] of Object.entries(copy)) {
|
|
85
|
+
if (key !== "png")
|
|
86
|
+
copy[key] = materializeRunValue(item, write, images);
|
|
87
|
+
}
|
|
88
|
+
return copy;
|
|
89
|
+
}
|
|
90
|
+
const copy = {};
|
|
91
|
+
for (const [key, item] of Object.entries(record))
|
|
92
|
+
copy[key] = materializeRunValue(item, write, images);
|
|
93
|
+
return copy;
|
|
94
|
+
}
|
|
95
|
+
export function bindRunLa(page, signal, log, send) {
|
|
96
|
+
return createBrowserLa({ page, signal, log, send });
|
|
97
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/** Small text envelope survives live SSE and restored tool-result previews. */
|
|
2
2
|
const SCREENSHOT_METADATA_BUDGET = 2500;
|
|
3
|
-
const ESSENTIAL_KEYS = ["tabId", "snapshotId", "screenshotUrl", "screenshotPath", "screenshotError", "imageWarning", "targets"];
|
|
3
|
+
const ESSENTIAL_KEYS = ["tabId", "snapshotId", "screenshotUrl", "screenshotPath", "screenshotError", "imageWarning", "targets", "region", "ignore", "regionStatus", "fingerprint"];
|
|
4
4
|
const OPTIONAL_KEYS = ["title", "url"];
|
|
5
5
|
const OPTIONAL_KEY_SET = new Set(OPTIONAL_KEYS);
|
|
6
6
|
/** Control characters balloon the serialized JSON and can break history restore. */
|
|
@@ -21,7 +21,7 @@ export function screenshotMetadata(result) {
|
|
|
21
21
|
delete output[key];
|
|
22
22
|
if (JSON.stringify(output).length > SCREENSHOT_METADATA_BUDGET) {
|
|
23
23
|
for (const key of ESSENTIAL_KEYS)
|
|
24
|
-
if (typeof output[key] === "string")
|
|
24
|
+
if (key !== "fingerprint" && typeof output[key] === "string")
|
|
25
25
|
output[key] = output[key].slice(0, 120);
|
|
26
26
|
}
|
|
27
27
|
return output;
|
|
@@ -9,11 +9,25 @@ import { Check } from "typebox/value";
|
|
|
9
9
|
import { BROWSER_BATCH_SCHEMA, preflightBrowserBatch, runBrowserBatch } from "./browser-batch.js";
|
|
10
10
|
const NAME = /^[a-z0-9][a-z0-9-]{0,62}$/;
|
|
11
11
|
const SECRET = /password|secret|token|cookie|authorization|credential|api[-_]?key/i;
|
|
12
|
-
|
|
12
|
+
const SEMANTIC_SCRIPT_SCHEMA = Type.Object({
|
|
13
13
|
...Type.Pick(BROWSER_BATCH_SCHEMA, ["schemaVersion", "steps"]).properties,
|
|
14
14
|
name: Type.String({ pattern: "^[a-z0-9][a-z0-9-]{0,62}$" }),
|
|
15
15
|
description: Type.Optional(Type.String({ maxLength: 500 })),
|
|
16
16
|
}, { additionalProperties: false });
|
|
17
|
+
const CODE_SCRIPT_SCHEMA = Type.Object({
|
|
18
|
+
kind: Type.Literal("code"),
|
|
19
|
+
name: Type.String({ pattern: "^[a-z0-9][a-z0-9-]{0,62}$" }),
|
|
20
|
+
description: Type.Optional(Type.String({ maxLength: 500 })),
|
|
21
|
+
code: Type.String({ minLength: 1, maxLength: 200_000 }),
|
|
22
|
+
params: Type.Optional(Type.Object({
|
|
23
|
+
type: Type.Optional(Type.Literal("object")),
|
|
24
|
+
properties: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
|
|
25
|
+
required: Type.Optional(Type.Array(Type.String())),
|
|
26
|
+
additionalProperties: Type.Optional(Type.Boolean()),
|
|
27
|
+
description: Type.Optional(Type.String()),
|
|
28
|
+
}, { additionalProperties: false })),
|
|
29
|
+
}, { additionalProperties: false });
|
|
30
|
+
export const BROWSER_SCRIPT_SCHEMA = Type.Union([SEMANTIC_SCRIPT_SCHEMA, CODE_SCRIPT_SCHEMA]);
|
|
17
31
|
export class BrowserScriptError extends Error {
|
|
18
32
|
code;
|
|
19
33
|
constructor(code, message) {
|
|
@@ -95,15 +109,39 @@ export class BrowserScriptStore {
|
|
|
95
109
|
if (!status)
|
|
96
110
|
await mkdir(parent, { recursive: true });
|
|
97
111
|
}
|
|
98
|
-
async run(name, automation, signal) {
|
|
112
|
+
async run(name, automation, signal, args, timeoutMs = 60_000) {
|
|
99
113
|
const script = validateScript(await this.read(name));
|
|
100
|
-
|
|
114
|
+
if ("kind" in script && script.kind === "code") {
|
|
115
|
+
for (const key of script.params?.required ?? []) {
|
|
116
|
+
if (!args || !Object.prototype.hasOwnProperty.call(args, key))
|
|
117
|
+
throw new BrowserScriptError("INVALID_SCRIPT_ARGS", `missing required arg ${key}`);
|
|
118
|
+
}
|
|
119
|
+
if (!automation.runCode)
|
|
120
|
+
throw new BrowserScriptError("INVALID_SCRIPT", "code scripts require the browser run executor");
|
|
121
|
+
return automation.runCode({ code: script.code, args: args ?? {}, timeoutMs }, signal);
|
|
122
|
+
}
|
|
123
|
+
const semantic = script;
|
|
124
|
+
return runBrowserBatch(automation, { schemaVersion: 1, steps: semantic.steps }, signal);
|
|
101
125
|
}
|
|
102
126
|
}
|
|
103
127
|
export function validateScript(value) {
|
|
104
128
|
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
105
129
|
throw new BrowserScriptError("INVALID_SCRIPT", "script must be an object");
|
|
106
130
|
const script = value;
|
|
131
|
+
if (script.kind === "code")
|
|
132
|
+
return validateCodeScript(script);
|
|
133
|
+
return validateSemanticScript(script);
|
|
134
|
+
}
|
|
135
|
+
function validateCodeScript(script) {
|
|
136
|
+
if (typeof script.name !== "string" || !NAME.test(script.name))
|
|
137
|
+
throw new BrowserScriptError("INVALID_SCRIPT_NAME", "script name must be a lowercase slug");
|
|
138
|
+
if (SECRET.test(JSON.stringify(script)))
|
|
139
|
+
throw new BrowserScriptError("SCRIPT_SECRET", "scripts cannot contain credential-like fields or values");
|
|
140
|
+
if (!Check(CODE_SCRIPT_SCHEMA, script))
|
|
141
|
+
throw new BrowserScriptError("INVALID_SCRIPT", "script must match its strict typed schema");
|
|
142
|
+
return script;
|
|
143
|
+
}
|
|
144
|
+
function validateSemanticScript(script) {
|
|
107
145
|
if (script.schemaVersion !== 1)
|
|
108
146
|
throw new BrowserScriptError("INVALID_SCRIPT", "unsupported script schema");
|
|
109
147
|
if (typeof script.name !== "string" || !NAME.test(script.name))
|
|
@@ -121,7 +159,7 @@ export function validateScript(value) {
|
|
|
121
159
|
throw new BrowserScriptError("SCRIPT_NOT_REUSABLE", "scripts must rediscover elements and cannot execute JavaScript");
|
|
122
160
|
}
|
|
123
161
|
}
|
|
124
|
-
if (!Check(
|
|
162
|
+
if (!Check(SEMANTIC_SCRIPT_SCHEMA, script))
|
|
125
163
|
throw new BrowserScriptError("INVALID_SCRIPT", "script must match its strict typed schema");
|
|
126
164
|
try {
|
|
127
165
|
preflightBrowserBatch({ schemaVersion: 1, steps: script.steps });
|
|
@@ -79,5 +79,9 @@ function summaryFor(toolName, value) {
|
|
|
79
79
|
return typeof value.matchCount === "number" ? `${value.matchCount} matches` : undefined;
|
|
80
80
|
if (toolName === "browser_tabs")
|
|
81
81
|
return clip(value.action);
|
|
82
|
+
if (toolName === "browser_cdp")
|
|
83
|
+
return typeof value.method === "string" ? value.method : "events";
|
|
84
|
+
if (toolName === "browser_run")
|
|
85
|
+
return value.ok === false && typeof value.code === "string" ? value.code : "run";
|
|
82
86
|
return clip(page?.title ?? page?.url);
|
|
83
87
|
}
|