@seekskyworld/open-browser 0.3.0 → 0.3.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 (82) hide show
  1. package/CONTRIBUTING.md +2 -0
  2. package/Docs/desktop-packages.md +45 -0
  3. 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 +1 -1
  4. package/README.md +8 -6
  5. package/README.zh-CN.md +2 -0
  6. package/api-contract.mjs +2 -1
  7. package/browser-extension/_locales/en/messages.json +8 -0
  8. package/browser-extension/_locales/zh_CN/messages.json +8 -0
  9. package/browser-extension/i18n.js +84 -0
  10. package/browser-extension/manifest.json +5 -4
  11. package/browser-extension/messages.js +266 -0
  12. package/browser-extension/newtab.css +4 -0
  13. package/browser-extension/newtab.html +9 -9
  14. package/browser-extension/newtab.js +38 -36
  15. package/browser-extension/page-locale.js +23 -0
  16. package/browser-extension/phase-labels.js +33 -6
  17. package/browser-extension/popup.css +2 -2
  18. package/browser-extension/popup.html +24 -26
  19. package/browser-extension/popup.js +72 -49
  20. package/browser-extension/tab-action.js +29 -24
  21. package/browser-extension/worker.js +29 -5
  22. package/browser-extension/workspace-title.js +2 -2
  23. package/build-profile.mjs +10 -2
  24. package/chromium-host.mjs +22 -11
  25. package/chromium-shell.mjs +5 -3
  26. package/cli.mjs +33 -30
  27. package/control.mjs +9 -8
  28. package/desktop/Info.plist +3 -1
  29. package/desktop/Launcher.m +10 -2
  30. package/desktop/OBControlBar.m +12 -8
  31. package/desktop/OBLocalization.h +20 -0
  32. package/desktop/OBPageView.m +2 -1
  33. package/desktop/WorkspacePanel.m +84 -83
  34. package/desktop/archive-release.py +5 -1
  35. package/desktop/build-macos.mjs +11 -5
  36. package/desktop/build-managed-input.mjs +2 -1
  37. package/desktop/build-portable.mjs +5 -3
  38. package/desktop/build-profile.mjs +2 -1
  39. package/desktop/build.mjs +2 -1
  40. package/desktop/create-shortcut.ps1 +7 -1
  41. package/desktop/en.lproj/Localizable.strings +106 -0
  42. package/desktop/install-menu-entry.mjs +2 -0
  43. package/desktop/notarize-macos.mjs +21 -24
  44. package/desktop/package-macos.mjs +4 -3
  45. package/desktop/sign.mjs +5 -4
  46. package/desktop/start-profile.mjs +2 -1
  47. package/desktop/start.mjs +3 -1
  48. package/desktop/verify-macos-release.mjs +9 -8
  49. package/desktop/zh-Hans.lproj/Localizable.strings +106 -0
  50. package/engine-service.mjs +1 -1
  51. package/hosted/cli.mjs +2 -1
  52. package/hosted/init.mjs +2 -1
  53. package/i18n.mjs +41 -0
  54. package/mcp-http.mjs +3 -2
  55. package/mcp-server.mjs +4 -3
  56. package/messages.zh-CN.mjs +175 -0
  57. package/package.json +4 -1
  58. package/page-activity.mjs +8 -6
  59. package/paths.mjs +2 -5
  60. package/runtime.mjs +4 -3
  61. package/sdk.mjs +40 -39
  62. package/service.mjs +2 -1
  63. package/skills/open-browser/SKILL.md +11 -9
  64. package/skills/open-browser/SKILL.zh-CN.md +22 -0
  65. package/skills/open-browser/references/macos.en.md +3 -0
  66. package/skills/open-browser/references/macos.md +2 -0
  67. package/skills/open-browser/references/operations.en.md +54 -0
  68. package/skills/open-browser/references/operations.md +2 -0
  69. package/skills/open-browser/references/recovery.en.md +36 -0
  70. package/skills/open-browser/references/recovery.md +2 -0
  71. package/skills/open-browser/references/windows.en.md +3 -0
  72. package/skills/open-browser/references/windows.md +2 -0
  73. package/skills/open-browser/scripts/bootstrap.mjs +6 -4
  74. package/skills/open-browser/scripts/guide.mjs +7 -4
  75. package/skills/open-browser/scripts/open-browser +5 -1
  76. package/studio/demo-site.mjs +5 -4
  77. package/studio/index.html +37 -33
  78. package/studio/index.mjs +10 -3
  79. package/studio/native-demo.mjs +8 -7
  80. package/studio/studio.css +3 -0
  81. package/studio/studio.js +98 -68
  82. package/system-i18n.mjs +19 -0
