@seekskyworld/open-browser 0.0.0-stage → 0.2.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.
Files changed (125) hide show
  1. package/CONTRIBUTING.md +15 -0
  2. package/Docs/Agent/346/265/217/350/247/210/345/231/250/346/200/273/344/275/223/346/236/266/346/236/204.md +58 -0
  3. package/Docs/THIRD-PARTY-NOTICES.md +12 -0
  4. package/Docs/open-browser-api.d.ts +291 -0
  5. package/Docs/open-browser/344/273/273/345/212/241/350/257/204/346/265/213/346/214/207/345/215/227.md +59 -0
  6. package/Docs/open-browser/351/232/220/347/247/201/344/270/216/345/274/200/346/272/220/345/256/241/350/256/241.md +37 -0
  7. package/Docs//346/216/247/345/210/266/345/217/260/345/210/206/347/273/204/344/270/216/346/216/245/347/256/241/346/226/271/346/241/210.md +31 -0
  8. package/Docs//350/267/250/345/271/263/345/217/260/350/257/225/347/224/250/344/270/216/345/217/221/350/241/214.md +84 -0
  9. package/LICENSE +200 -0
  10. package/README.md +159 -2
  11. package/README.zh-CN.md +166 -0
  12. package/SECURITY.md +9 -0
  13. package/access-registry.mjs +156 -0
  14. package/action-execution.mjs +385 -0
  15. package/activity-notifier.mjs +34 -0
  16. package/api-contract.mjs +134 -0
  17. package/browser-extension/icons/open-browser-128.png +0 -0
  18. package/browser-extension/icons/open-browser-16.png +0 -0
  19. package/browser-extension/icons/open-browser-32.png +0 -0
  20. package/browser-extension/icons/open-browser-48.png +0 -0
  21. package/browser-extension/icons/open-browser-wordmark.png +0 -0
  22. package/browser-extension/manifest.json +35 -0
  23. package/browser-extension/newtab.css +26 -0
  24. package/browser-extension/newtab.html +19 -0
  25. package/browser-extension/newtab.js +174 -0
  26. package/browser-extension/phase-labels.js +9 -0
  27. package/browser-extension/popup.css +19 -0
  28. package/browser-extension/popup.html +56 -0
  29. package/browser-extension/popup.js +405 -0
  30. package/browser-extension/tab-action.js +138 -0
  31. package/browser-extension/worker.js +281 -0
  32. package/browser-extension/workspace-title.js +15 -0
  33. package/build-profile.mjs +23 -0
  34. package/capability-matrix.mjs +21 -0
  35. package/chromium-host.mjs +209 -0
  36. package/chromium-shell.mjs +179 -0
  37. package/cli.mjs +141 -0
  38. package/contract-validation.mjs +27 -0
  39. package/control.mjs +107 -0
  40. package/desktop/Info.plist +13 -0
  41. package/desktop/Launcher.m +117 -0
  42. package/desktop/OBControlBar.h +7 -0
  43. package/desktop/OBControlBar.m +217 -0
  44. package/desktop/OBPageView.h +6 -0
  45. package/desktop/OBPageView.m +348 -0
  46. package/desktop/WorkspacePanel.h +16 -0
  47. package/desktop/WorkspacePanel.m +916 -0
  48. package/desktop/archive-release.py +129 -0
  49. package/desktop/brand-keychain.py +111 -0
  50. package/desktop/brand-locales.py +93 -0
  51. package/desktop/brand-macos-icons.py +24 -0
  52. package/desktop/brand-windows-icons.mjs +48 -0
  53. package/desktop/build-macos.mjs +112 -0
  54. package/desktop/build-managed-input.mjs +37 -0
  55. package/desktop/build-portable.mjs +95 -0
  56. package/desktop/build-profile.mjs +6 -0
  57. package/desktop/build.mjs +13 -0
  58. package/desktop/create-shortcut.ps1 +9 -0
  59. package/desktop/generate-icons.py +39 -0
  60. package/desktop/icons/open-browser.icns +0 -0
  61. package/desktop/icons/open-browser.ico +0 -0
  62. package/desktop/install-menu-entry.mjs +24 -0
  63. package/desktop/macos-entitlements.plist +12 -0
  64. package/desktop/notarize-macos.mjs +145 -0
  65. package/desktop/package-assets.mjs +34 -0
  66. package/desktop/package-macos.mjs +54 -0
  67. package/desktop/patches/chromium-macos-keychain-service.patch +18 -0
  68. package/desktop/patches/chromium-managed-input.patch +144 -0
  69. package/desktop/portable-archive.py +22 -0
  70. package/desktop/sign.mjs +77 -0
  71. package/desktop/smoke-portable.mjs +65 -0
  72. package/desktop/start-profile.mjs +5 -0
  73. package/desktop/start.mjs +34 -0
  74. package/desktop/verify-macos-release.mjs +61 -0
  75. package/desktop/verify-upgrade.mjs +74 -0
  76. package/desktop/verify-version.mjs +12 -0
  77. package/desktop-page.mjs +211 -0
  78. package/diagnostics.mjs +37 -0
  79. package/downloads.mjs +110 -0
  80. package/engine-service.mjs +1158 -0
  81. package/hosted/README.md +74 -0
  82. package/hosted/cli.mjs +17 -0
  83. package/hosted/directory.mjs +261 -0
  84. package/hosted/init.mjs +37 -0
  85. package/hosted/server.mjs +129 -0
  86. package/managed-input.mjs +138 -0
  87. package/managed-popup.mjs +54 -0
  88. package/mcp-http.mjs +84 -0
  89. package/mcp-server.mjs +41 -0
  90. package/mcp.mjs +5 -0
  91. package/network-policy.mjs +107 -0
  92. package/output-store.mjs +96 -0
  93. package/package.json +77 -4
  94. package/page-activity.mjs +188 -0
  95. package/page-dialogs.mjs +53 -0
  96. package/page-observation.mjs +318 -0
  97. package/paths.mjs +22 -0
  98. package/privacy-config.mjs +95 -0
  99. package/receipt-store.mjs +198 -0
  100. package/runtime.mjs +53 -0
  101. package/scheduler.mjs +70 -0
  102. package/sdk.mjs +193 -0
  103. package/service.mjs +290 -0
  104. package/site-workflow.mjs +115 -0
  105. package/skill-links.mjs +90 -0
  106. package/skills/open-browser/SKILL.macos.md +112 -0
  107. package/skills/open-browser/SKILL.md +107 -0
  108. package/skills/open-browser/SKILL.windows.md +112 -0
  109. package/skills/open-browser/scripts/bootstrap.mjs +213 -0
  110. package/skills/open-browser/scripts/open-browser +21 -0
  111. package/skills/open-browser/scripts/open-browser.cmd +9 -0
  112. package/skills/open-browser/workflows/login-export.json +10 -0
  113. package/skills/open-browser/workflows/upload-verify.json +8 -0
  114. package/studio/demo-site.mjs +111 -0
  115. package/studio/demo.css +1 -0
  116. package/studio/index.html +66 -0
  117. package/studio/index.mjs +57 -0
  118. package/studio/native-demo.mjs +124 -0
  119. package/studio/studio.css +119 -0
  120. package/studio/studio.js +438 -0
  121. package/tab-adoption.mjs +77 -0
  122. package/uploads.mjs +63 -0
  123. package/visual-page.mjs +306 -0
  124. package/workspace-lifecycle.mjs +238 -0
  125. package/workspace-state.mjs +107 -0
