@sparkelf/dsh-dataops-managed 0.4.0 → 0.4.1

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.
Files changed (35) hide show
  1. package/lib/client.js +294 -213
  2. package/lib/client.js.map +1 -1
  3. package/lib/index.js +331 -106
  4. package/lib/types/client/BrowserVersionPrompt.d.ts +26 -0
  5. package/lib/types/client/locales.d.ts +4 -0
  6. package/lib/types/collect-api.d.ts +10 -19
  7. package/lib/types/tool-scope.d.ts +16 -1
  8. package/package.json +4 -2
  9. package/skills/browser/SKILL.md +33 -44
  10. package/skills/{browser/references/bridge.md → browser-bridge-companion/SKILL.md} +6 -1
  11. package/skills/{browser/references/headless.md → browser-headless/SKILL.md} +6 -1
  12. package/skills/dataops-collect/SKILL.md +96 -57
  13. package/skills/dataops-governance/SKILL.md +41 -0
  14. package/skills/dataops-governance/i18n/zh.json +10 -0
  15. package/skills/dataops-governance/references/01-file-import.md +201 -0
  16. package/skills/dataops-governance/references/02-api-import.md +11 -0
  17. package/skills/dataops-governance/references/03-metadata-write.md +32 -0
  18. package/skills/dataops-governance/references/04-metadata-read.md +132 -0
  19. package/skills/dataops-metadata-optimizer/SKILL.md +53 -0
  20. package/skills/dataops-metadata-optimizer/i18n/zh.json +10 -0
  21. package/skills/dataops-metadata-optimizer/references/01-inventory.md +23 -0
  22. package/skills/dataops-metadata-optimizer/references/02-pattern-catalog.md +16 -0
  23. package/skills/dataops-metadata-optimizer/references/03-proposal-and-preview.md +34 -0
  24. package/skills/dataops-metadata-optimizer/references/04-apply-and-measure.md +27 -0
  25. package/skills/dataops-synonym-governance/SKILL.md +38 -0
  26. package/skills/dataops-synonym-governance/references/synonym_governance.md +56 -0
  27. package/skills/browser/references/chrome-install.md +0 -309
  28. package/skills/browser/references/chrome-install.openai.yaml +0 -4
  29. package/skills/browser/references/scripts/check_browser_bridge_status.js +0 -33
  30. package/skills/browser/references/scripts/cleanup_isolated_chrome.ps1 +0 -10
  31. package/skills/browser/references/scripts/start_isolated_chrome.ps1 +0 -25
  32. package/skills/browser/references/scripts/start_test_browser_bridge.cjs +0 -245
  33. package/skills/dataops-collect/references/append.md +0 -137
  34. package/skills/dataops-collect/references/execution.md +0 -133
  35. package/skills/dataops-collect/references/plan-schema.md +0 -142