@@ -0,0 +1,54 @@
1
+ # Operations and permissions
2
+
3
+ ## Page ownership and input
4
+
5
+ In agent mode, the managed page blocks human pointer, touch and keyboard input. The service opens a short dispatch window for each agent action and locks the page again once it finishes. The address bar, tabs and workspace bar remain usable. Click **Take over** to edit the page and **Return to agent** to hand it back. Observe the page again after handoff.
6
+
7
+ Read `getWorkspace.security.inputGuard` for the active implementation. The `native` guard requires the patched Chromium build. The `fallback` guard implements the same handoff using a capture layer on the managed page. Set `OPEN_BROWSER_INPUT_GUARD=off` only when intentionally diagnosing the guard.
8
+
9
+ A single-tab grant covers the selected task and site. The original tab stays open at finish. Call `previewFinish` to inspect `keptPageIds` and `closedPageIds`, then pass the same selection and `previewId` to `finishWorkspace`. If the service reports `finish_preview_changed`, preview the current selection again.
10
+
11
+ The macOS desktop app groups task pages in native Chromium tab groups. Workspaces in the same application profile share sign-in state for the same site. Check the account shown on the page. Use the page handles belonging to the task. For a sign-in popup, find the child by `openerPageId` and `openedByOperationId`. Script workers follow the managed-page policy.
12
+
13
+ Supply `agentName` or set `OPEN_BROWSER_AGENT_NAME` to identify the creator. MCP uses the client's handshake title or name. CLI and SDK recognize a Codex session, otherwise they display CLI and SDK respectively. The service verifies access separately. To use distinct site accounts, set the same `OPEN_BROWSER_PROFILE` on each matching service and client. Each profile has its own Chromium data, service and receipts. Use `profileId` when creating a workspace to verify the selected profile, or use `new OpenBrowserClient({profileId:'work'})` to connect to that running instance. A paired client selects its token with `OPEN_BROWSER_CLIENT_TOKEN_FILE`. See the repository README for pairing, delegation and revocation.
14
+
15
+ ## Controls, waits and receipts
16
+
17
+ - Locate a control with `observe.locator`, for example `{"role":"button","name":"Save","within":{"role":"region","name":"Order B"}}`. Only `match.status:"unique"` returns an actionable ref. For multiple matches, inspect the containers in `match.candidates` and narrow the locator. A modal’s title and bounds appear in `foreground`. The actionable controls belong to that foreground.
18
+ - For `select`, use the combobox ref and an option value from the current observation. Controls can expose `checked`, `pressed`, `expanded` and `selected`. The first two can be `"mixed"`. Send `{"kind":"setChecked","ref":"…","checked":true}` to request a specific state and read it back from the observation or `delta.changed`.
19
+ - A wait can match visible `text`, a full `url`, or an `element:{role,name}` with expected control state. Use `absent:{role,name}` to wait for a control to disappear. Per-step `timeoutMs` is 1–10000 ms. The top-level operation budget is 1–60000 ms including queue time. Batch a click and its expected outcome. For navigation use `{"kind":"wait","navigation":"commit","timeoutMs":3000}` and check `navigation` for `document_committed`, `same_document` or `not_committed`. After a dispatched submission times out, check the site and receipt before retrying.
20
+ - Request `observeAfter:"full"` for an observation or `"delta"` for changed text and controls. A new document or baseline can yield a full observation. Observe again after a generation change or when reading a historical receipt. Use `includeFrames:true` for visible first-level frame text on approved origins. Use `frameControls:true` for `frames[].elements[].ref` and observe again if the frame reloads.
21
+ - If `truncated:true`, pass the returned `nextCursor` as `cursor` with the same page handle. Use `name` for substring matching, `region:{x,y,width,height}` for a viewport CSS-pixel region, and `limit` from 1 to 180. Restart observation after `stale_cursor`. For `target_obscured`, inspect the current obstacle and wait for it to clear before acting with a new operation ID. For `inspect_before_retry`, check the site outcome first.
22
+ - Use `capabilities` for the running service's methods and limits, and `--schema` for the CLI schema. `diagnoseOperation` accepts `workspaceId` and `operationId` and returns the completed step count, dispatch status, failure class and a next action. The workspace panel can export a redacted error log. For `check_site_result`, check the actual site result.
23
+
24
+ ## Canvases and pixels
25
+
26
+ `canvasSnapshot` reads rendered React Flow nodes and edges, marked-up chat messages and download labels. Compare `snapshotVersion` after an action. Content or control generation changes the version. If the adapter reports `unsupported`, use ordinary observations or authorized pixels.
27
+
28
+ Check `capabilities`. A task owner requests screenshot permission from the selected tab’s extension using **Allow screenshots for this task**. The user can revoke the grant there. For delegated clients, a local administrator grants pixel access to the workspace, principal and origin via `admin.setPixelPermission`.
29
+
30
+ Call `captureVisual` with the handle and an optional `region:{x,y,width,height}` or current control `ref`. The PNG starts at viewport CSS coordinates `clip.x,clip.y`. The `frameId` is single-use and expires in eight seconds. Pass the same document and control generation to `act`, for example `{"kind":"spatial","frameId":"FRAME_ID","action":{"type":"click","x":50,"y":50}}`. Other input types are hover, tap, drag (`toX/toY`), scroll (`deltaX/deltaY`), key (`keys`) and text (`text`). Forms and private regions are masked. Sign in using semantic refs. Recapture on `stale_visual_frame` and verify a site's outcome on `outcome_unknown`.
31
+
32
+ For continuously redrawing single-canvas games such as Godot, pass `liveCanvas:true` to `captureVisual`. Input must hit the same canvas. Keyboard input also requires it to have focus. Ordinary frames are checked for pixel changes.
33
+
34
+ ## Popups, dialogs, uploads and downloads
35
+
36
+ For a popup opened by a managed click on an approved HTTP(S) site, use `openedPageIds` in the receipt. For a delayed popup, inspect `getWorkspace` to identify the child opened by that operation.
37
+
38
+ Before an action, save `eventCursor.nextCursor`. Call `waitForEvent` with the page handle, `after`, `kind` (popup, download or dialog), optional `operationId` and `timeoutMs` of 1–10000. You can start waiting before clicking. A timeout returns `event:null` and the original cursor can be reused. On success, continue from `nextCursor`. The event’s `resourceId` identifies the child page, download or dialog. Omit the operation filter for an asynchronous download attributed only to a page. Read-only delegates can view events.
39
+
40
+ For a native dialog, check `getWorkspace.pendingDialogs` for page, operation, origin and type. With control of the page, use `respondDialog` with `workspaceId`, `pageId`, `dialogId`, `controlGeneration` and `accept`. Prompts also take `text`. Answer each dialog once. A user can take over and respond in the extension. Playwright cannot identify the initiating frame for these dialogs and the service cancels dialogs from multi-origin frame trees.
41
+
42
+ For an upload, the user selects a file in the extension after checking the page and origin. Retrieve the `fileId` with `listUploads`. Send `{"kind":"upload","ref":"CURRENT_PICKER_REF","fileId":"GRANTED_ID"}` with `act`. A grant permits one file of at most 8 MiB, scoped to the page, document, origin and control generation. It expires after five minutes and is consumed on dispatch to the site. Verify uncertain results before retrying.
43
+
44
+ Call `listDownloads` and distinguish files with the same name by `downloadId`. Cancelling requires workspace control. The user keeps desired files in the workspace panel before delivery. Use the path shown in the panel. `listOutputs` then returns local manifests. Read base64 chunks with `readOutput`, using `offset`, `limit` of up to 64 KiB and `nextOffset`. Outputs are retained for 24 hours by default. Manifests exclude credentials and page body text.
45
+
46
+ ## Site workflows, delivery and recovery
47
+
48
+ Adapt the [sign-in and export](../workflows/login-export.json) or [upload and verify](../workflows/upload-verify.json) template to the exact site origin, control roles, names and success criteria. Call `runWorkflow` with the page handle, current `documentId`, `controlGeneration`, unique `operationId`, `workflow` and run-specific `bindings`, e.g. `{"attachment":"GRANTED_FILE_ID"}` or `{"password":"BOUND_CREDENTIAL_REF"}`. Templates contain parameter names. The service observes and checks origin and control on each step. Check `getOperation` for completed steps on `target_ambiguous`, `target_missing` or `workflow_origin_changed`. For an export, also verify the download receipt.
49
+
50
+ Inspect `observe.blockedRequests` or `getWorkspace.blockedOrigins` for origin and resource type. Once in control, grant a recorded origin via `grantOrigin` using the latest `controlGeneration`, full `origin` and `scope`. The `resource` scope permits passive images, fonts, styles and media. The `navigation` scope permits documents and scripts. Observe again or rerun the original operation after granting access.
51
+
52
+ Call `finishWorkspace` with `workspaceId`, a unique `operationId` and `keepPageIds`. Selected pages become ordinary tabs. The other managed pages close. Retry with the same operation ID and page selection. Verify an `outcome_unknown` on the site. The user can also select tabs to keep in the workspace panel. Ordinary tabs opened outside the workspace need no cleanup.
53
+
54
+ Use `listOperations` and `listEvents` after completion. Page through events with `after`, `limit` and `nextCursor`. The default history retention period is seven days. Choose random operation IDs to keep account names, URLs and content out of history. After an interruption, use `getRecoverySummary`. Reobserve pages marked `observe`, check the site for `verify_site`, and recognize `already_completed` as a recorded completion. `handle_unavailable` means the old handle is invalid. Delivery receipts list kept tabs in `keptPageIds`, confirmed download IDs in `deliveries` and readable outputs in `outputs`. Page through receipts using `nextCursor` as `after`, and through objects using `nextObjectCursor` as `objectsAfter`.
@@ -57,3 +57,5 @@ Godot 等持续重绘且只有一个画布的游戏可在 captureVisual 中传 l
57
57
  - `diagnoseOperation` 接受 `workspaceId` 和 `operationId`,返回已完成步数、是否记录过派发、故障类别和建议处置。桌面工作区面板也可预览并保存同一份脱敏 JSON。结果为 `check_site_result` 时先用页面的业务结果核实是否生效。