@@ -0,0 +1,198 @@
1
+ // The service owns its local socket exclusively before opening this journal.
2
+ import {EventEmitter} from 'node:events';
3
+ import { operationDiagnostic } from './diagnostics.mjs';
4
+ import { chmodSync } from 'node:fs';
5
+ import { DatabaseSync } from 'node:sqlite';
6
+
7
+ const retentionMs = 7 * 24 * 3600_000;
8
+
9
+ export function durableReceipt(receipt) {
10
+ const {operationId, pageId, state, phase, totalSteps, stepKind, completedSteps, error, keptPageIds, closedPageIds, fillOutcome} = receipt;
11
+ return { operationId, ...(pageId && {pageId}), state, ...(phase && {phase}), ...(totalSteps !== undefined && {totalSteps}),
12
+ ...(stepKind && {stepKind}), completedSteps, ...(error && {error}),
13
+ ...(fillOutcome && {fillOutcome}),
14
+ ...(receipt.navigation && {navigation:receipt.navigation}),
15
+ ...(keptPageIds && {keptPageIds: [...keptPageIds]}), ...(closedPageIds && {closedPageIds: [...closedPageIds]}) };
16
+ }
17
+
18
+ export class ReceiptStore {
19
+ constructor(path = ':memory:', actor = () => undefined) {
20
+ this.actor = actor;
21
+ this.notifications = new EventEmitter();
22
+ this.waiting = 0;
23
+ this.db = new DatabaseSync(path);
24
+ if (path !== ':memory:') chmodSync(path, 0o600);
25
+ this.db.exec(`PRAGMA synchronous=FULL;
26
+ CREATE TABLE IF NOT EXISTS receipts (
27
+ owner TEXT, workspace TEXT, operation TEXT, digest TEXT NOT NULL, data TEXT NOT NULL,
28
+ inflight INTEGER NOT NULL, expires INTEGER NOT NULL, PRIMARY KEY(owner,workspace,operation));
29
+ CREATE TABLE IF NOT EXISTS recovery_objects (
30
+ owner TEXT NOT NULL, workspace TEXT NOT NULL, kind TEXT NOT NULL, id TEXT NOT NULL, expires INTEGER NOT NULL,
31
+ PRIMARY KEY(owner,workspace,kind,id));
32
+ CREATE INDEX IF NOT EXISTS recovery_expiry ON recovery_objects(expires);
33
+ CREATE INDEX IF NOT EXISTS receipt_expiry ON receipts(expires);
34
+ CREATE TABLE IF NOT EXISTS events (
35
+ sequence INTEGER PRIMARY KEY AUTOINCREMENT, owner TEXT, workspace TEXT, kind TEXT, state TEXT,
36
+ operationId TEXT, completedSteps INTEGER, expires INTEGER, actorId TEXT, pixelWidth INTEGER, pixelHeight INTEGER);
37
+ CREATE INDEX IF NOT EXISTS event_feed ON events(owner,workspace,sequence);
38
+ CREATE INDEX IF NOT EXISTS event_expiry ON events(expires);`);
39
+ if (!this.db.prepare('PRAGMA table_info(recovery_objects)').all().some(field => field.name === 'disposition'))
40
+ this.db.exec('ALTER TABLE recovery_objects ADD COLUMN disposition TEXT');
41
+ this.sweep = this.db.prepare('DELETE FROM receipts WHERE expires <= ?');
42
+ this.sweepRecovery = this.db.prepare('DELETE FROM recovery_objects WHERE expires<=?');
43
+ this.sweepRecovery.run(Date.now());
44
+ this.sweep.run(Date.now());
45
+ this.sweepEvents = this.db.prepare('DELETE FROM events WHERE expires<=?');
46
+ this.sweepEvents.run(Date.now());
47
+ const columns = new Set(this.db.prepare('PRAGMA table_info(events)').all().map(field=>field.name));
48
+ for(const [name,type] of [['actorId','TEXT'],['pixelWidth','INTEGER'],['pixelHeight','INTEGER'],['pageId','TEXT'],['resourceId','TEXT']])
49
+ if(!columns.has(name)) this.db.exec(`ALTER TABLE events ADD COLUMN ${name} ${type}`);
50
+ this.appendEvent = this.db.prepare('INSERT INTO events(owner,workspace,kind,state,operationId,completedSteps,expires,actorId,pixelWidth,pixelHeight,pageId,resourceId) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)');
51
+ this.nextSweep = Date.now() + 60_000;
52
+ this.read = this.db.prepare('SELECT digest,data FROM receipts WHERE owner=? AND workspace=? AND operation=? AND expires>?');
53
+ this.write = this.db.prepare(`INSERT INTO receipts VALUES (?,?,?,?,?,?,?)
54
+ ON CONFLICT(owner,workspace,operation) DO UPDATE SET data=excluded.data,inflight=excluded.inflight,expires=excluded.expires
55
+ WHERE receipts.digest=excluded.digest`);
56
+ for (const row of this.db.prepare('SELECT * FROM receipts WHERE json_extract(data,\'$.state\') IN (\'queued\',\'running\')').all()) {
57
+ const receipt = JSON.parse(row.data);
58
+ receipt.state = row.inflight ? 'outcome_unknown' : 'cancelled';
59
+ receipt.phase = receipt.state;
60
+ receipt.error = row.inflight ? 'inspect_before_retry' : 'service_restarted';
61
+ this.save(row.owner, row.workspace, row.digest, receipt);
62
+ }
63
+ }
64
+
65
+ remember(owner, workspace, kind, id) {
66
+ this.db.prepare('INSERT OR REPLACE INTO recovery_objects(owner,workspace,kind,id,expires) VALUES (?,?,?,?,?)')
67
+ .run(owner, workspace, kind, id, Date.now() + retentionMs);
68
+ }
69
+
70
+ pageDisposition(owner, workspace, id, disposition) {
71
+ this.db.prepare("UPDATE recovery_objects SET disposition=? WHERE owner=? AND workspace=? AND kind='page' AND id=?")
72
+ .run(disposition, owner, workspace, id);
73
+ }
74
+
75
+ recoveryObjects(owner, workspace, after = 0, limit = 50) {
76
+ if (!Number.isSafeInteger(after) || after < 0) throw Object.assign(new Error('invalid_params'), {code:'invalid_params'});
77
+ // ReceiptStore.list has already validated the common limit.
78
+ const rows = this.db.prepare('SELECT rowid,kind,id,disposition FROM recovery_objects WHERE owner=? AND workspace=? AND expires>? AND rowid>? ORDER BY rowid LIMIT ?')
79
+ .all(owner, workspace, Date.now(), after, limit + 1);
80
+ return {records:rows.slice(0,limit), nextObjectCursor:rows.length > limit ? rows[limit-1].rowid : null};
81
+ }
82
+
83
+ get(owner, workspace, id) {
84
+ if (typeof workspace !== 'string' || typeof id !== 'string') return null;
85
+ const row = this.read.get(owner, workspace, id, Date.now());
86
+ return row ? { digest: row.digest, receipt: JSON.parse(row.data) } : null;
87
+ }
88
+
89
+ list(owner, workspace, after = 0, limit = 50) {
90
+ if (typeof workspace !== 'string' || !Number.isSafeInteger(after) || after < 0 ||
91
+ !Number.isInteger(limit) || limit < 1 || limit > 100)
92
+ throw Object.assign(new Error('invalid_params'), {code:'invalid_params'});
93
+ const rows = this.db.prepare('SELECT rowid,data FROM receipts WHERE owner=? AND workspace=? AND rowid>? AND expires>? ORDER BY rowid LIMIT ?')
94
+ .all(owner, workspace, after, Date.now(), limit + 1);
95
+ return { operations: rows.slice(0, limit).map(row => JSON.parse(row.data)),
96
+ nextCursor: rows.length > limit ? rows[limit - 1].rowid : null };
97
+ }
98
+
99
+ save(owner, workspace, digest, receipt, inflight = false) {
100
+ const now = Date.now();
101
+ if (now >= this.nextSweep) {
102
+ this.sweepRecovery.run(now);
103
+ this.sweep.run(now);
104
+ this.sweepEvents.run(now);
105
+ this.nextSweep = now + 60_000;
106
+ }
107
+ this.db.exec('BEGIN IMMEDIATE');
108
+ try {
109
+ const result = this.write.run(owner, workspace, receipt.operationId, digest,
110
+ JSON.stringify(durableReceipt(receipt)), Number(inflight), now + retentionMs);
111
+ if (!result.changes) throw Object.assign(new Error('operation_id_conflict'), {code:'operation_id_conflict'});
112
+ this.event(owner, workspace, inflight ? 'dispatch' : 'operation', receipt.state, receipt.operationId, receipt.completedSteps);
113
+ this.db.exec('COMMIT');
114
+ } catch (error) { this.db.exec('ROLLBACK'); throw error; }
115
+ }
116
+
117
+ event(owner, workspace, kind, state, operation = null, steps = null, size = {}) {
118
+ this.appendEvent.run(owner, workspace, kind, state, operation, steps, Date.now() + retentionMs, this.actor() || owner,
119
+ size.pixelWidth ?? null, size.pixelHeight ?? null, size.pageId ?? null,size.resourceId ?? null);
120
+ if (size.resourceId) this.notifications.emit(workspace);
121
+
122
+ }
123
+
124
+ events(owner, workspace, after = 0, limit = 50) {
125
+ if (typeof workspace !== 'string' || !Number.isSafeInteger(after) || after < 0 ||
126
+ !Number.isInteger(limit) || limit < 1 || limit > 100)
127
+ throw Object.assign(new Error('invalid_params'), {code:'invalid_params'});
128
+ const rows = this.db.prepare('SELECT sequence,kind,state,operationId,completedSteps,actorId,pixelWidth,pixelHeight,pageId,resourceId FROM events WHERE owner=? AND workspace=? AND sequence>? AND expires>? ORDER BY sequence LIMIT ?')
129
+ .all(owner, workspace, after, Date.now(), limit);
130
+ return { events: rows.map(row => Object.fromEntries(Object.entries(row).filter(([,value]) => value !== null))),
131
+ nextCursor: rows.at(-1)?.sequence ?? after };
132
+ }
133
+
134
+ cursor(owner,workspace) {
135
+ return {nextCursor:this.db.prepare('SELECT COALESCE(MAX(sequence),0) AS cursor FROM events WHERE owner=? AND workspace=?')
136
+ .get(owner,workspace).cursor};
137
+ }
138
+
139
+ waitForEvent(owner,{workspaceId,pageId,operationId,kind,after,timeoutMs=5000}) {
140
+ if (!Number.isSafeInteger(after) || after<0 || !Number.isSafeInteger(timeoutMs) || timeoutMs<1 || timeoutMs>10000 ||
141
+ !['dialog','popup','download'].includes(kind) || typeof pageId!=='string' ||
142
+ (operationId!==undefined && typeof operationId!=='string'))
143
+ throw Object.assign(new Error('invalid_params'),{code:'invalid_params'});
144
+ const sql=`SELECT sequence,kind,state,pageId,resourceId,operationId FROM events
145
+ WHERE owner=? AND workspace=? AND pageId=? AND kind=? AND sequence>? AND expires>?
146
+ AND (? IS NULL OR operationId=?) ORDER BY sequence LIMIT 1`;
147
+ const query=this.db.prepare(sql);
148
+ const read=()=>{
149
+ const row=query.get(owner,workspaceId,pageId,kind,after,Date.now(),operationId??null,operationId??null);
150
+ if (row?.operationId===null) delete row.operationId;
151
+ return row && {event:row,nextCursor:row.sequence};
152
+ };
153
+ const first=read();
154
+ if (first) return first;
155
+ if (this.waiting>=128 || this.notifications.listenerCount(workspaceId)>=8)
156
+ throw Object.assign(new Error('queue_full'),{code:'queue_full'});
157
+ return new Promise(resolve=>{
158
+ const done=result=>{
159
+ clearTimeout(timer);
160
+ this.notifications.off(workspaceId,changed);
161
+ this.waiting--;
162
+ resolve(result || {event:null,nextCursor:after});
163
+ };
164
+ const changed=()=>{
165
+ if (this.closing) return done();
166
+ const event=read();
167
+ if (event) done(event);
168
+ };
169
+ this.waiting++;
170
+ const timer=setTimeout(done,timeoutMs);
171
+ this.notifications.on(workspaceId,changed);
172
+ });
173
+ }
174
+
175
+ diagnose(owner, workspace, operationId) {
176
+ const record = this.get(owner, workspace, operationId);
177
+ if (!record) throw Object.assign(new Error('operation_not_found'), {code:'operation_not_found'});
178
+ const dispatched = this.db.prepare("SELECT 1 FROM events WHERE owner=? AND workspace=? AND operationId=? AND kind='dispatch' AND expires>? LIMIT 1")
179
+ .get(owner, workspace, operationId, Date.now());
180
+ return operationDiagnostic(record.receipt, Boolean(dispatched));
181
+ }
182
+
183
+ clear(workspace) {
184
+ this.db.exec('BEGIN IMMEDIATE');
185
+ try {
186
+ this.db.prepare('DELETE FROM recovery_objects WHERE workspace=?').run(workspace);
187
+ this.db.prepare('DELETE FROM receipts WHERE workspace=?').run(workspace);
188
+ this.db.prepare('DELETE FROM events WHERE workspace=?').run(workspace);
189
+ this.db.exec('COMMIT');
190
+ } catch (error) { this.db.exec('ROLLBACK'); throw error; }
191
+ }
192
+
193
+ close() {
194
+ this.closing=true;
195
+ for (const workspace of this.notifications.eventNames()) this.notifications.emit(workspace);
196
+ this.db.close();
197
+ }
198
+ }
package/runtime.mjs ADDED
@@ -0,0 +1,53 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { readFile, realpath, rename, writeFile } from 'node:fs/promises';
4
+ import { createRequire } from 'node:module';
5
+ import path from 'node:path';
6
+ import { fileURLToPath, pathToFileURL } from 'node:url';
7
+
8
+ const require = createRequire(import.meta.url);
9
+ const version = require('playwright-core/package.json').version;
10
+ const engineDir = fileURLToPath(new URL('./.open-browser/engine/', import.meta.url));
11
+ function targetArch() {
12
+ return process.env.OPEN_BROWSER_TARGET_ARCH?.trim() || process.arch;
13
+ }
14
+
15
+ export async function engineExecutable() {
16
+ const arch = targetArch();
17
+ const manifest = path.join(engineDir, `engine-${version}-${process.platform}-${arch}.json`);
18
+ if (process.platform === 'darwin' && !['arm64', 'x64'].includes(arch))
19
+ throw new Error('macOS 引擎目标架构必须是 arm64 或 x64。');
20
+ try {
21
+ const entry = JSON.parse(await readFile(manifest, 'utf8'));
22
+ const executable = await realpath(path.join(engineDir, entry.executable));
23
+ const relative = path.relative(await realpath(engineDir), executable);
24
+ if (!relative || relative.startsWith('..' + path.sep) || path.isAbsolute(relative))
25
+ throw new Error('Invalid engine path');
26
+ return executable;
27
+ } catch {
28
+ throw new Error('open-browser engine unavailable. Run npm run browser:install.');
29
+ }
30
+ }
31
+
32
+ async function install() {
33
+ if (process.platform === 'darwin' && targetArch !== process.arch)
34
+ throw new Error(`当前 Node 是 ${process.arch},不能下载并登记 ${targetArch} 引擎。请在对应架构的 macOS 或 Rosetta x64 Node 下运行。`);
35
+ process.env.PLAYWRIGHT_BROWSERS_PATH = engineDir;
36
+ const cli = path.join(path.dirname(require.resolve('playwright-core/package.json')), 'cli.js');
37
+ execFileSync(process.execPath, [cli, 'install', 'chromium', '--no-shell'], { stdio: 'inherit' });
38
+ const { chromium } = await import('playwright-core');
39
+ let binary = await realpath(chromium.executablePath());
40
+ if (process.platform === 'win32') {
41
+ const { installWindowsIcons } = await import('./desktop/brand-windows-icons.mjs');
42
+ binary = await installWindowsIcons(binary);
43
+ }
44
+ const executable = path.relative(engineDir, binary);
45
+ const manifest = path.join(engineDir, `engine-${version}-${process.platform}-${targetArch()}.json`);
46
+ const temp = manifest + '.' + randomUUID();
47
+ await writeFile(temp, JSON.stringify({ executable }) + '\n', { flag: 'wx' });
48
+ await rename(temp, manifest);
49
+ }
50
+
51
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
52
+ await install();
53
+ }
package/scheduler.mjs ADDED
@@ -0,0 +1,70 @@
1
+ // Requests in a page lane enter this scheduler only when the preceding operation settles.
2
+ export class WorkspaceScheduler {
3
+ constructor(maximum, { lowMemoryMiB = 0, availableBytes = () => process.availableMemory() } = {}) {
4
+ if (!Number.isSafeInteger(lowMemoryMiB) || lowMemoryMiB < 0) throw new Error('invalid_memory_watermark');
5
+ this.maximum = maximum;
6
+ this.limit = maximum;
7
+ this.active = 0;
8
+ this.queues = new Map();
9
+ this.lowBytes = lowMemoryMiB * 1024 * 1024;
10
+ this.availableBytes = availableBytes;
11
+ this.sampledAt = -Infinity;
12
+ this.completed = 0;
13
+ this.waitMs = 0;
14
+ this.executionMs = 0;
15
+ }
16
+
17
+ refreshLimit(now) {
18
+ if (!this.lowBytes || now - this.sampledAt < 1000) return;
19
+ this.sampledAt = now;
20
+ const available = this.availableBytes();
21
+ // Unknown readings keep the previous limit. Separate watermarks avoid rapid oscillation.
22
+ if (available > 0 && available < this.lowBytes) this.limit = Math.max(1, Math.floor(this.maximum / 2));
23
+ if (available > this.lowBytes * 1.5) this.limit = this.maximum;
24
+ }
25
+
26
+ drain() {
27
+ this.refreshLimit(performance.now());
28
+ while (this.active < this.limit && this.queues.size) {
29
+ const [workspace, queue] = this.queues.entries().next().value;
30
+ this.queues.delete(workspace);
31
+ const item = queue.shift();
32
+ if (queue.length) this.queues.set(workspace, queue);
33
+ this.active++;
34
+ item.start();
35
+ }
36
+ }
37
+
38
+ async run(workspace, work, signal, enqueuedAt) {
39
+ if (signal.aborted) throw Object.assign(new Error('operation_cancelled'), {code:'operation_cancelled'});
40
+ await new Promise((resolve, reject) => {
41
+ const queue = this.queues.get(workspace) || [];
42
+ const item = { start: () => { signal.removeEventListener('abort', abort); resolve(); } };
43
+ const abort = () => {
44
+ const index = queue.indexOf(item);
45
+ if (index >= 0) queue.splice(index, 1);
46
+ if (!queue.length && this.queues.get(workspace) === queue) this.queues.delete(workspace);
47
+ reject(Object.assign(new Error('operation_cancelled'), {code:'operation_cancelled'}));
48
+ };
49
+ signal.addEventListener('abort', abort, {once:true});
50
+ queue.push(item);
51
+ this.queues.set(workspace, queue);
52
+ this.drain();
53
+ });
54
+ const started = performance.now();
55
+ this.waitMs += started - enqueuedAt;
56
+ try { return await work(); }
57
+ finally {
58
+ this.executionMs += performance.now() - started;
59
+ this.completed++;
60
+ this.active--;
61
+ this.drain();
62
+ }
63
+ }
64
+
65
+ snapshot(pending) {
66
+ return { maximum:this.maximum, limit:this.limit, active:this.active, pending,
67
+ lowMemoryMiB:this.lowBytes / 1048576, completed:this.completed,
68
+ cumulativeWaitMs:Math.round(this.waitMs), cumulativeExecutionMs:Math.round(this.executionMs) };
69
+ }
70
+ }
package/sdk.mjs ADDED
@@ -0,0 +1,193 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { Agent, request } from 'node:http';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { pathsForProfile, profileId } from './paths.mjs';
5
+
6
+ import { agentMethods, limits } from './api-contract.mjs';
7
+ export { agentMethods };
8
+
9
+ /**
10
+ * A short, machine-readable hint for the next safe operation after a common
11
+ * service error. The hint never replaces the server error message.
12
+ */
13
+ export const recoveryHints = Object.freeze({
14
+ SERVICE_UNAVAILABLE: '启动 open-browser 后重试同一只读请求。',
15
+ TASK_NAME_REQUIRED: '为 createWorkspace 或 open 提供清晰的非空 name,再重新创建任务。',
16
+ REQUEST_TIMEOUT: '用同一 operationId 查询 getOperation 或 diagnoseOperation,再决定是否继续。',
17
+ stale_ref: '重新 observe 当前页面并用新 ref 构造动作。',
18
+ stale_document: '重新 observe 当前页面后再执行动作。',
19
+ stale_control: '重新 observe 获取最新 controlGeneration。',
20
+ stale_observation: '重新 observe 当前页面,不要复用旧文档标识。',
21
+ target_obscured: '重新 observe 并等待遮罩消失,再用新的 operationId 重试。',
22
+ target_ambiguous: '用 observe 的 locator 或 within 缩小目标范围。',
23
+ target_missing: '重新 observe 并核对页面状态或目标名称。',
24
+ navigation_failed: '先 observe 当前页面和地址,再决定是否重试导航。',
25
+ origin_denied: '核对 blockedOrigins,取得控制权后用 grantOrigin 授权所需来源。',
26
+ profile_mismatch: '请切换至该标签页所在的 open-browser profile。',
27
+ adoption_expired: '请用户在原标签页重新签发授权,使用所选任务的 workspaceId 兑换。',
28
+ adoption_page_changed: '请用户核对当前标签和站点,再授权此页。',
29
+ adoption_requires_empty_workspace: '创建新的命名工作区,再让用户选择该任务。',
30
+ adoption_requires_private_workspace: '创建一个仅当前 Agent 使用的新任务后重新授权。',
31
+ sync_pending: '扩展尚未确认该页。请读取 getWorkspace 后重试 reattachPage。',
32
+ single_tab_scope: '此授权覆盖用户所选的一页及其站点。其他页需要单独授权。',
33
+ page_not_found: '用 getRecoverySummary 核对原页状态,需要时请用户重新选择标签。',
34
+ workspace_not_found: '核对 profileId。服务重启后用 getRecoverySummary 查历史,并请用户重新授权原页。',
35
+ finish_preview_changed: '等待当前操作完成,重新调用 previewFinish 核对页面清单。',
36
+ input_guard_unavailable: '请检查 Dev Chromium 是否包含受管页面输入保护补丁。',
37
+ workspace_under_user_control: '等待用户交回 Agent 控制权后重新 observe。',
38
+ outcome_unknown: '先用 getOperation 或 diagnoseOperation,并核对站点结果后再重试。',
39
+ inspect_before_retry: '先核对站点是否已生效,再决定是否提交新的 operationId。',
40
+ run_timeout: '运行预算已耗尽。用同一 operationId 查询回执,并核对站点结果后再决定是否继续。',
41
+ invalid_params: '运行 --schema 或读取 capabilities,按当前契约修正参数。',
42
+ });
43
+
44
+ export class OpenBrowserError extends Error {
45
+ constructor(code, message) {
46
+ super(message);
47
+ this.name = 'OpenBrowserError';
48
+ this.code = code;
49
+ this.nextAction = recoveryHints[code];
50
+ }
51
+ }
52
+
53
+ const unavailable = () => new OpenBrowserError('SERVICE_UNAVAILABLE', '请先启动 open-browser 本地服务。');
54
+
55
+ export class OpenBrowserClient {
56
+ constructor(options = {}) {
57
+ const selected = pathsForProfile(options.profileId ?? profileId);
58
+ this.socketPath = options.socketPath ?? selected.socketPath;
59
+ this.tokenPath = options.tokenPath ?? process.env.OPEN_BROWSER_CLIENT_TOKEN_FILE ?? selected.tokenPath;
60
+ this.agent = options.agent ?? new Agent({ keepAlive: true, maxSockets: 4 });
61
+ const codex = process.env.CODEX_THREAD_ID || process.env.CODEX_SESSION_ID;
62
+ this.agentName = options.agentName ?? (process.env.OPEN_BROWSER_AGENT_NAME?.trim() ||
63
+ (codex ? 'Codex' : options.fallbackName ?? 'SDK'));
64
+ }
65
+
66
+ async call(method, params = {}) {
67
+ if (!agentMethods.includes(method))
68
+ throw new OpenBrowserError('UNKNOWN_METHOD', '未知的 Agent API 方法。');
69
+ if (!params || typeof params !== 'object' || Array.isArray(params))
70
+ throw new OpenBrowserError('INVALID_PARAMS', '参数必须是 JSON 对象。');
71
+ if (['createWorkspace', 'open'].includes(method) &&
72
+ (typeof params.name !== 'string' || !params.name.trim()))
73
+ throw new OpenBrowserError('TASK_NAME_REQUIRED', '创建 Agent 任务时必须提供非空任务名称 name。');
74
+ if (['createWorkspace','open'].includes(method) && params.agentName === undefined)
75
+ params = { ...params, agentName: this.agentName };
76
+ return localRequest(this.socketPath,this.tokenPath,'/v1/call',method,params,this.agent);
77
+ }
78
+ async capabilities() {
79
+ try { return await this.call('capabilities'); }
80
+ catch(error) {
81
+ if (['UNKNOWN_METHOD','unknown_method','forbidden'].includes(error.code)) return {version:0,visual:{enabled:false,actions:[]}};
82
+ throw error;
83
+ }
84
+ }
85
+ captureVisual(page, options = {}) { return this.call('captureVisual',{...options,...page}); }
86
+ respondDialog(page, response) { return this.call('respondDialog',{...response,...page}); }
87
+ listUploads(workspaceId) { return this.call('listUploads',{workspaceId}); }
88
+ listDownloads(workspaceId) { return this.call('listDownloads', {workspaceId}); }
89
+ listOutputs(workspaceId) { return this.call('listOutputs', {workspaceId}); }
90
+ readOutput(workspaceId, outputId, options = {}) { return this.call('readOutput', { ...options, workspaceId, outputId }); }
91
+ cancelDownload(workspaceId, downloadId) { return this.call('cancelDownload', {workspaceId, downloadId}); }
92
+ eventCursor(workspaceId) { return this.call('eventCursor',{workspaceId}); }
93
+ waitForEvent(page,options) { return this.call('waitForEvent',{...options,...page}); }
94
+ listEvents(workspaceId, options = {}) { return this.call('listEvents', { ...options, workspaceId }); }
95
+ getRecoverySummary(workspaceId, options = {}) { return this.call('getRecoverySummary', { ...options, workspaceId }); }
96
+ listOperations(workspaceId, options = {}) { return this.call('listOperations', { ...options, workspaceId }); }
97
+ finishWorkspace(workspaceId, keepPageIds, operationId, previewId) {
98
+ return this.call('finishWorkspace', {workspaceId, keepPageIds, operationId, previewId});
99
+ }
100
+
101
+ /** Finish a workspace with a fresh idempotency key generated by the SDK. */
102
+ finish(workspaceId, keepPageIds = []) {
103
+ return this.finishWorkspace(workspaceId, keepPageIds, randomUUID());
104
+ }
105
+
106
+ createWorkspace(params = {}) { return this.call('createWorkspace', params); }
107
+ open(params = {}) { return this.call('open', params); }
108
+ grantOrigin(params) { return this.call('grantOrigin', params); }
109
+ listWorkspaces() { return this.call('listWorkspaces'); }
110
+ getWorkspace(workspaceId) { return this.call('getWorkspace', { workspaceId }); }
111
+ openPage(workspaceId, url) { return this.call('openPage', { workspaceId, url }); }
112
+ canvasSnapshot(page) { return this.call('canvasSnapshot', page); }
113
+ adoptCurrentTab(workspaceId, adoptionToken) { return this.call('adoptCurrentTab', {workspaceId, adoptionToken}); }
114
+ reattachPage(page, options = {}) { return this.call('reattachPage', {...options, ...page}); }
115
+ previewFinish(workspaceId, keepPageIds = []) { return this.call('previewFinish', {workspaceId, keepPageIds}); }
116
+ observe(page) { return this.call('observe', page); }
117
+ observeAndAct(page, request = {}) {
118
+ const { actions, observeAfter, timeoutMs, operationId = randomUUID(), ...observeOptions } = request;
119
+ if (!Array.isArray(actions) || actions.length === 0)
120
+ return Promise.reject(new OpenBrowserError('INVALID_PARAMS', 'observeAndAct 需要至少一个 action。'));
121
+ return this.call('observeAndAct', {
122
+ ...page, ...observeOptions, actions, observeAfter, timeoutMs, operationId,
123
+ });
124
+ }
125
+ /** Open one URL and immediately return its first observation. */
126
+ async openAndObserve(options = {}, observeOptions = {}) {
127
+ const page = await this.open(options);
128
+ const observation = await this.observe({ ...page, ...observeOptions });
129
+ return { ...page, observation };
130
+ }
131
+ /** Observe immediately before acting, while preserving document and control checks. */
132
+ async actAfterObserve(page, request = {}) {
133
+ return this.observeAndAct(page, request).then(({ observation, receipt }) => ({ observation, receipt }));
134
+ }
135
+ runWorkflow(page, request) { return this.call('runWorkflow',{...request,...page}); }
136
+ act(page, operation) { return this.call('act', { ...operation, ...page }); }
137
+ diagnoseOperation(workspaceId, operationId) { return this.call('diagnoseOperation', {workspaceId, operationId}); }
138
+ getOperation(workspaceId, operationId) {
139
+ return this.call('getOperation', { workspaceId, operationId });
140
+ }
141
+ cancelOperation(workspaceId, operationId) {
142
+ return this.call('cancelOperation', { workspaceId, operationId });
143
+ }
144
+ handOff(workspaceId) { return this.call('handOff', { workspaceId }); }
145
+ closeWorkspace(workspaceId) { return this.call('closeWorkspace', { workspaceId }); }
146
+ close() { this.agent.destroy(); }
147
+ }
148
+
149
+ export async function localRequest(socket, credentials, endpoint, method, params, agent) {
150
+ const body = JSON.stringify({ method, params });
151
+ let token;
152
+ try {
153
+ token = (await readFile(credentials, 'utf8')).trim();
154
+ } catch {
155
+ throw unavailable();
156
+ }
157
+ if (!token) throw unavailable();
158
+ return new Promise((resolve, reject) => {
159
+ const req = request({
160
+ socketPath: socket,
161
+ method: 'POST',
162
+ path: endpoint,
163
+ headers: {
164
+ authorization: 'Bearer ' + token,
165
+ 'content-type': 'application/json',
166
+ 'content-length': Buffer.byteLength(body),
167
+ },
168
+ agent,
169
+ }, res => {
170
+ let data = '';
171
+ res.setEncoding('utf8');
172
+ res.on('data', chunk => { data += chunk; });
173
+ res.on('error', () => reject(unavailable()));
174
+ res.on('end', () => {
175
+ let reply;
176
+ try { reply = JSON.parse(data); } catch {}
177
+ if (typeof reply?.error?.code === 'string') {
178
+ reject(new OpenBrowserError(reply.error.code, reply.error.message || reply.error.code));
179
+ } else if (res.statusCode === 200 && reply && Object.hasOwn(reply, 'result')) {
180
+ resolve(reply.result);
181
+ } else {
182
+ reject(new OpenBrowserError('INVALID_RESPONSE', '本地服务返回了无法识别的响应。'));
183
+ }
184
+ });
185
+ });
186
+ req.once('error', () => reject(unavailable()));
187
+ req.setTimeout(limits.clientTimeoutMs, () => {
188
+ reject(new OpenBrowserError('REQUEST_TIMEOUT', '等待服务响应超时。对于已派发的动作,请按 operationId 查询回执。'));
189
+ req.destroy();
190
+ });
191
+ req.end(body);
192
+ });
193
+ }