@@ -1,309 +0,0 @@
1
- > **已废弃(2026-11):** 本参考描述的是旧 Chrome 扩展安装流程。现在请优先使用 [bridge.md](bridge.md) 的离线 Companion + Playwright MCP。保留本文仅用于排查旧环境。
2
-
3
- # Browser Bridge Chrome Install
4
-
5
- ## Overview
6
-
7
- Prepare a local browser for DataOps `browser` tool verification on Windows.
8
-
9
- This skill covers the stable operator workflow for automated test-browser startup, unpacked extension refresh, backend bridge verification, and the fallback manual Google Chrome flow.
10
-
11
- ## Preconditions
12
-
13
- - Work from the `dataops` repo on the same Windows machine that runs Chrome/Chromium.
14
- - The snippets read the admin password from `DATAOPS_ADMIN_PASSWORD`; never paste a real credential into this file, a script, or a log.
15
- - `references/scripts/start_test_browser_bridge.cjs` also needs `DATAOPS_PROJECTS_ROOT` pointing at the directory that contains the `dataops` checkout, and `DATAOPS_BROWSER_BRIDGE_PASSWORD` for the login.
16
- - Reuse the current DataOps backend/frontend when available; do not restart them unless the user asks.
17
- - Treat browser-side install as local-machine state. It is acceptable to open browser UI, but do not mutate unrelated browser profiles.
18
- - Prefer an isolated Playwright Chromium profile for automated testing. Only use the user's Google Chrome profile when they explicitly ask to.
19
-
20
- ## Stable Workflow
21
-
22
- ### 1. Confirm backend truth first
23
-
24
- Run these checks before touching the browser:
25
-
26
- ```powershell
27
- Get-NetTCPConnection -State Listen -LocalPort 3000,3101 -ErrorAction SilentlyContinue |
28
- Select-Object LocalPort,OwningProcess,State
29
- ```
30
-
31
- ```powershell
32
- @'
33
- process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
34
- (async() => {
35
- const loginResponse = await fetch('https://127.0.0.1:3101/api/auth/login', {
36
- method: 'POST',
37
- headers: { 'content-type': 'application/json' },
38
- body: JSON.stringify({ account: 'admin', password: process.env.DATAOPS_ADMIN_PASSWORD }),
39
- });
40
- const loginPayload = await loginResponse.json();
41
- const toolsResponse = await fetch('https://127.0.0.1:3101/api/ai/tools', {
42
- headers: { Authorization: `Bearer ${loginPayload.accessToken}` },
43
- });
44
- const toolsPayload = await toolsResponse.json();
45
- const browserTool = toolsPayload.tools.find((tool) => tool.name === 'browser');
46
- console.log(JSON.stringify({
47
- browserBridge: browserTool?.browserBridge ?? null,
48
- dependencyPackage: browserTool?.dependencyPackage ?? null,
49
- }, null, 2));
50
- })();
51
- '@ | node -
52
- ```
53
-
54
- Interpretation:
55
-
56
- - `dependencyPackage.available = true` means backend package generation works.
57
- - `browserBridge.connected = false` means Chrome-side install/connect work is still required.
58
- - `workspaceStatus = RUNNING` is needed later for screenshot persistence, but not for extension install.
59
-
60
- ### 2. Download and unpack the extension package
61
-
62
- Save the package and unpack it into a predictable local folder:
63
-
64
- ```powershell
65
- @'
66
- process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
67
- (async() => {
68
- const fs = require('fs');
69
- const loginResponse = await fetch('https://127.0.0.1:3101/api/auth/login', {
70
- method: 'POST',
71
- headers: { 'content-type': 'application/json' },
72
- body: JSON.stringify({ account: 'admin', password: process.env.DATAOPS_ADMIN_PASSWORD }),
73
- });
74
- const loginPayload = await loginResponse.json();
75
- const response = await fetch('https://127.0.0.1:3101/api/ai/tools/browser/dependency-package', {
76
- headers: { Authorization: `Bearer ${loginPayload.accessToken}` },
77
- });
78
- fs.writeFileSync('D:/project/projects/tmp-dataops-browser-bridge.zip', Buffer.from(await response.arrayBuffer()));
79
- })();
80
- '@ | node -
81
- ```
82
-
83
- ```powershell
84
- if (Test-Path D:\project\projects\tmp-dataops-browser-bridge) {
85
- Remove-Item -LiteralPath D:\project\projects\tmp-dataops-browser-bridge -Recurse -Force
86
- }
87
- Expand-Archive -LiteralPath D:\project\projects\tmp-dataops-browser-bridge.zip `
88
- -DestinationPath D:\project\projects\tmp-dataops-browser-bridge -Force
89
- ```
90
-
91
- The unpacked extension root is:
92
-
93
- - `D:\project\projects\tmp-dataops-browser-bridge\extension`
94
-
95
- ### 3. Preferred automated path: launch the test browser
96
-
97
- The preferred automated path is the Playwright Chromium browser that loads the latest unpacked Browser Bridge and connects it to the current backend automatically.
98
-
99
- Run from this skill's base directory (the directory containing this `references/` folder):
100
-
101
- ```powershell
102
- node .\references\scripts\start_test_browser_bridge.cjs --keep-open
103
- ```
104
-
105
- Expected success signal:
106
-
107
- - the script prints `backendBridge.connected = true`
108
- - the script prints an `extensionId`, `workerUrl`, and non-empty `sessionId`
109
- - backend `GET /api/ai/tools` shows `browser.browserBridge.connected = true`
110
-
111
- What the script does:
112
-
113
- - logs into backend with the current admin account
114
- - reads `browser.dependencyPackage.version` from backend truth
115
- - downloads and unpacks the latest Browser Bridge package when the local unpacked directory is missing or when the recorded package version no longer matches backend truth
116
- - launches a persistent Playwright Chromium profile
117
- - loads the unpacked extension with `--disable-extensions-except` and `--load-extension`
118
- - opens the DataOps frontend, injects the login token into the page, opens the extension popup, fills the DataOps URL, and lets the extension auto-poll until it resolves the same-origin signed-in session and connects
119
- - polls both popup state and backend state until the bridge is connected
120
-
121
- Use this path for automated testing and repeatable local verification.
122
-
123
- ### 4. Fallback manual path: isolated Google Chrome
124
-
125
- Use a dedicated profile and CDP port so manual Google Chrome validation does not collide with the user's normal Chrome windows:
126
-
127
- ```powershell
128
- $chrome = 'C:\Users\Administrator\AppData\Local\Google\Chrome\Bin\chrome.exe'
129
- $profile = 'D:\project\projects\tmp-chrome-browser-bridge-profile'
130
- $extension = 'D:\project\projects\tmp-dataops-browser-bridge\extension'
131
- New-Item -ItemType Directory -Force -Path $profile | Out-Null
132
- Start-Process -FilePath $chrome -ArgumentList @(
133
- "--user-data-dir=$profile",
134
- '--disable-background-networking',
135
- '--remote-debugging-port=9999',
136
- "--disable-extensions-except=$extension",
137
- "--load-extension=$extension",
138
- '--no-first-run',
139
- '--no-default-browser-check',
140
- '--ignore-certificate-errors',
141
- '--new-window',
142
- 'https://127.0.0.1:3000'
143
- )
144
- ```
145
-
146
- Confirm CDP is reachable:
147
-
148
- ```powershell
149
- curl.exe http://127.0.0.1:9999/json/version
150
- ```
151
-
152
- ### 5. Manual install and reload method
153
-
154
- Use this path only when the user explicitly wants Google Chrome itself rather than the automated test browser:
155
-
156
- 1. Open `chrome://extensions/`
157
- 2. Turn on `Developer mode`
158
- 3. Click `Load unpacked`
159
- 4. Select `D:\project\projects\tmp-dataops-browser-bridge\extension`
160
- 5. Open a logged-in DataOps tab in the same Chrome instance
161
- 6. Open the `DataOps Browser Bridge` popup
162
- 7. Enter the DataOps URL or paste a full DataOps page URL
163
- 8. Leave the popup open while it auto-polls for the same-origin signed-in session and connects; `Connect bridge` is only an immediate manual retry.
164
-
165
- For an already installed unpacked extension after code changes:
166
-
167
- 1. Keep the unpacked folder path stable
168
- 2. Open `chrome://extensions/`
169
- 3. Use the existing extension card's `Reload`
170
- 4. Reopen the popup and wait for auto-connect if backend restarted
171
-
172
- ### 6. Current automation boundary
173
-
174
- What automation can do reliably today:
175
-
176
- - confirm backend Browser Bridge truth
177
- - download and unpack the extension package
178
- - launch Playwright Chromium with the extension and connect it automatically
179
- - launch isolated Google Chrome with CDP
180
- - open `chrome://extensions/`
181
- - click `Load unpacked`
182
- - detect the native folder-picker dialog and enumerate its controls
183
-
184
- What remains unreliable and should be treated as a manual confirmation point:
185
-
186
- - consumer Google Chrome on Windows does not provide a stable script-only path for registering the unpacked extension into `chrome.management`
187
- - in project-local verification, Google Chrome logs `--disable-extensions-except is not allowed in Google Chrome, ignoring.`, so the automated path must target Playwright Chromium rather than the user's regular Google Chrome installation
188
- - the native Windows Google Chrome folder picker for unpacked extensions does not reliably accept Win32 `WM_SETTEXT`, synthetic `SendKeys`, or repeated button invoke attempts in a way that registers the unpacked extension into `chrome.management`
189
- - in the current verified environment, Google Chrome can still expose `chrome-extension://.../popup.html` targets that resolve to `chrome-error://chromewebdata/ ERR_FILE_NOT_FOUND`; do not treat those targets as proof the extension is installed
190
-
191
- Therefore the stable workflow is:
192
-
193
- - use Playwright Chromium for any automated Browser Bridge testing
194
- - reserve Google Chrome for manual operator validation only
195
- - if Google Chrome must be used, let the operator manually confirm the `extension/` directory in the folder picker and then continue with popup import/connect validation
196
-
197
- ## Verification
198
-
199
- ### Automated test-browser verification
200
-
201
- After `start_test_browser_bridge.cjs`, verify backend state directly:
202
-
203
- ```powershell
204
- cd dataops
205
- node .\references\scripts\check_browser_bridge_status.js
206
- ```
207
-
208
- Success condition:
209
-
210
- - `browserBridge.connected = true`
211
- - `activeSessionCount >= 1`
212
-
213
- ### Manual Google Chrome verification
214
-
215
- After manual confirmation, verify the extension is real rather than trusting stale popup targets:
216
-
217
- ```powershell
218
- @'
219
- const path = require('path');
220
- const { createRequire } = require('module');
221
- const frontendRequire = createRequire(path.resolve('d:/project/projects/dataops/frontend/package.json'));
222
- const { chromium } = frontendRequire('playwright');
223
- (async () => {
224
- const browser = await chromium.connectOverCDP('http://127.0.0.1:9999');
225
- const context = browser.contexts()[0];
226
- const page = await context.newPage();
227
- await page.goto('chrome://extensions/', { waitUntil: 'domcontentloaded', timeout: 60000 });
228
- const result = await page.evaluate(() => new Promise((resolve, reject) => {
229
- chrome.management.getAll((items) => {
230
- const err = chrome.runtime?.lastError?.message;
231
- if (err) return reject(new Error(err));
232
- resolve(items.map((item) => ({
233
- id: item.id,
234
- name: item.name,
235
- enabled: item.enabled,
236
- installType: item.installType,
237
- type: item.type,
238
- })));
239
- });
240
- }));
241
- console.log(JSON.stringify(result, null, 2));
242
- await browser.close();
243
- })();
244
- '@ | node -
245
- ```
246
-
247
- Success condition:
248
-
249
- - `chrome.management.getAll()` contains `DataOps Browser Bridge`
250
-
251
- Failure condition:
252
-
253
- - `getAll()` stays empty or does not include the Browser Bridge entry
254
- - any `chrome-extension://.../popup.html` target still renders `chrome-error://chromewebdata/ ERR_FILE_NOT_FOUND`
255
-
256
- ### Backend-side verification
257
-
258
- After popup auto-connect, backend must flip to connected:
259
-
260
- ```powershell
261
- @'
262
- process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
263
- (async() => {
264
- const loginResponse = await fetch('https://127.0.0.1:3101/api/auth/login', {
265
- method: 'POST',
266
- headers: { 'content-type': 'application/json' },
267
- body: JSON.stringify({ account: 'admin', password: process.env.DATAOPS_ADMIN_PASSWORD }),
268
- });
269
- const loginPayload = await loginResponse.json();
270
- const toolsResponse = await fetch('https://127.0.0.1:3101/api/ai/tools', {
271
- headers: { Authorization: `Bearer ${loginPayload.accessToken}` },
272
- });
273
- const toolsPayload = await toolsResponse.json();
274
- const browserTool = toolsPayload.tools.find((tool) => tool.name === 'browser');
275
- console.log(JSON.stringify(browserTool?.browserBridge ?? null, null, 2));
276
- })();
277
- '@ | node -
278
- ```
279
-
280
- Success condition:
281
-
282
- - `connected = true`
283
- - `activeSessionCount >= 1`
284
-
285
- ## Recovery Notes
286
-
287
- - If backend still shows `Bridge required`, reopen the popup in the same browser instance and wait for auto-connect.
288
- - If `start_test_browser_bridge.cjs` fails before backend flips to connected, rerun it with the latest unpacked package in place and read the emitted popup/backend state rather than switching immediately to the manual Chrome path.
289
- - If `chrome.management.getAll()` does not show `DataOps Browser Bridge` in Google Chrome, do not keep retrying synthetic text-entry against the folder picker. Reopen `chrome://extensions/` and perform the final folder selection manually.
290
- - If Chrome is already running on the default profile, prefer the isolated profile/CDP launch above instead of reusing the default profile for automation.
291
-
292
- ## Cleanup
293
-
294
- Only remove temporary artifacts that were created for isolated automation:
295
-
296
- ```powershell
297
- Get-CimInstance Win32_Process -Filter \"Name = 'chrome.exe'\" |
298
- Where-Object { $_.CommandLine -like '*tmp-chrome-browser-bridge-profile*' } |
299
- ForEach-Object { Stop-Process -Id $_.ProcessId -Force }
300
- ```
301
-
302
- ```powershell
303
- Remove-Item D:\project\projects\tmp-dataops-browser-bridge.zip -Force -ErrorAction SilentlyContinue
304
- Remove-Item D:\project\projects\tmp-dataops-browser-bridge -Recurse -Force -ErrorAction SilentlyContinue
305
- Remove-Item D:\project\projects\tmp-chrome-browser-bridge-profile -Recurse -Force -ErrorAction SilentlyContinue
306
- Remove-Item D:\project\projects\tmp-chrome-browser-bridge-profile-2 -Recurse -Force -ErrorAction SilentlyContinue
307
- Remove-Item D:\project\projects\tmp-playwright-browser-bridge-profile -Recurse -Force -ErrorAction SilentlyContinue
308
- Remove-Item D:\project\projects\tmp-chrome-browser-bridge-profile-log -Recurse -Force -ErrorAction SilentlyContinue
309
- ```
@@ -1,4 +0,0 @@
1
- interface:
2
- display_name: "Browser Bridge Chrome Install"
3
- short_description: "Install and verify the DataOps Browser Bridge in Chrome"
4
- default_prompt: "Use $browser-bridge-chrome-install to prepare Chrome for a DataOps Browser Bridge update."
@@ -1,33 +0,0 @@
1
- process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
2
-
3
- async function main() {
4
- const backendOrigin = process.env.DATAOPS_BROWSER_BRIDGE_BACKEND_ORIGIN || 'https://127.0.0.1:3101';
5
- const account = process.env.DATAOPS_BROWSER_BRIDGE_ACCOUNT || 'admin';
6
- const password = process.env.DATAOPS_BROWSER_BRIDGE_PASSWORD;
7
- if (!password) {
8
- throw new Error('set DATAOPS_BROWSER_BRIDGE_PASSWORD before running this script');
9
- }
10
- const loginResponse = await fetch(`${backendOrigin}/api/auth/login`, {
11
- method: 'POST',
12
- headers: { 'content-type': 'application/json' },
13
- body: JSON.stringify({ account, password }),
14
- });
15
- if (!loginResponse.ok) {
16
- throw new Error(`Login failed: ${loginResponse.status}`);
17
- }
18
- const loginPayload = await loginResponse.json();
19
- const toolsResponse = await fetch(`${backendOrigin}/api/ai/tools`, {
20
- headers: { Authorization: `Bearer ${loginPayload.accessToken}` },
21
- });
22
- if (!toolsResponse.ok) {
23
- throw new Error(`GET /api/ai/tools failed: ${toolsResponse.status}`);
24
- }
25
- const toolsPayload = await toolsResponse.json();
26
- const browserTool = toolsPayload.tools.find((tool) => tool.name === 'browser');
27
- console.log(JSON.stringify(browserTool ?? null, null, 2));
28
- }
29
-
30
- main().catch((error) => {
31
- console.error(String(error));
32
- process.exit(1);
33
- });
@@ -1,10 +0,0 @@
1
- Get-CimInstance Win32_Process -Filter "Name = 'chrome.exe'" |
2
- Where-Object { $_.CommandLine -like '*tmp-chrome-browser-bridge-profile*' } |
3
- ForEach-Object { Stop-Process -Id $_.ProcessId -Force }
4
-
5
- Remove-Item D:\project\projects\tmp-dataops-browser-bridge.zip -Force -ErrorAction SilentlyContinue
6
- Remove-Item D:\project\projects\tmp-dataops-browser-bridge -Recurse -Force -ErrorAction SilentlyContinue
7
- Remove-Item D:\project\projects\tmp-chrome-browser-bridge-profile -Recurse -Force -ErrorAction SilentlyContinue
8
- Remove-Item D:\project\projects\tmp-chrome-browser-bridge-profile-2 -Recurse -Force -ErrorAction SilentlyContinue
9
- Remove-Item D:\project\projects\tmp-playwright-browser-bridge-profile -Recurse -Force -ErrorAction SilentlyContinue
10
- Remove-Item D:\project\projects\tmp-chrome-browser-bridge-profile-log -Recurse -Force -ErrorAction SilentlyContinue
@@ -1,25 +0,0 @@
1
- $chrome = 'C:\Users\Administrator\AppData\Local\Google\Chrome\Bin\chrome.exe'
2
- $profile = 'D:\project\projects\tmp-chrome-browser-bridge-profile'
3
- $extension = 'D:\project\projects\tmp-dataops-browser-bridge\extension'
4
-
5
- if (-not (Test-Path $chrome)) {
6
- throw "Chrome executable not found at $chrome"
7
- }
8
- if (-not (Test-Path $extension)) {
9
- throw "Unpacked extension directory not found at $extension"
10
- }
11
-
12
- New-Item -ItemType Directory -Force -Path $profile | Out-Null
13
-
14
- Start-Process -FilePath $chrome -ArgumentList @(
15
- "--user-data-dir=$profile",
16
- '--disable-background-networking',
17
- '--remote-debugging-port=9999',
18
- "--disable-extensions-except=$extension",
19
- "--load-extension=$extension",
20
- '--no-first-run',
21
- '--no-default-browser-check',
22
- '--ignore-certificate-errors',
23
- '--new-window',
24
- 'https://127.0.0.1:3000'
25
- )
@@ -1,245 +0,0 @@
1
- process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
2
-
3
- const fs = require('fs');
4
- const path = require('path');
5
- const { execFileSync } = require('child_process');
6
- const { createRequire } = require('module');
7
-
8
- const repoRoot = process.env.DATAOPS_PROJECTS_ROOT;
9
- if (!repoRoot) {
10
- throw new Error('set DATAOPS_PROJECTS_ROOT to the directory containing the dataops checkout');
11
- }
12
- const frontendRequire = createRequire(path.resolve(repoRoot, 'dataops/frontend/package.json'));
13
- const { chromium } = frontendRequire('playwright');
14
-
15
- const args = new Set(process.argv.slice(2));
16
- const keepOpen = args.has('--keep-open');
17
-
18
- const backendOrigin = process.env.DATAOPS_BROWSER_BRIDGE_BACKEND_ORIGIN || 'https://127.0.0.1:3101';
19
- const frontendOrigin = process.env.DATAOPS_BROWSER_BRIDGE_FRONTEND_ORIGIN || 'https://127.0.0.1:3000';
20
- const account = process.env.DATAOPS_BROWSER_BRIDGE_ACCOUNT || 'admin';
21
- const password = process.env.DATAOPS_BROWSER_BRIDGE_PASSWORD;
22
- if (!password) {
23
- throw new Error('set DATAOPS_BROWSER_BRIDGE_PASSWORD before running this script');
24
- }
25
- const profileDir = process.env.DATAOPS_BROWSER_BRIDGE_PROFILE_DIR || path.resolve(repoRoot, 'tmp-playwright-browser-bridge-profile');
26
- const packageZipPath = path.resolve(repoRoot, 'tmp-dataops-browser-bridge.zip');
27
- const packageDir = path.resolve(repoRoot, 'tmp-dataops-browser-bridge');
28
- const extensionDir = path.resolve(packageDir, 'extension');
29
- const packageVersionPath = path.resolve(packageDir, '.package-version.txt');
30
- const bridgeOrigin = process.env.DATAOPS_BROWSER_BRIDGE_SITE_ORIGIN || backendOrigin;
31
-
32
- async function login() {
33
- const response = await fetch(`${backendOrigin}/api/auth/login`, {
34
- method: 'POST',
35
- headers: { 'content-type': 'application/json' },
36
- body: JSON.stringify({ account, password }),
37
- });
38
- if (!response.ok) {
39
- throw new Error(`Login failed: ${response.status}`);
40
- }
41
- return response.json();
42
- }
43
-
44
- async function fetchBrowserTool(accessToken) {
45
- const response = await fetch(`${backendOrigin}/api/ai/tools`, {
46
- headers: { Authorization: `Bearer ${accessToken}` },
47
- });
48
- if (!response.ok) {
49
- throw new Error(`GET /api/ai/tools failed: ${response.status}`);
50
- }
51
- const payload = await response.json();
52
- return payload.tools.find((tool) => tool.name === 'browser') || null;
53
- }
54
-
55
- async function ensureExtensionPackage(accessToken, browserTool) {
56
- const expectedVersion = browserTool?.dependencyPackage?.version || null;
57
- const manifestPath = path.join(extensionDir, 'manifest.json');
58
- const currentVersion = fs.existsSync(packageVersionPath)
59
- ? fs.readFileSync(packageVersionPath, 'utf8').trim()
60
- : null;
61
- if (fs.existsSync(manifestPath) && expectedVersion && currentVersion === expectedVersion) {
62
- return;
63
- }
64
- const response = await fetch(`${backendOrigin}/api/ai/tools/browser/dependency-package`, {
65
- headers: { Authorization: `Bearer ${accessToken}` },
66
- });
67
- if (!response.ok) {
68
- throw new Error(`GET /api/ai/tools/browser/dependency-package failed: ${response.status}`);
69
- }
70
- fs.writeFileSync(packageZipPath, Buffer.from(await response.arrayBuffer()));
71
- if (fs.existsSync(packageDir)) {
72
- fs.rmSync(packageDir, { recursive: true, force: true });
73
- }
74
- execFileSync('powershell', [
75
- '-NoProfile',
76
- '-Command',
77
- `Expand-Archive -LiteralPath '${packageZipPath}' -DestinationPath '${packageDir}' -Force`,
78
- ], { stdio: 'pipe' });
79
- if (!fs.existsSync(manifestPath)) {
80
- throw new Error(`Unpacked extension manifest not found at ${manifestPath}`);
81
- }
82
- if (expectedVersion) {
83
- fs.writeFileSync(packageVersionPath, `${expectedVersion}\n`);
84
- }
85
- }
86
-
87
- async function getPopupState(popup) {
88
- return popup.evaluate(() => new Promise((resolve) => {
89
- chrome.runtime.sendMessage({ type: 'browser_bridge:get_state' }, (response) => {
90
- resolve({ response, lastError: chrome.runtime?.lastError?.message || null });
91
- });
92
- }));
93
- }
94
-
95
- async function ensurePopupPage(context, extensionId, existingPopup = null) {
96
- const usablePopup =
97
- existingPopup
98
- && !existingPopup.isClosed()
99
- && existingPopup.url().startsWith(`chrome-extension://${extensionId}/`);
100
- if (usablePopup) {
101
- return usablePopup;
102
- }
103
- const popup = await context.newPage();
104
- await popup.goto(`chrome-extension://${extensionId}/popup.html`, {
105
- waitUntil: 'domcontentloaded',
106
- timeout: 60000,
107
- });
108
- return popup;
109
- }
110
-
111
- async function waitForConnected(popup, accessToken) {
112
- for (let attempt = 0; attempt < 30; attempt += 1) {
113
- let popupState;
114
- try {
115
- popupState = await getPopupState(popup);
116
- } catch (error) {
117
- if (String(error).includes('Execution context was destroyed')) {
118
- throw Object.assign(new Error('POPUP_CONTEXT_DESTROYED'), { cause: error });
119
- }
120
- throw error;
121
- }
122
- const browserTool = await fetchBrowserTool(accessToken);
123
- if (popupState.response?.state?.connected === true && browserTool?.browserBridge?.connected === true) {
124
- return { popupState, browserTool };
125
- }
126
- await new Promise((resolve) => setTimeout(resolve, 1000));
127
- }
128
- throw new Error('Timed out waiting for Browser Bridge to connect.');
129
- }
130
-
131
- async function main() {
132
- const loginPayload = await login();
133
- const browserToolBeforeLaunch = await fetchBrowserTool(loginPayload.accessToken);
134
- await ensureExtensionPackage(loginPayload.accessToken, browserToolBeforeLaunch);
135
-
136
- if (fs.existsSync(profileDir)) {
137
- fs.rmSync(profileDir, { recursive: true, force: true });
138
- }
139
-
140
- const context = await chromium.launchPersistentContext(profileDir, {
141
- headless: false,
142
- ignoreHTTPSErrors: true,
143
- args: [
144
- `--disable-extensions-except=${extensionDir}`,
145
- `--load-extension=${extensionDir}`,
146
- '--no-first-run',
147
- '--no-default-browser-check',
148
- '--ignore-certificate-errors',
149
- '--allow-insecure-localhost',
150
- ],
151
- });
152
-
153
- const closeContext = async () => {
154
- try {
155
- await context.close();
156
- } catch {}
157
- };
158
- process.on('SIGINT', async () => {
159
- await closeContext();
160
- process.exit(130);
161
- });
162
- process.on('SIGTERM', async () => {
163
- await closeContext();
164
- process.exit(143);
165
- });
166
-
167
- const page = await context.newPage();
168
- await page.goto(bridgeOrigin, { waitUntil: 'domcontentloaded', timeout: 60000 });
169
- await page.evaluate((token) => localStorage.setItem('dataops_auth_token', token), loginPayload.accessToken);
170
- await page.reload({ waitUntil: 'domcontentloaded', timeout: 60000 });
171
-
172
- let worker = context.serviceWorkers().find((item) => item.url().startsWith('chrome-extension://'));
173
- if (!worker) {
174
- worker = await context.waitForEvent('serviceworker', {
175
- timeout: 60000,
176
- predicate: (item) => item.url().startsWith('chrome-extension://'),
177
- });
178
- }
179
- const extensionId = new URL(worker.url()).host;
180
-
181
- let popup = await ensurePopupPage(context, extensionId);
182
- popup.on('console', (message) => {
183
- console.log(`[popup:console:${message.type()}] ${message.text()}`);
184
- });
185
- popup.on('pageerror', (error) => {
186
- console.log(`[popup:pageerror] ${error.message}`);
187
- });
188
- popup.on('close', () => {
189
- console.log('[popup:close]');
190
- });
191
- await popup.locator('#serverOrigin').fill(bridgeOrigin);
192
-
193
- let popupState;
194
- let browserTool;
195
- try {
196
- ({ popupState, browserTool } = await waitForConnected(popup, loginPayload.accessToken));
197
- } catch (error) {
198
- if (error?.message === 'POPUP_CONTEXT_DESTROYED') {
199
- popup = await ensurePopupPage(context, extensionId, popup);
200
- popup.on('console', (message) => {
201
- console.log(`[popup:console:${message.type()}] ${message.text()}`);
202
- });
203
- popup.on('pageerror', (pageError) => {
204
- console.log(`[popup:pageerror] ${pageError.message}`);
205
- });
206
- popup.on('close', () => {
207
- console.log('[popup:close]');
208
- });
209
- ({ popupState, browserTool } = await waitForConnected(popup, loginPayload.accessToken));
210
- } else {
211
- throw error;
212
- }
213
- }
214
-
215
- const payload = {
216
- ok: true,
217
- frontendOrigin,
218
- backendOrigin,
219
- bridgeOrigin,
220
- profileDir,
221
- extensionDir,
222
- extensionId,
223
- workerUrl: worker.url(),
224
- sessionId: popupState.response?.state?.sessionId || null,
225
- popupState,
226
- backendBridge: browserTool?.browserBridge ?? null,
227
- };
228
-
229
- console.log(JSON.stringify(payload, null, 2));
230
-
231
- if (keepOpen) {
232
- await new Promise(() => {});
233
- } else {
234
- await closeContext();
235
- }
236
- }
237
-
238
- main().catch((error) => {
239
- console.error(JSON.stringify({
240
- ok: false,
241
- error: String(error),
242
- stack: error && error.stack ? error.stack : null,
243
- }, null, 2));
244
- process.exit(1);
245
- });