58
58
 
59
59
  当 `observe` 返回 `blockedRequests` 或 `getWorkspace` 返回 `blockedOrigins` 时,先核对来源和资源类型。用户或 Agent 取得当前工作区控制权后,可用 `grantOrigin` 传入最新 `controlGeneration`、完整 `origin` 和 `scope`。`resource` 只放行图片、字体、样式和媒体,`navigation` 才允许文档和脚本等完整站点能力。授权后重新 `observe` 或重新执行原操作。
60
+
61
+ <!-- source-sha256: 2c1118716ddc6407fb44aeb6cdff07097fd5f8fe825a98172178f327872f76b6 -->
@@ -0,0 +1,36 @@
1
+ # Recover a page or read a CLI error
2
+
3
+ | Result | Next step |
4
+ | --- | --- |
5
+ | `mode:agent` with `pages:[]` | Inspect `pageAvailability`. Wait for `page_bound` on first assignment. Select the page again if it closed. |
6
+ | `sync_pending` | Retry `reattachPage` with the original workspace and page IDs. |
7
+ | `workspace_not_found` | Check the profile and calling client, then call `getRecoverySummary` with the original workspace ID. Read `closeReason`, the page dispositions and operation receipts. If the summary says `nextAction:request_tab_selection`, ask the user to select the tab again. Older records may report `unknown`. |
8
+ | `service_shutdown` | If the user opted in when assigning the tab, the service recorded its browser-issued identity. Following a normal exit or a forced termination, a valid record in the same profile can rebind the same restored Chromium tab for 24 hours. Call `reattachPage` with the original IDs. Follow the summary if the user took over, the tab was lost, its identity changed or a submission needs verification. |
9
+ | `page_not_found`, `origin_denied` | Check the selected tab and site with the user. Several tabs may share a URL. |
10
+ | `stale_document`, `stale_control`, `stale_ref` | Observe the original page again and use the current target. |
11
+ | `outcome_unknown`, timeout | Keep the operation ID. Check its receipt and the site’s result before deciding to retry. |
12
+ | `RESPONSE_LOST` | The service may already have processed the request. After creating a workspace, verify its name and page with `listWorkspaces`. Query `getOperation` when you have an operation ID. |
13
+ | `target_obscured` | Inspect `obstruction` in the receipt and the foreground dialog in the latest observation before clearing the obstruction. |
14
+ | `human_verification_required` | Use `handOff` for the user to complete site verification, then wait with `reattachPage`. |
15
+
16
+ Closing the host ends the current Chromium context. A restored tab has a new document and needs fresh control refs and visual frames. For manual authorization, the user can click **Generate backup authorization code**. Redeem it once with `adoptCurrentTab` within two minutes.
17
+
18
+ ## CLI errors
19
+
20
+ With `session`, read one `{id,result}` or `{id,error}` per line on stdout. With `--json <method>`, read `{result}` or `{error}` from stdout and check the exit status. The default single-call interface prints success to stdout and an error to stderr with a nonzero status. This wrapper accepts the absolute skill launcher path and preserves the original error code and launcher diagnostics.
21
+
22
+ ```python
23
+ import json
24
+ import subprocess
25
+
26
+ def call(launcher, method, params):
27
+ proc = subprocess.run([launcher, method], input=json.dumps(params),
28
+ text=True, capture_output=True)
29
+ if proc.returncode == 0:
30
+ return json.loads(proc.stdout)
31
+ try:
32
+ detail = json.loads(proc.stderr)["error"]
33
+ except (ValueError, KeyError, TypeError):
34
+ detail = {"code": "CLI_EXIT", "message": proc.stderr.strip()}
35
+ raise RuntimeError(proc.returncode, detail)
36
+ ```
@@ -34,3 +34,5 @@ def call(launcher, method, params):
34
34
  detail = {"code": "CLI_EXIT", "message": proc.stderr.strip()}
35
35
  raise RuntimeError(proc.returncode, detail)
36
36
  ```
37
+
38
+ <!-- source-sha256: 06ce7ba2e45127c0ff5d9f7cb3463b3d09a85a657c76ba95e4bb10fc5fbd3107 -->
@@ -0,0 +1,3 @@
1
+ ### Windows
2
+
3
+ Use `scripts/open-browser.cmd` in the skill. The portable distribution supplies its own Node runtime. To open the browser window, run `open-browser.cmd` in the extracted package.
@@ -1,3 +1,5 @@
1
1
  ### Windows
2
2
 
3
3
  在 Windows 便携版中,Skill 会使用 `scripts/open-browser.cmd` 和包内 Node。需要打开浏览器窗口时运行便携包中的 `open-browser.cmd`。
4
+
5
+ <!-- source-sha256: 59f6c581d9fc816b5c1f6d7e957837d60d7cb1d7c21b41f81cb08c1279f4ee67 -->
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import { locale, t } from '../../../i18n.mjs';
2
3
  import { readFile, realpath, stat } from 'node:fs/promises';
3
4
  import { spawn } from 'node:child_process';
4
5
  import { once } from 'node:events';
@@ -49,11 +50,12 @@ async function wakeExisting(root) {
49
50
 
50
51
  async function startLocalBrowser(root) {
51
52
  if (await wakeExisting(root)) return;
53
+ const language = process.env.OPEN_BROWSER_LOCALE ? ['--env', 'OPEN_BROWSER_LOCALE=' + locale] : [];
52
54
  const appBundle = process.platform === 'darwin' && path.basename(root) === 'app'
53
55
  ? path.resolve(root, '../../../')
54
56
  : undefined;
55
57
  if (appBundle?.endsWith('.app')) {
56
- return detached('open', ['-g', appBundle]);
58
+ return detached('open', ['-g', ...language, appBundle]);
57
59
  }
58
60
 
59
61
  const portableRoot = path.resolve(root, '..');
@@ -70,7 +72,7 @@ async function startLocalBrowser(root) {
70
72
  if (process.platform === 'darwin' && process.env.OPEN_BROWSER_USE_SOURCE !== '1' &&
71
73
  process.env.OPEN_BROWSER_BUILD_PROFILE !== 'dev') {
72
74
  for (const app of [path.join(root, 'dist/open-browser.app'), '/Applications/open-browser.app']) {
73
- if (await isFile(path.join(app, 'Contents/MacOS/open-browser'))) return detached('open', ['-g', app]);
75
+ if (await isFile(path.join(app, 'Contents/MacOS/open-browser'))) return detached('open', ['-g', ...language, app]);
74
76
  }
75
77
  }
76
78
  const service = path.join(root, 'service.mjs');
@@ -133,7 +135,7 @@ async function ensureService(root, start = startLocalBrowser, initialError) {
133
135
  }
134
136
  }
135
137
  } catch (cause) {
136
- if (signal.aborted) throw new OpenBrowserError('REQUEST_TIMEOUT', '等待本机服务就绪超时。');
138
+ if (signal.aborted) throw new OpenBrowserError('REQUEST_TIMEOUT', t("Timed out waiting for the local service to become ready."));
137
139
  throw cause;
138
140
  } finally {
139
141
  api.close();
@@ -174,7 +176,7 @@ async function main() {
174
176
  // Older desktop launchers provide their own package directory as argv[2].
175
177
  if (args[0] && path.isAbsolute(args[0]) && await realpath(args[0]).catch(() => null) === path.resolve(root)) args.shift();
176
178
  if (args[0] === 'skill') {
177
- if (args.length > 1) throw Object.assign(new Error('skill 不接受额外参数。'), { code: 'INVALID_PARAMS' });
179
+ if (args.length > 1) throw Object.assign(new Error(t("skill takes no additional arguments.")), { code: 'INVALID_PARAMS' });
178
180
  const { readSkillGuide } = await import('./guide.mjs');
179
181
  process.stdout.write(await readSkillGuide());
180
182
  return;
@@ -1,17 +1,20 @@
1
+ import { locale, t } from '../../../i18n.mjs';
1
2
  import { readFile } from 'node:fs/promises';
2
3
 
3
4
  export async function readSkillGuide(platform = process.platform) {
5
+ const chinese = locale === 'zh-CN';
6
+ const filename = chinese ? 'SKILL.zh-CN.md' : 'SKILL.md';
4
7
  let body;
5
8
  try {
6
- body = await readFile(new URL('../SKILL.md', import.meta.url), 'utf8');
9
+ body = await readFile(new URL('../' + filename, import.meta.url), 'utf8');
7
10
  } catch (cause) {
8
- throw Object.assign(new Error('未找到 skills/open-browser/SKILL.md。', {cause}), {code:'SKILL_GUIDE_NOT_FOUND'});
11
+ throw Object.assign(new Error(t("Could not find the open-browser skill guide."), {cause}), {code:'SKILL_GUIDE_NOT_FOUND'});
9
12
  }
10
13
  if (!body.endsWith('\n')) body += '\n';
11
14
  const label = {darwin:'macOS', win32:'Windows'}[platform];
12
15
  if (!label) return body;
13
- const supplement = await readFile(new URL(`../references/${label.toLowerCase()}.md`, import.meta.url), 'utf8')
16
+ const supplement = await readFile(new URL(`../references/${label.toLowerCase()}${chinese ? '' : '.en'}.md`, import.meta.url), 'utf8')
14
17
  .catch(error => { if (error.code !== 'ENOENT') throw error; });
15
18
  if (!supplement) return body;
16
- return `[open-browser:skill] open-browser usage guide (${label})\n\n${body}\n${supplement}`;
19
+ return `[open-browser:skill] ${t('Open Browser usage guide ({0})', label)}\n\n${body}\n${supplement}`;
17
20
  }
@@ -17,5 +17,9 @@ done
17
17
  if [ -f "$repo/cli.mjs" ]; then
18
18
  exec node "$repo/skills/open-browser/scripts/bootstrap.mjs" "$repo" "$@"
19
19
  fi
20
- printf '%s\n' '未找到 open-browser CLI。请在源码仓库中使用本 Skill,或将 open-browser.app 安装到 /Applications。' >&2
20
+ case "${OPEN_BROWSER_LOCALE:-${LC_ALL:-${LC_MESSAGES:-${LANG:-en}}}}" in
21
+ [zZ][hH]*) message='未找到 open-browser CLI。请从源码目录使用此 Skill,或将 open-browser.app 安装到 /Applications。' ;;
22
+ *) message='Open Browser CLI was not found. Use the skill from the source checkout or install open-browser.app in /Applications.' ;;
23
+ esac
24
+ printf '%s\n' "$message" >&2
21
25
  exit 1
@@ -1,3 +1,4 @@
1
+ import { locale, t } from '../i18n.mjs';
1
2
  import { createServer } from 'node:http';
2
3
  import { randomBytes, scryptSync, timingSafeEqual } from 'node:crypto';
3
4
  import { once } from 'node:events';
@@ -51,7 +52,7 @@ export async function serve(handler) {
51
52
  }
52
53
 
53
54
  function demoDocument(title, body) {
54
- return `<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${title} · open-browser</title><link rel="icon" type="image/png" href="/open-browser-icon.png"><link rel="stylesheet" href="/demo.css"><main class="login-shell"><header><img src="/open-browser-icon.png" width="28" height="28" alt=""><span>open-browser</span></header>${body}</main></html>`;
55
+ return `<!doctype html><html lang="${locale}"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${title} · open-browser</title><link rel="icon" type="image/png" href="/open-browser-icon.png"><link rel="stylesheet" href="/demo.css"><main class="login-shell"><header><img src="/open-browser-icon.png" width="28" height="28" alt=""><span>open-browser</span></header>${body}</main></html>`;
55
56
  }
56
57
 
57
58
  export async function startDemo() {
@@ -64,8 +65,8 @@ export async function startDemo() {
64
65
  const cookieName = 'open-browser-demo-' + randomBytes(5).toString('hex');
65
66
  const cookiePrefix = cookieName + '=';
66
67
  const cookieAttributes = '; HttpOnly; SameSite=Strict; Path=/';
67
- const form = '<form method="post" action="/login"><label for="username">账号</label><input name="username" id="username" autocomplete="username" required><label for="password">密码</label><input name="password" id="password" type="password" autocomplete="current-password" required><button type="submit">登录</button></form>';
68
- const viewLogin = invalid => demoDocument('登录', '<p class="kicker">本机验证站</p><h1>登录账号</h1>' + (invalid ? '<p role="alert">账号或密码不正确</p>' : '') + form);
68
+ const form = () => `<form method="post" action="/login"><label for="username">${t('Username')}</label><input name="username" id="username" autocomplete="username" required><label for="password">${t('Password')}</label><input name="password" id="password" type="password" autocomplete="current-password" required><button type="submit">${t('Sign in')}</button></form>`;
69
+ const viewLogin = invalid => demoDocument(t('Sign in'), `<p class="kicker">${t('Local test site')}</p><h1>${t('Sign in to your account')}</h1>` + (invalid ? `<p role="alert">${t('Incorrect username or password')}</p>` : '') + form());
69
70
  const site = await serve(async (req, res, origin) => {
70
71
  const token = (req.headers.cookie || '').split('; ').find(c => c.startsWith(cookiePrefix))?.slice(cookiePrefix.length);
71
72
  const signedIn = (sessions.get(token) || 0) > Date.now();
@@ -81,7 +82,7 @@ export async function startDemo() {
81
82
  }
82
83
  if (req.url === '/account') {
83
84
  if (!signedIn) return redirect('/login');
84
- const html = demoDocument('我的账号', '<p class="kicker">本机验证站</p><h1>我的账号</h1><p class="identity">当前账号 <strong>' + demoAccount.username + '</strong></p><form method="post" action="/logout"><button type="submit">退出登录</button></form>');
85
+ const html = demoDocument(t('My account'), `<p class="kicker">${t('Local test site')}</p><h1>${t('My account')}</h1><p class="identity">${t('Signed in as')} <strong>` + demoAccount.username + `</strong></p><form method="post" action="/logout"><button type="submit">${t('Sign out')}</button></form>`);
85
86
  return reply(res, 200, html, 'text/html; charset=utf-8', { 'Referrer-Policy': 'same-origin' });
86
87
  }
87
88
  }
package/studio/index.html CHANGED
@@ -1,66 +1,70 @@
1
1
  <!doctype html>
2
- <html lang="zh-CN">
2
+ <html lang="en">
3
3
  <head>
4
4
  <meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
5
- <title>open-browser · 工作区</title><link rel="icon" type="image/png" href="/open-browser-icon.png"><link rel="stylesheet" href="/studio.css">
5
+ <title data-i18n>Open Browser · Workspaces</title><link rel="icon" type="image/png" href="/open-browser-icon.png"><link rel="stylesheet" href="/studio.css">
6
6
  </head>
7
7
  <body>
8
8
  <div class="shell">
9
9
  <aside>
10
10
  <header class="brand"><img src="/open-browser-icon.png" width="28" height="28" alt="">open-browser</header>
11
- <div class="rail-title"><h2>工作区</h2><span id="count" class="count">0</span></div>
12
- <button id="show-new" class="new"><span aria-hidden="true">+</span> 新建工作区</button>
13
- <nav id="workspaces" aria-label="工作区列表"></nav><p id="rail-empty" class="rail-empty">暂无工作区</p>
14
- <div id="connection-status" class="connection"><i></i><span id="connection">正在连接</span></div>
11
+ <div class="studio-language"><label data-i18n for="interface-language">Language</label>
12
+ <select id="interface-language" disabled><option data-i18n value="system">Follow system</option><option value="zh-CN" lang="zh-CN">简体中文</option><option value="en" lang="en">English</option></select></div>
13
+ <div class="rail-title"><h2 data-i18n>Workspace</h2><span id="count" class="count">0</span></div>
14
+ <button data-i18n id="show-new" class="new"><span aria-hidden="true">+</span> New workspace</button>
15
+ <nav data-i18n-attrs="aria-label" id="workspaces" aria-label="Workspace list"></nav><p data-i18n id="rail-empty" class="rail-empty">No workspaces</p>
16
+ <div id="connection-status" class="connection"><i></i><span data-i18n id="connection">Connecting</span></div>
15
17
  </aside>
16
18
  <main>
17
19
  <div id="notice" role="status" hidden></div>
18
20
  <section id="new-view">
19
- <header class="section-head"><h1>新建工作区</h1><p>为任务打开独立的浏览器页面。</p></header>
21
+ <header class="section-head"><h1 data-i18n>New workspace</h1><p data-i18n>Open a separate browser page for a task.</p></header>
20
22
  <form id="new-form" class="panel editor">
21
- <div class="field"><label for="name">工作区名称</label><input id="name" value="我的工作区" maxlength="80" required></div>
22
- <div class="field"><label for="url">打开网址</label><input id="url" type="url" placeholder="https://example.com" required></div>
23
- <button class="primary">创建并打开 <span aria-hidden="true">↗</span></button>
23
+ <div class="field"><label data-i18n for="name">Workspace name</label><input data-i18n-attrs="value" id="name" value="My workspace" maxlength="80" required></div>
24
+ <div class="field"><label data-i18n for="url">URL to open</label><input id="url" type="url" placeholder="https://example.com" required></div>
25
+ <button data-i18n class="primary">Create and open <span aria-hidden="true">↗</span></button>
24
26
  </form>
25
27
  <div class="demo-block">
26
- <div class="demo-header"><span class="site-mark" aria-hidden="true">◎</span><div><h2>账号登录演示</h2><p>在本机验证站试用自动登录或补充密码。</p></div></div>
27
- <div class="buttons"><button id="demo">自动登录</button><button id="missing">测试缺少密码</button></div>
28
+ <div class="demo-header"><span class="site-mark" aria-hidden="true">◎</span><div><h2 data-i18n>Sign-in demo</h2><p data-i18n>Try automatic sign-in or supply a missing password on the local demo site.</p></div></div>
29
+ <div class="buttons"><button data-i18n id="demo">Automatic sign-in</button><button data-i18n id="missing">Test missing password</button></div>
28
30
  </div>
29
31
  </section>
30
32
  <section id="active-view" hidden>
31
33
  <header class="section-head active-head"><div><h1 id="workspace-name"></h1><p id="wid" class="mono subtle"></p></div>
32
- <div class="buttons"><button id="take" class="primary">接管页面</button><button id="view-controlled">查看接管页</button><button id="give" class="primary">交回 Agent</button></div>
34
+ <div class="buttons"><button data-i18n id="take" class="primary">Take over page</button><button data-i18n id="view-controlled">View controlled page</button><button data-i18n id="give" class="primary">Return to agent</button></div>
33
35
  </header>
34
36
  <section id="work-summary" class="summary">
35
- <div><h2>控制权</h2><strong id="mode"></strong></div>
36
- <div><h2>当前活动</h2><strong id="work-state"></strong></div>
37
- <div><h2>最近结果</h2><strong id="result-text"></strong></div>
37
+ <div><h2 data-i18n>Control</h2><strong id="mode"></strong></div>
38
+ <div><h2 data-i18n>Current activity</h2><strong id="work-state"></strong></div>
39
+ <div><h2 data-i18n>Latest result</h2><strong id="result-text"></strong></div>
38
40
  </section>
39
- <section id="credential-view" class="credential" hidden><h2 id="credential-title">需要补充凭据</h2>
40
- <dl class="meta"><dt>站点</dt><dd id="credential-origin"></dd><dt>凭据引用</dt><dd id="credential-ref"></dd></dl>
41
- <form id="credential-form"><label for="password" id="credential-label">凭据值</label><input id="password" type="password" required autocomplete="off">
42
- <div class="buttons"><button id="submit-credential" class="primary">绑定凭据</button><button type="button" id="insert-password">填入演示密码</button></div>
41
+ <section id="credential-view" class="credential" hidden><h2 data-i18n id="credential-title">Credential needed</h2>
42
+ <dl class="meta"><dt data-i18n>Site</dt><dd id="credential-origin"></dd><dt data-i18n>Credential reference</dt><dd id="credential-ref"></dd></dl>
43
+ <form id="credential-form"><label data-i18n for="password" id="credential-label">Credential value</label><input id="password" type="password" required autocomplete="off">
44
+ <div class="buttons"><button data-i18n id="submit-credential" class="primary">Bind credential</button><button data-i18n type="button" id="insert-password">Fill demo password</button></div>
43
45
  </form>
44
46
  </section>
45
47
  <section class="panel page-panel">
46
- <div class="section-title"><h2>工作区页面</h2><select id="pages" aria-label="当前页面"></select></div>
47
- <form id="page-form" class="nav-form"><label for="address">打开新页面</label><div><input type="url" id="address" placeholder="https://example.com" required><button>打开 ↗</button></div></form>
48
- <div class="section-title"><h3>页面观察</h3><span id="observed-at"></span></div>
49
- <pre id="snapshot">暂无观察结果</pre>
50
- <div class="buttons"><button id="observe">读取页面</button><button id="login-action" hidden>运行登录任务</button></div>
48
+ <div class="section-title"><h2 data-i18n>Workspace pages</h2><select data-i18n-attrs="aria-label" id="pages" aria-label="Current page"></select></div>
49
+ <form id="page-form" class="nav-form"><label data-i18n for="address">Open a new page</label><div><input type="url" id="address" placeholder="https://example.com" required><button data-i18n>Open ↗</button></div></form>
50
+ <div class="section-title"><h3 data-i18n>Page observation</h3><span id="observed-at"></span></div>
51
+ <pre data-i18n id="snapshot">No observation yet</pre>
52
+ <div class="buttons"><button data-i18n id="observe">Read page</button><button data-i18n id="login-action" hidden>Run sign-in task</button></div>
51
53
  </section>
52
- <details id="credential-settings"><summary>绑定站点凭据</summary>
54
+ <details id="credential-settings"><summary data-i18n>Bind site credentials</summary>
53
55
  <form id="bind-form" class="editor">
54
- <div class="field"><label for="bind-id">凭据引用</label><input id="bind-id" placeholder="account.password" maxlength="128" required></div>
55
- <div class="field"><label for="bind-value">值</label><input type="password" autocomplete="off" id="bind-value" required></div>
56
- <button>绑定到当前页面来源</button>
56
+ <div class="field"><label data-i18n for="bind-id">Credential reference</label><input id="bind-id" placeholder="account.password" maxlength="128" required></div>
57
+ <div class="field"><label data-i18n for="bind-value">Value</label><input type="password" autocomplete="off" id="bind-value" required></div>
58
+ <button data-i18n>Bind to this page's origin</button>
57
59
  </form>
58
60
  </details>
59
- <details id="demo-details" hidden><summary>演示账号</summary><dl class="meta"><dt>账号</dt><dd id="demo-user"></dd><dt>密码</dt><dd><button id="reveal" class="quiet">显示密码</button><span id="demo-secret" class="mono"></span></dd></dl></details>
60
- <button id="close-workspace" class="quiet danger">关闭工作区</button>
61
+ <details id="demo-details" hidden><summary data-i18n>Demo account</summary><dl class="meta"><dt data-i18n>Username</dt><dd id="demo-user"></dd><dt data-i18n>Password</dt><dd><button data-i18n id="reveal" class="quiet">Show password</button><span id="demo-secret" class="mono"></span></dd></dl></details>
62
+ <button data-i18n id="close-workspace" class="quiet danger">Close workspace</button>
61
63
  </section>
62
- <section class="activity"><div class="section-title"><h2>控制台操作记录</h2><span id="activity-count"></span></div><ol id="activity"><li class="empty">本次打开控制台后暂无操作</li></ol></section>
64
+ <section class="activity"><div class="section-title"><h2 data-i18n>Console activity</h2><span id="activity-count"></span></div><ol id="activity"><li data-i18n class="empty">No activity since the console opened</li></ol></section>
63
65
  </main>
64
66
  </div>
65
- <script src="/studio.js" defer></script>
67
+ <script defer src="/messages.js"></script>
68
+ <script defer src="/i18n.js"></script>
69
+ <script src="/studio.js" defer></script>
66
70
  </body></html>
package/studio/index.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import { interfaceLanguage, locale, setInterfaceLanguage } from '../i18n.mjs';
1
2
  import { readFile } from 'node:fs/promises';
2
3
  import { startDemo, randomToken, reply, json, readBody, serve } from './demo-site.mjs';
3
4
 
@@ -8,6 +9,8 @@ export async function startStudio({ call }) {
8
9
  ['/open-browser-icon.png', '../browser-extension/icons/open-browser-48.png', 'image/png'],
9
10
  ['/', 'index.html', 'text/html; charset=utf-8'],
10
11
  ['/studio.css', 'studio.css', 'text/css'],
12
+ ['/messages.js', '../browser-extension/messages.js', 'text/javascript; charset=utf-8'],
13
+ ['/i18n.js', '../browser-extension/i18n.js', 'text/javascript; charset=utf-8'],
11
14
  ['/studio.js', 'studio.js', 'text/javascript; charset=utf-8'],
12
15
  ]) resources[route] = [await readFile(new URL(name, import.meta.url)), type];
13
16
  const demo = await startDemo();
@@ -19,7 +22,7 @@ export async function startStudio({ call }) {
19
22
  site = await serve(async (req, res, origin) => {
20
23
  if (req.method === 'GET' && Object.hasOwn(resources, req.url)) {
21
24
  const [content, type] = resources[req.url];
22
- return reply(res, 200, content, type);
25
+ return reply(res, 200, req.url === '/' ? content.toString().replace('lang="en"', `lang="${locale}"`) : content, type);
23
26
  }
24
27
  if (req.method !== 'POST' || req.headers.origin !== origin ||
25
28
  req.headers['content-type'] !== 'application/json') return reply(res, 403, 'Forbidden');
@@ -30,12 +33,16 @@ export async function startStudio({ call }) {
30
33
  return json(res, 200, { access });
31
34
  }
32
35
  if (req.headers.authorization !== 'Bearer ' + access) return json(res, 403, { error: 'unauthorized' });
33
- if (req.url === '/config') return json(res, 200, { demoUrl, username: demo.demoAccount.username });
36
+ if (req.url === '/config') return json(res, 200, { demoUrl, username: demo.demoAccount.username, language: interfaceLanguage() });
37
+ if (req.url === '/language') {
38
+ const { preference } = JSON.parse(await readBody(req));
39
+ return json(res, 200, setInterfaceLanguage(preference));
40
+ }
34
41
  if (req.url === '/demo-password') return json(res, 200, { password: demo.demoAccount.password });
35
42
  if (req.url === '/call') {
36
43
  const { method, params = {} } = JSON.parse(await readBody(req));
37
44
  if (!methods.has(method)) return json(res, 400, { error: 'unknown_method' });
38
- try { return json(res, 200, { result: await call(method, params) }); }
45
+ try { return json(res, 200, { result: await call(method, params), language: interfaceLanguage() }); }
39
46
  catch (error) {
40
47
  return json(res, 400, { error: /^[a-z0-9_]+$/i.test(error.code || '') ? error.code : 'request_failed' });
41
48
  }
@@ -1,3 +1,4 @@
1
+ import { t } from "../i18n.mjs";
1
2
  import { randomUUID } from 'node:crypto';
2
3
  import { setTimeout as sleep } from 'node:timers/promises';
3
4
  import { startDemo } from './demo-site.mjs';
@@ -36,8 +37,8 @@ export function nativeDemo(call, { deliverResult = true } = {}) {
36
37
  active.add(page.pageId);
37
38
  try {
38
39
  const view = await call('observe', page);
39
- const authenticated = snap => snap.text.includes('我的账号') &&
40
- snap.elements.some(el => el.role === 'button' && el.name === '退出登录');
40
+ const authenticated = snap => snap.text.includes(t("My account")) &&
41
+ snap.elements.some(el => el.role === 'button' && el.name === t("Sign out"));
41
42
  if (authenticated(view)) return await complete(page,view.controlGeneration);
42
43
  const field = (role, name) => {
43
44
  const match = view.elements.find(el => el.role === role && el.name === name);
@@ -47,9 +48,9 @@ export function nativeDemo(call, { deliverResult = true } = {}) {
47
48
  const { documentId, controlGeneration } = view;
48
49
  const operationId = randomUUID();
49
50
  const actions = [
50
- { kind: 'fillCredential', ref: field('textbox', '账号'), credentialRef: 'demo.username' },
51
- { kind: 'fillCredential', ref: field('textbox', '密码'), credentialRef: 'demo.password' },
52
- { kind: 'click', ref: field('button', '登录') },
51
+ { kind: 'fillCredential', ref: field('textbox', t("Username")), credentialRef: 'demo.username' },
52
+ { kind: 'fillCredential', ref: field('textbox', t("Password")), credentialRef: 'demo.password' },
53
+ { kind: 'click', ref: field('button', t("Sign in")) },
53
54
  ];
54
55
  let receipt = await call('act', { ...page, documentId, controlGeneration, operationId, actions });
55
56
  const deadline = Date.now() + 35_000;
@@ -64,7 +65,7 @@ export function nativeDemo(call, { deliverResult = true } = {}) {
64
65
  }
65
66
  if (receipt.state !== 'completed') fail(receipt.error || receipt.state);
66
67
  const after = await call('observe', page);
67
- if (!authenticated(after)) fail(after.text.includes('账号或密码不正确') ? 'wrong_password' : 'account_page_unconfirmed');
68
+ if (!authenticated(after)) fail(after.text.includes(t("Incorrect username or password")) ? 'wrong_password' : 'account_page_unconfirmed');
68
69
  return await complete(page,after.controlGeneration);
69
70
  } finally { active.delete(page.pageId); }
70
71
  }
@@ -80,7 +81,7 @@ export function nativeDemo(call, { deliverResult = true } = {}) {
80
81
  await starting;
81
82
  if (closed) fail('service_stopped');
82
83
  const { workspaceId } = await call('createWorkspace', {
83
- name: withPassword ? '自动登录' : '凭据补充', agentName: '登录助手', allowedOrigins: [site.origin],
84
+ name: withPassword ? t("Automatic sign-in") : t("Supply a missing credential"), agentName: t("Sign-in assistant"), allowedOrigins: [site.origin],
84
85
  });
85
86
  let page;
86
87
  try {
package/studio/studio.css CHANGED
@@ -117,3 +117,6 @@ summary { cursor: pointer; font-weight: 560; }
117
117
  #work-summary { grid-template-columns: 1fr 1fr; }
118
118
  #work-summary > div:last-child { grid-column: span 2; border: 0; border-top: 1px solid var(--line); }
119
119
  }
120
+
121
+ .studio-language { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
122
+ .studio-language select { width: auto; font: inherit; }