@seekskyworld/open-browser 0.2.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.
- package/CONTRIBUTING.md +2 -0
- package/Docs/desktop-packages.md +45 -0
- package/Docs/open-browser-api.d.ts +13 -9
- 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 +6 -6
- package/README.md +11 -9
- package/README.zh-CN.md +6 -4
- package/access-registry.mjs +8 -3
- package/action-execution.mjs +30 -5
- package/api-contract.mjs +8 -7
- package/browser-extension/_locales/en/messages.json +8 -0
- package/browser-extension/_locales/zh_CN/messages.json +8 -0
- package/browser-extension/i18n.js +84 -0
- package/browser-extension/manifest.json +5 -4
- package/browser-extension/messages.js +266 -0
- package/browser-extension/newtab.css +4 -0
- package/browser-extension/newtab.html +9 -9
- package/browser-extension/newtab.js +38 -35
- package/browser-extension/page-locale.js +23 -0
- package/browser-extension/phase-labels.js +33 -6
- package/browser-extension/popup.css +2 -2
- package/browser-extension/popup.html +25 -25
- package/browser-extension/popup.js +102 -59
- package/browser-extension/tab-action.js +31 -25
- package/browser-extension/worker.js +31 -7
- package/browser-extension/workspace-title.js +2 -2
- package/build-profile.mjs +10 -2
- package/capability-matrix.mjs +1 -1
- package/chromium-host.mjs +26 -19
- package/chromium-shell.mjs +7 -5
- package/cli.mjs +51 -48
- package/contract-validation.mjs +1 -1
- package/control.mjs +9 -8
- package/desktop/Info.plist +4 -2
- package/desktop/Launcher.m +10 -2
- package/desktop/OBControlBar.m +12 -8
- package/desktop/OBLocalization.h +20 -0
- package/desktop/OBPageView.m +2 -1
- package/desktop/WorkspacePanel.m +85 -83
- package/desktop/archive-release.py +5 -1
- package/desktop/build-macos.mjs +17 -8
- package/desktop/build-managed-input.mjs +2 -1
- package/desktop/build-portable.mjs +5 -3
- package/desktop/build-profile.mjs +2 -1
- package/desktop/build.mjs +2 -1
- package/desktop/create-shortcut.ps1 +7 -1
- package/desktop/en.lproj/Localizable.strings +106 -0
- package/desktop/install-menu-entry.mjs +2 -0
- package/desktop/notarize-macos.mjs +70 -29
- package/desktop/package-macos.mjs +4 -3
- package/desktop/sign.mjs +22 -6
- package/desktop/start-profile.mjs +2 -1
- package/desktop/start.mjs +3 -1
- package/desktop/verify-macos-release.mjs +27 -18
- package/desktop/verify-version.mjs +22 -2
- package/desktop/zh-Hans.lproj/Localizable.strings +106 -0
- package/engine-service.mjs +86 -27
- package/hosted/cli.mjs +2 -1
- package/hosted/init.mjs +2 -1
- package/i18n.mjs +41 -0
- package/managed-input.mjs +22 -5
- package/mcp-http.mjs +12 -11
- package/mcp-server.mjs +27 -10
- package/mcp.mjs +1 -0
- package/messages.zh-CN.mjs +175 -0
- package/package.json +9 -5
- package/page-activity.mjs +10 -7
- package/page-observation.mjs +4 -1
- package/paths.mjs +2 -5
- package/receipt-store.mjs +17 -7
- package/runtime.mjs +5 -4
- package/sdk.mjs +57 -46
- package/service.mjs +38 -21
- package/skill-links.mjs +72 -18
- package/skills/open-browser/SKILL.md +10 -97
- package/skills/open-browser/SKILL.zh-CN.md +22 -0
- package/skills/open-browser/references/macos.en.md +3 -0
- package/skills/open-browser/references/macos.md +5 -0
- package/skills/open-browser/references/operations.en.md +54 -0
- package/skills/open-browser/{SKILL.windows.md → references/operations.md} +8 -59
- package/skills/open-browser/references/recovery.en.md +36 -0
- package/skills/open-browser/references/recovery.md +38 -0
- package/skills/open-browser/references/windows.en.md +3 -0
- package/skills/open-browser/references/windows.md +5 -0
- package/skills/open-browser/scripts/bootstrap.mjs +80 -90
- package/skills/open-browser/scripts/guide.mjs +20 -0
- package/skills/open-browser/scripts/open-browser +5 -1
- package/studio/demo-site.mjs +5 -4
- package/studio/index.html +37 -33
- package/studio/index.mjs +10 -3
- package/studio/native-demo.mjs +8 -7
- package/studio/studio.css +3 -0
- package/studio/studio.js +99 -69
- package/system-i18n.mjs +19 -0
- package/tab-adoption.mjs +9 -3
- package/tab-recovery.mjs +100 -0
- package/visual-page.mjs +17 -7
- package/workspace-lifecycle.mjs +18 -2
- package/workspace-state.mjs +57 -16
- package/skills/open-browser/SKILL.macos.md +0 -112
|
@@ -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`.
|
|
@@ -1,66 +1,20 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
---
|
|
4
|
-
name: open-browser
|
|
5
|
-
description: 用户要求用 open-browser 浏览、观察页面、操作工作区或验证登录时,通过 open-browser CLI 控制其独立 Chromium。
|
|
6
|
-
---
|
|
7
|
-
|
|
8
|
-
在 macOS 和 Linux 使用本 Skill 目录内的 `scripts/open-browser`,在 Windows 使用 `scripts/open-browser.cmd`。便携包中的 Skill 位于 `app/skills/open-browser/`,其启动脚本使用包内 Node。下文以 `$ob` 表示它的绝对路径。命令名是第一个参数,其余参数从标准输入读取 JSON,标准输出也是 JSON。运行 `"$ob" --help` 查看方法。首次调用会探测本机服务,必要时自动启动 open-browser 应用或便携包并等待就绪后重试一次。设置 `OPEN_BROWSER_AUTOSTART=0` 可关闭自动启动。该引导只使用本机 socket 或命名管道,不需要配置 MCP 地址。连续任务可运行 `"$ob" session`,它按行读取 `{\"id\":1,\"method\":\"observe\",\"params\":{...}}`,复用同一个 Node 客户端直到标准输入关闭。
|
|
1
|
+
# 操作与授权
|
|
9
2
|
|
|
10
3
|
## Agent 控制时的输入保护
|
|
11
4
|
|
|
12
|
-
工作区进入 `agent`
|
|
13
|
-
|
|
14
|
-
`getWorkspace.security.inputGuard` 会报告 `native` 或 `fallback`。没有 Chromium 输入补丁时使用受管页面捕获层。发行包默认启用保护,只有明确设置 `OPEN_BROWSER_INPUT_GUARD=off` 才关闭。
|
|
5
|
+
工作区进入 `agent` 状态后,受管页面的内容区域会强制锁定人工鼠标、触控板和键盘输入。Agent 的每个写入动作在服务端打开一次短暂的派发窗口,动作结束后立即重新锁定。地址栏、标签栏和工作区控制条仍可使用。页面底部的 **人工接管** 是唯一的人工输入入口,接管完成后页面会显示 **交回 Agent**。
|
|
15
6
|
|
|
16
|
-
|
|
7
|
+
`getWorkspace` 的 `security.inputGuard` 会报告 `native` 或 `fallback`。`native` 使用带有 open-browser 输入补丁的 Chromium,`fallback` 使用受管页面的捕获层并保持相同的接管状态机。没有该补丁的 Dev 构建可启用 `fallback`。只有明确设置 `OPEN_BROWSER_INPUT_GUARD=off` 才会关闭保护,适合诊断场景。Agent 操作期间不要继续使用旧的人工输入结果,交回后先重新 `observe`。
|
|
17
8
|
|
|
18
|
-
| 场景 | 调用顺序 |
|
|
19
|
-
| --- | --- |
|
|
20
|
-
| 已登录的 open-browser 普通标签页 | 先用 `createWorkspace` 建立命名任务。请用户在原页打开扩展,选择该任务,点击「让 Agent 操作此页」,将授权框内的 JSON 交给你。在两分钟内原样传给 `adoptCurrentTab`,再用返回的句柄 `observe`。 |
|
|
21
|
-
| 新开页面 | 用 `open` 传任务名和 URL,再 `observe`。 |
|
|
22
|
-
| 用户接管后交回 | 用保存的 workspaceId 和 pageId 调用 `reattachPage`,可传 `waitMs:30000` 等待用户点击「交回 Agent」,交回后自动核对原页并返回新的观察。原页已关闭时请用户重新选择。 |
|
|
23
|
-
| 登录资料或服务发生变化 | 核对工作区的 `profileId`、站点和用户填写的账号别名。服务重启后用 `getRecoverySummary` 查看历史,再请用户在正确资料内重新授权。 |
|
|
24
9
|
|
|
25
10
|
单页授权绑定当前任务和站点。任务结束时原页自动保留。用 `previewFinish` 核对 `keptPageIds` 和 `closedPageIds`,将返回的 `previewId` 及原选择传入 `finishWorkspace`。遇到 `finish_preview_changed` 时重新预览。
|
|
26
11
|
|
|
27
12
|
对于 React Flow 画布或带消息角色标记的聊天区,`canvasSnapshot` 返回已渲染的节点、边、消息和下载链接标签。操作后可再读一次核对结果,`snapshotVersion` 随快照内容或控制代次变化。返回 `unsupported` 时使用普通观察或已授权的画面。
|
|
28
13
|
|
|
29
|
-
## 最短路径
|
|
30
|
-
|
|
31
|
-
一次性打开并读取页面时,优先使用 `open`,它会创建工作区、打开明确网址并返回页面句柄。随后把句柄传给 `observe`,再把最新观察中的 `documentId` 和 `controlGeneration` 传给 `act`。任务完成后调用 `finishWorkspace`,将需要交付的页面放进 `keepPageIds`。
|
|
32
|
-
|
|
33
|
-
```sh
|
|
34
|
-
ob="$PWD/skills/open-browser/scripts/open-browser"
|
|
35
|
-
page=$(printf '%s\n' '{"url":"https://example.org","name":"页面检查"}' | "$ob" open)
|
|
36
|
-
printf '%s\n' "$page"
|
|
37
|
-
# 从上一个 JSON 结果取 workspaceId 和 pageId,再执行 observe
|
|
38
|
-
printf '%s\n' '{"workspaceId":"WORKSPACE_ID","pageId":"PAGE_ID"}' | "$ob" observe
|
|
39
|
-
```
|
|
40
|
-
|
|
41
|
-
多步骤任务使用 `createWorkspace` 和 `openPage`,因为它们允许你明确设置 `allowedOrigins` 与 `resourceOrigins`。调用 `capabilities` 可先查看当前服务版本、限额、隐私模式及可用视觉动作。
|
|
42
|
-
|
|
43
|
-
遇到错误时按返回的 `code` 和 `nextAction` 处理。`stale_ref`、`stale_document`、`stale_control` 和 `stale_observation` 先重新 `observe`。`target_ambiguous` 用 `observe.locator` 缩小范围。`target_obscured` 等待遮罩消失后用新的操作号重试。`origin_denied` 先核对 `blockedOrigins`,取得工作区控制权后再用 `grantOrigin`。`human_verification_required` 表示站点要求安全验证,停止重试,调用 `handOff`,让用户在可见页面完成验证后再调用 `returnToAgent` 并重新 `observe`。`REQUEST_TIMEOUT`、`run_timeout`、`outcome_unknown` 或 `inspect_before_retry` 先用同一个 `operationId` 查询回执并核对站点结果。
|
|
44
|
-
|
|
45
|
-
若只使用 SDK,可用 `openAndObserve` 省去首次句柄拼接,用 `observeAndAct` 或 `actAfterObserve` 在一次服务请求中完成最新观察和动作提交,用 `finish` 自动生成交付操作号。这些辅助方法仍执行服务端的工作区权限、来源和过期引用检查。连续任务优先复用同一个 SDK 客户端,避免每个动作重新启动 CLI。
|
|
46
|
-
|
|
47
|
-
1. 运行 `"$ob" listWorkspaces </dev/null`。继续已有任务时使用该任务的工作区。新任务通过 `createWorkspace` 创建,必须填写清晰的 `name` 任务名称,并保存返回的 `workspaceId`。`name` 填任务名称,`agentName` 填创建者的显示名(最多 80 个 Unicode 码点)。多个子代理并行时,每个子代理须显式传自己的名字。同一客户端的子代理通常共享环境或 MCP 握手,只能由子代理自身区分身份。
|
|
48
|
-
2. 调用 `openPage`,传入 `workspaceId` 和目标 `url`,保存返回的页面句柄。把完整句柄传给 `observe`,读取可见文本、元素的 `role/name/ref`、`documentId` 和 `controlGeneration`。
|
|
49
|
-
3. 调用 `act`,把页面句柄、刚取得的两个代次标识、唯一 `operationId` 和有序的 `actions` 放入同一个 JSON 对象。例如动作可为 `{"kind":"fill","ref":"实际输入框引用","value":"待填写的普通文本"}` 和 `{"kind":"click","ref":"实际按钮引用"}`。相同控件在连续观察中保留引用。节点被移除或替换后,收到 `stale_ref` 时重新观察并核对目标。可见标签返回 `role:"label"` 时用 `click` 勾选关联控件。密码使用 `fillCredential` 和当前工作区、站点已绑定的 `credentialRef`。
|
|
50
|
-
4. 对 `queued` 或 `running` 回执,使用同一个 `operationId` 和 `workspaceId` 调用 `getOperation`,直至终态。再次 `observe` 核对页面业务结果。若结果为 `outcome_unknown`,先核对页面;导航或用户交回控制权后,重新观察再构造新动作。
|
|
51
|
-
5. 已有会话或凭据可用时自动继续;缺少凭据时只提示缺少的引用,用户在浏览器工具栏的 **open-browser 工作区** 扩展中核对站点并点 **绑定凭据** 后继续。需要用户操作时用 `handOff`。在 macOS 桌面应用中,用户可点击受管页面底部的「人工接管」和「交回 Agent」。工具栏也可切换控制权;缺凭据时可从弹出的面板接管。接管覆盖整个工作区,用户点 **交回 Agent** 后重新观察。整项任务完成后,Agent 在向用户报告前调用 `finishWorkspace`,将结果页放入 `keepPageIds`;没有要交付的页面时传空数组。一次动作完成后仍需继续任务时沿用原工作区。
|
|
52
|
-
|
|
53
14
|
macOS 桌面版把任务页面放进 Chromium 原生标签组。新建工作区仍共享应用专用 profile 内同站点的登录态,判断当前账号时请以页面实际显示为准。仅操作任务返回的页面句柄。登录流程打开新窗口时,从工作区页面清单按 openerPageId 和 openedByOperationId 找到对应子页。脚本工作线程受受管页策略约束。
|
|
54
15
|
|
|
55
16
|
省略 `agentName` 时可通过 `OPEN_BROWSER_AGENT_NAME` 配置默认名称。MCP 优先读取握手中的客户端标题,再读取名称。CLI 和 SDK 在已知 Codex 会话环境下显示 Codex,其他情况下分别显示 CLI 和 SDK。显示名称用于识别工作区创建者,访问权限由本机服务验证。
|
|
56
17
|
|
|
57
|
-
在项目根目录创建试用工作区可运行以下命令。
|
|
58
|
-
|
|
59
|
-
```sh
|
|
60
|
-
ob="$PWD/skills/open-browser/scripts/open-browser"
|
|
61
|
-
printf '%s\n' '{"name":"CLI 试用","agentName":"页面核验助手"}' | "$ob" createWorkspace
|
|
62
|
-
```
|
|
63
|
-
|
|
64
18
|
需要同时使用两个账号时,先给服务和调用端设置相同的 `OPEN_BROWSER_PROFILE`。每个 profile 使用自己的 Chromium 登录资料、本机服务和回执;同一 profile 的工作区仍共享站点账号。已配对的客户端通过 `OPEN_BROWSER_CLIENT_TOKEN_FILE` 选择自己的令牌。管理者可从本机 CLI 签发、委托和撤销权限,详见仓库 README。
|
|
65
19
|
|
|
66
20
|
- `act` 支持 `select` 和 `wait`。选择项使用最近观察中 combobox 的 ref 和选项 value。等待条件任选可见文本 `text`、完整页面地址 `url` 或可见元素 `element:{role,name}`,动作等待的 `timeoutMs` 为 1 到 10000。动作请求还可传顶层 `timeoutMs`,它是覆盖排队和执行的 1 到 60000 毫秒 wall budget。提交后等结果页的条件可与点击放在一批。用操作回执和网站结果共同核对业务完成。
|
|
@@ -71,7 +25,9 @@ printf '%s\n' '{"name":"CLI 试用","agentName":"页面核验助手"}' | "$ob" c
|
|
|
71
25
|
- 交付调用 `finishWorkspace`,传 `workspaceId`、唯一 `operationId` 及 `keepPageIds` 数组。保留的页面脱离任务,未选中的受管页关闭。重试沿用同一操作 ID 和同一页集合;收到 `outcome_unknown` 时先核实页面。用户也可从工作区面板选择保留页。新打开的普通标签无需清理。
|
|
72
26
|
- `listOperations` 查询结束的工作区回执;`listEvents` 使用 `after`、`limit` 续读。事件序号从响应的 `nextCursor` 取得。默认保留 7 天。使用随机操作 ID,避免把账号、URL 或正文写入 ID。
|
|
73
27
|
|
|
74
|
-
|
|
28
|
+
Godot 等持续重绘且只有一个画布的游戏可在 captureVisual 中传 liveCanvas:true。此帧只接受命中同一画布的输入,键盘操作还要求画布已获得焦点。普通截图仍核对像素是否变化。
|
|
29
|
+
|
|
30
|
+
画布、拖拽或触摸操作先运行 `capabilities`。具有页面像素权限时,调用 `captureVisual`,传页面句柄及可选的 `region:{x,y,width,height}` 或最新元素 `ref`。PNG 的左上角对应返回的 `clip.x,clip.y`,坐标均为视口 CSS 像素。返回的 `frameId` 有效 8 秒,可用一次。通过 `act` 传同一帧的文档和控制代次,以及 `{"kind":"spatial","frameId":"<帧 ID>","action":{"type":"click","x":50,"y":50}}`。可用类型包括 click、hover、tap、drag(toX/toY)、scroll(deltaX/deltaY)、key(keys)和 text(text)。表单控件及私有区域已遮盖,登录继续使用语义引用。遇到 `stale_visual_frame` 时重新截图;若操作回执为 `outcome_unknown`,先核对业务结果。工作区所有者可请用户在所选页面的扩展内点击「允许本任务截图」,核对任务和站点,也可在同处撤销。委托调用方的像素权限由本机管理员通过 `admin.setPixelPermission` 授予到指定工作区、调用方及来源。
|
|
75
31
|
|
|
76
32
|
### 长页面、弹窗和下载
|
|
77
33
|
|
|
@@ -93,20 +49,13 @@ printf '%s\n' '{"name":"CLI 试用","agentName":"页面核验助手"}' | "$ob" c
|
|
|
93
49
|
|
|
94
50
|
### 按网站运行流程
|
|
95
51
|
|
|
96
|
-
将 [登录后导出](workflows/login-export.json) 或 [上传后核对](workflows/upload-verify.json) 保存为本地模板,按实际站点填写精确的 `origin`、控件角色、名称和成功条件。调用 `runWorkflow` 时传页面句柄、最新 `documentId`、`controlGeneration`、唯一 `operationId`、模板对象 `workflow`,以及本次运行的 `bindings`。例如 `{"attachment":"已授权 fileId"}` 或 `{"password":"已绑定 credentialRef"}`。模板仅保存参数名,每次运行时提供授权引用。服务端逐步重新观察、核对来源和控制权。
|
|
52
|
+
将 [登录后导出](../workflows/login-export.json) 或 [上传后核对](../workflows/upload-verify.json) 保存为本地模板,按实际站点填写精确的 `origin`、控件角色、名称和成功条件。调用 `runWorkflow` 时传页面句柄、最新 `documentId`、`controlGeneration`、唯一 `operationId`、模板对象 `workflow`,以及本次运行的 `bindings`。例如 `{"attachment":"已授权 fileId"}` 或 `{"password":"已绑定 credentialRef"}`。模板仅保存参数名,每次运行时提供授权引用。服务端逐步重新观察、核对来源和控制权。
|
|
97
53
|
|
|
98
54
|
用 `getOperation` 查看已完成步数。遇到 `target_ambiguous`、`target_missing` 或 `workflow_origin_changed` 时核对页面和已执行步骤。登录后导出还应读取当前工作区的下载回执,核对交付物。
|
|
99
55
|
|
|
100
56
|
- 使用 `capabilities` 确认服务提供的方法和限额,`--schema` 输出当前 CLI 的全部方法和参数。遇到不支持的方法时以服务端返回的能力为准。
|
|
101
57
|
- `diagnoseOperation` 接受 `workspaceId` 和 `operationId`,返回已完成步数、是否记录过派发、故障类别和建议处置。桌面工作区面板也可预览并保存同一份脱敏 JSON。结果为 `check_site_result` 时先用页面的业务结果核实是否生效。
|
|
102
58
|
|
|
103
|
-
单页快捷入口
|
|
104
|
-
|
|
105
|
-
只需打开一个明确网址时,可直接调用 `open`,它会创建工作区并返回页面句柄。需要继续在同一任务中打开页面时,再按上面的 `createWorkspace` 和 `openPage` 流程操作。
|
|
106
|
-
|
|
107
59
|
当 `observe` 返回 `blockedRequests` 或 `getWorkspace` 返回 `blockedOrigins` 时,先核对来源和资源类型。用户或 Agent 取得当前工作区控制权后,可用 `grantOrigin` 传入最新 `controlGeneration`、完整 `origin` 和 `scope`。`resource` 只放行图片、字体、样式和媒体,`navigation` 才允许文档和脚本等完整站点能力。授权后重新 `observe` 或重新执行原操作。
|
|
108
60
|
|
|
109
|
-
|
|
110
|
-
### Windows
|
|
111
|
-
|
|
112
|
-
在 Windows 便携版中,Skill 会使用 `scripts/open-browser.cmd` 和包内 Node。需要打开浏览器窗口时运行便携包中的 `open-browser.cmd`。
|
|
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
|
+
```
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# 恢复页面与读取错误
|
|
2
|
+
|
|
3
|
+
| 返回 | 下一步 |
|
|
4
|
+
| --- | --- |
|
|
5
|
+
| `mode:agent` 且 `pages:[]` | 查看 `pageAvailability`。首次绑定时等待 `page_bound`,已关闭的页需要重新选择。 |
|
|
6
|
+
| `sync_pending` | 用原工作区和页面调用 `reattachPage` 重试同步。 |
|
|
7
|
+
| `workspace_not_found` | 核对 profile 和调用方,用原工作区 ID 调用 `getRecoverySummary`。读取 `closeReason`、页面处置和动作回执。历史记录没有可用绑定时,按 `nextAction:request_tab_selection` 请用户重新选页。旧记录可能返回 `unknown`。 |
|
|
8
|
+
| `service_shutdown` | 用户交付标签时可勾选重启恢复。服务在授权时记录浏览器生成的页面身份。正常退出或服务进程被强制终止后,原资料中的有效记录可在 24 小时内重新绑定 Chromium 恢复的同一标签。用原工作区和页面调用 `reattachPage` 取得新观察。人工接管、原标签未恢复、页面身份变化或提交仍待核实时,请按恢复摘要重新选页。 |
|
|
9
|
+
| `page_not_found`、`origin_denied` | 核对用户实际选中的标签和站点。恢复时按用户选择绑定,同一地址可能有多个标签。 |
|
|
10
|
+
| `stale_document`、`stale_control`、`stale_ref` | 对原页重新观察,核对控件再提交。 |
|
|
11
|
+
| `outcome_unknown`、请求超时 | 保留原 operationId,查询动作回执,核对站点结果后再决定是否重试。 |
|
|
12
|
+
| `RESPONSE_LOST` | 请求已发出,服务可能已执行。创建任务后用 `listWorkspaces` 核对名称和页面。有 operationId 时用 `getOperation` 核对回执。 |
|
|
13
|
+
| `target_obscured` | 查看回执的 obstruction 和观察中的前景弹窗,核对后再处理遮挡。 |
|
|
14
|
+
| `human_verification_required` | 用 `handOff` 请用户处理站点验证,用 `reattachPage` 等待交回。 |
|
|
15
|
+
|
|
16
|
+
宿主进程关闭会结束当前 Chromium 上下文。恢复标签会得到新文档,旧控件引用和一次性视觉帧随之失效。备用授权流程由用户点击「生成备用授权码」,然后调用 `adoptCurrentTab` 兑换,一次有效,期限两分钟。
|
|
17
|
+
|
|
18
|
+
## CLI 错误
|
|
19
|
+
|
|
20
|
+
连续调用使用 `session`,每行 stdout 按请求 id 返回 `{id,result}` 或 `{id,error}`。单次脚本调用可用 `--json <方法>`,统一从 stdout 读取 `{result}` 或 `{error}` 并检查退出码。兼容旧版时,单次 CLI 成功时在 stdout 返回结果,失败时以非零状态退出,并在 stderr 返回错误。下面的 Python 函数接收 Skill 启动器的绝对路径,保留错误码和原始启动错误。
|
|
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
|
+
```
|
|
37
|
+
|
|
38
|
+
<!-- source-sha256: 06ce7ba2e45127c0ff5d9f7cb3463b3d09a85a657c76ba95e4bb10fc5fbd3107 -->
|
|
@@ -1,17 +1,16 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
2
|
+
import { locale, t } from '../../../i18n.mjs';
|
|
3
|
+
import { readFile, realpath, stat } from 'node:fs/promises';
|
|
3
4
|
import { spawn } from 'node:child_process';
|
|
5
|
+
import { once } from 'node:events';
|
|
4
6
|
import net from 'node:net';
|
|
7
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
5
8
|
import path from 'node:path';
|
|
6
|
-
import { pathToFileURL } from 'node:url';
|
|
9
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
7
10
|
|
|
8
11
|
const defaultWaitMs = 10_000;
|
|
9
12
|
const retryDelayMs = 150;
|
|
10
13
|
|
|
11
|
-
function sleep(ms) {
|
|
12
|
-
return new Promise(resolve => setTimeout(resolve, ms));
|
|
13
|
-
}
|
|
14
|
-
|
|
15
14
|
function parseErrorCode(stderr) {
|
|
16
15
|
try {
|
|
17
16
|
const response = JSON.parse(stderr.trim());
|
|
@@ -21,17 +20,13 @@ function parseErrorCode(stderr) {
|
|
|
21
20
|
}
|
|
22
21
|
}
|
|
23
22
|
|
|
24
|
-
async function
|
|
25
|
-
|
|
26
|
-
await access(file);
|
|
27
|
-
return true;
|
|
28
|
-
} catch {
|
|
29
|
-
return false;
|
|
30
|
-
}
|
|
23
|
+
async function isFile(file) {
|
|
24
|
+
return stat(file).then(entry => entry.isFile(), () => false);
|
|
31
25
|
}
|
|
32
26
|
|
|
33
|
-
function detached(command, args, options = {}) {
|
|
27
|
+
async function detached(command, args, options = {}) {
|
|
34
28
|
const child = spawn(command, args, { ...options, detached: true, stdio: 'ignore' });
|
|
29
|
+
await once(child, 'spawn');
|
|
35
30
|
child.unref();
|
|
36
31
|
}
|
|
37
32
|
|
|
@@ -43,6 +38,7 @@ async function wakeExisting(root) {
|
|
|
43
38
|
process.kill(pid, 0);
|
|
44
39
|
const active = await new Promise(resolve => {
|
|
45
40
|
const probe = net.connect(socketPath);
|
|
41
|
+
probe.setTimeout(1000, () => { probe.destroy(); resolve(false); });
|
|
46
42
|
probe.once('connect', () => { probe.destroy(); resolve(true); });
|
|
47
43
|
probe.once('error', () => resolve(false));
|
|
48
44
|
});
|
|
@@ -54,39 +50,40 @@ async function wakeExisting(root) {
|
|
|
54
50
|
|
|
55
51
|
async function startLocalBrowser(root) {
|
|
56
52
|
if (await wakeExisting(root)) return;
|
|
53
|
+
const language = process.env.OPEN_BROWSER_LOCALE ? ['--env', 'OPEN_BROWSER_LOCALE=' + locale] : [];
|
|
57
54
|
const appBundle = process.platform === 'darwin' && path.basename(root) === 'app'
|
|
58
55
|
? path.resolve(root, '../../../')
|
|
59
56
|
: undefined;
|
|
60
57
|
if (appBundle?.endsWith('.app')) {
|
|
61
|
-
detached('open', ['-g', appBundle]);
|
|
62
|
-
return;
|
|
58
|
+
return detached('open', ['-g', ...language, appBundle]);
|
|
63
59
|
}
|
|
64
60
|
|
|
65
61
|
const portableRoot = path.resolve(root, '..');
|
|
66
62
|
const portableLauncher = process.platform === 'win32'
|
|
67
63
|
? path.join(portableRoot, 'open-browser.cmd')
|
|
68
64
|
: path.join(portableRoot, 'open-browser');
|
|
69
|
-
if (await
|
|
65
|
+
if (await isFile(portableLauncher)) {
|
|
70
66
|
if (process.platform === 'win32') {
|
|
71
|
-
detached(process.env.ComSpec || 'cmd.exe', ['/d', '/s', '/c', `"${portableLauncher}"`], { cwd: portableRoot });
|
|
72
|
-
} else {
|
|
73
|
-
detached(portableLauncher, [], { cwd: portableRoot });
|
|
67
|
+
return detached(process.env.ComSpec || 'cmd.exe', ['/d', '/s', '/c', `"${portableLauncher}"`], { cwd: portableRoot });
|
|
74
68
|
}
|
|
75
|
-
return;
|
|
69
|
+
return detached(portableLauncher, [], { cwd: portableRoot });
|
|
76
70
|
}
|
|
77
71
|
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
72
|
+
if (process.platform === 'darwin' && process.env.OPEN_BROWSER_USE_SOURCE !== '1' &&
|
|
73
|
+
process.env.OPEN_BROWSER_BUILD_PROFILE !== 'dev') {
|
|
74
|
+
for (const app of [path.join(root, 'dist/open-browser.app'), '/Applications/open-browser.app']) {
|
|
75
|
+
if (await isFile(path.join(app, 'Contents/MacOS/open-browser'))) return detached('open', ['-g', ...language, app]);
|
|
76
|
+
}
|
|
82
77
|
}
|
|
78
|
+
const service = path.join(root, 'service.mjs');
|
|
79
|
+
if (await isFile(service)) return detached(process.execPath, [service, '--chromium'], { cwd: root });
|
|
83
80
|
|
|
84
81
|
throw new Error('OPEN_BROWSER_APP_NOT_FOUND');
|
|
85
82
|
}
|
|
86
83
|
|
|
87
84
|
function waitLimit() {
|
|
88
85
|
const value = Number(process.env.OPEN_BROWSER_AUTOSTART_TIMEOUT_MS ?? defaultWaitMs);
|
|
89
|
-
return Number.isFinite(value) ? Math.max(1_000, Math.min(30_000, value)) : defaultWaitMs;
|
|
86
|
+
return Number.isFinite(value) ? Math.max(1_000, Math.min(30_000, Math.trunc(value))) : defaultWaitMs;
|
|
90
87
|
}
|
|
91
88
|
|
|
92
89
|
async function run(node, root, args, input) {
|
|
@@ -110,89 +107,82 @@ async function run(node, root, args, input) {
|
|
|
110
107
|
});
|
|
111
108
|
}
|
|
112
109
|
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
110
|
+
// Only readiness is polled. One SDK client and one deadline cover every probe.
|
|
111
|
+
async function ensureService(root, start = startLocalBrowser, initialError) {
|
|
112
|
+
const { OpenBrowserClient, OpenBrowserError } = await import(pathToFileURL(path.join(root, 'sdk.mjs')).href);
|
|
113
|
+
const api = new OpenBrowserClient();
|
|
114
|
+
const signal = AbortSignal.timeout(waitLimit());
|
|
115
|
+
let error = initialError;
|
|
116
|
+
let launched = false;
|
|
117
|
+
try {
|
|
118
|
+
for (;;) {
|
|
119
|
+
if (error) {
|
|
120
|
+
if (process.env.OPEN_BROWSER_AUTOSTART === '0' ||
|
|
121
|
+
!['SERVICE_UNAVAILABLE', 'not_ready', 'RESPONSE_LOST'].includes(error.code)) throw error;
|
|
122
|
+
if (error.code === 'SERVICE_UNAVAILABLE' && !launched) {
|
|
123
|
+
await start(root);
|
|
124
|
+
launched = true;
|
|
125
|
+
} else {
|
|
126
|
+
await delay(retryDelayMs, undefined, { signal });
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
try {
|
|
130
|
+
await api.capabilities({ signal });
|
|
131
|
+
return;
|
|
132
|
+
} catch (cause) {
|
|
133
|
+
signal.throwIfAborted();
|
|
134
|
+
error = cause;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
} catch (cause) {
|
|
138
|
+
if (signal.aborted) throw new OpenBrowserError('REQUEST_TIMEOUT', t("Timed out waiting for the local service to become ready."));
|
|
139
|
+
throw cause;
|
|
140
|
+
} finally {
|
|
141
|
+
api.close();
|
|
121
142
|
}
|
|
122
|
-
return false;
|
|
123
143
|
}
|
|
124
144
|
|
|
125
145
|
async function runSession(node, root, args) {
|
|
126
|
-
|
|
127
|
-
const errorCode = parseErrorCode(probe.stderr);
|
|
128
|
-
if (probe.code !== 0 && ['SERVICE_UNAVAILABLE', 'not_ready'].includes(errorCode) && process.env.OPEN_BROWSER_AUTOSTART !== '0') {
|
|
129
|
-
if (errorCode === 'SERVICE_UNAVAILABLE') {
|
|
130
|
-
try { await startLocalBrowser(root); } catch { /* return the original service error below */ }
|
|
131
|
-
}
|
|
132
|
-
if (await waitForService(node, root)) probe = { code: 0 };
|
|
133
|
-
}
|
|
134
|
-
if (probe.code !== 0) {
|
|
135
|
-
if (probe.stdout) process.stdout.write(probe.stdout);
|
|
136
|
-
if (probe.stderr) process.stderr.write(probe.stderr);
|
|
137
|
-
return probe.code;
|
|
138
|
-
}
|
|
146
|
+
await ensureService(root);
|
|
139
147
|
const child = spawn(node, [path.join(root, 'cli.mjs'), ...args], {
|
|
140
148
|
cwd: root,
|
|
141
149
|
env: process.env,
|
|
142
150
|
stdio: 'inherit',
|
|
143
151
|
});
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
async function installSkillLinks(root) {
|
|
148
|
-
if (process.env.OPEN_BROWSER_AUTO_INSTALL_SKILLS === '0') return;
|
|
149
|
-
const installer = path.join(root, 'skill-links.mjs');
|
|
150
|
-
if (!await executable(installer)) return;
|
|
151
|
-
try {
|
|
152
|
-
const { installAgentSkillLinks } = await import(pathToFileURL(installer).href);
|
|
153
|
-
const result = await installAgentSkillLinks({ source: path.join(root, 'skills', 'open-browser') });
|
|
154
|
-
if (process.env.OPEN_BROWSER_SKILLS_VERBOSE === '1') process.stderr.write(JSON.stringify({ skillLinks: result }) + '\n');
|
|
155
|
-
} catch (error) {
|
|
156
|
-
if (process.env.OPEN_BROWSER_SKILLS_VERBOSE === '1') process.stderr.write(JSON.stringify({ skillLinksError: error.message }) + '\n');
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
async function printSkillGuide(root) {
|
|
161
|
-
const platform = process.platform === 'darwin' ? 'macos' : process.platform === 'win32' ? 'windows' : null;
|
|
162
|
-
const candidates = platform
|
|
163
|
-
? [path.join(root, 'skills', 'open-browser', `SKILL.${platform}.md`), path.join(root, 'skills', 'open-browser', 'SKILL.md')]
|
|
164
|
-
: [path.join(root, 'skills', 'open-browser', 'SKILL.md')];
|
|
165
|
-
for (const guide of candidates) {
|
|
166
|
-
try {
|
|
167
|
-
const { readFile } = await import('node:fs/promises');
|
|
168
|
-
process.stdout.write(await readFile(guide, 'utf8'));
|
|
169
|
-
return;
|
|
170
|
-
} catch {}
|
|
171
|
-
}
|
|
172
|
-
throw Object.assign(new Error(`未找到 Skill 指南。已检查:${candidates.join('、')}`), { code: 'SKILL_GUIDE_NOT_FOUND' });
|
|
152
|
+
const [code] = await once(child, 'close');
|
|
153
|
+
return code ?? 1;
|
|
173
154
|
}
|
|
174
155
|
|
|
175
156
|
export async function invoke({ node, root, args, input, start = startLocalBrowser }) {
|
|
176
157
|
const first = await run(node, root, args, input);
|
|
177
158
|
if (first.code === 0) return first;
|
|
178
|
-
const errorCode = parseErrorCode(first.stderr);
|
|
179
|
-
if (
|
|
180
|
-
if (errorCode === '
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
159
|
+
const errorCode = parseErrorCode(args[0] === '--json' ? first.stdout : first.stderr);
|
|
160
|
+
if (process.env.OPEN_BROWSER_AUTOSTART === '0') return first;
|
|
161
|
+
if (errorCode === 'RESPONSE_LOST') {
|
|
162
|
+
const method = args[0] === '--json' ? args[1] : args[0];
|
|
163
|
+
const { readCapabilities } = await import(pathToFileURL(path.join(root, 'capability-matrix.mjs')).href);
|
|
164
|
+
// Capturing a frame issues a new one-time ticket. Retry only repeatable reads.
|
|
165
|
+
if (method === 'captureVisual' || !(readCapabilities.includes(method) ||
|
|
166
|
+
['capabilities', 'listWorkspaces', 'listUploads', 'canvasSnapshot', 'admin.list', 'admin.scheduler'].includes(method))) return first;
|
|
167
|
+
} else if (!['SERVICE_UNAVAILABLE', 'not_ready'].includes(errorCode)) return first;
|
|
168
|
+
try { await ensureService(root, start, { code: errorCode }); }
|
|
169
|
+
catch { return first; }
|
|
184
170
|
return run(node, root, args, input);
|
|
185
171
|
}
|
|
186
172
|
|
|
187
173
|
async function main() {
|
|
188
|
-
const
|
|
189
|
-
|
|
174
|
+
const root = fileURLToPath(new URL('../../..', import.meta.url));
|
|
175
|
+
const args = process.argv.slice(2);
|
|
176
|
+
// Older desktop launchers provide their own package directory as argv[2].
|
|
177
|
+
if (args[0] && path.isAbsolute(args[0]) && await realpath(args[0]).catch(() => null) === path.resolve(root)) args.shift();
|
|
190
178
|
if (args[0] === 'skill') {
|
|
191
|
-
if (args.length > 1) throw Object.assign(new Error(
|
|
192
|
-
await
|
|
179
|
+
if (args.length > 1) throw Object.assign(new Error(t("skill takes no additional arguments.")), { code: 'INVALID_PARAMS' });
|
|
180
|
+
const { readSkillGuide } = await import('./guide.mjs');
|
|
181
|
+
process.stdout.write(await readSkillGuide());
|
|
193
182
|
return;
|
|
194
183
|
}
|
|
195
|
-
await
|
|
184
|
+
const { autoInstallSkillLinks } = await import('../../../skill-links.mjs');
|
|
185
|
+
await autoInstallSkillLinks({ useCache: true });
|
|
196
186
|
if (args[0] === 'session') {
|
|
197
187
|
process.exitCode = await runSession(process.execPath, root, args);
|
|
198
188
|
return;
|
|
@@ -205,9 +195,9 @@ async function main() {
|
|
|
205
195
|
process.exitCode = result.code;
|
|
206
196
|
}
|
|
207
197
|
|
|
208
|
-
if (process.argv[1] &&
|
|
198
|
+
if (import.meta.main ?? (process.argv[1] && await realpath(process.argv[1]).catch(() => null) === fileURLToPath(import.meta.url))) {
|
|
209
199
|
main().catch(error => {
|
|
210
|
-
process.stderr.write(JSON.stringify({ error: { code: error.code ?? 'CLI_BOOTSTRAP_FAILED', message: error.message } }) + '\n');
|
|
200
|
+
process.stderr.write(JSON.stringify({ error: { code: error.code ?? 'CLI_BOOTSTRAP_FAILED', message: error.message, nextAction: error.nextAction } }) + '\n');
|
|
211
201
|
process.exitCode = 1;
|
|
212
202
|
});
|
|
213
203
|
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { locale, t } from '../../../i18n.mjs';
|
|
2
|
+
import { readFile } from 'node:fs/promises';
|
|
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';
|
|
7
|
+
let body;
|
|
8
|
+
try {
|
|
9
|
+
body = await readFile(new URL('../' + filename, import.meta.url), 'utf8');
|
|
10
|
+
} catch (cause) {
|
|
11
|
+
throw Object.assign(new Error(t("Could not find the open-browser skill guide."), {cause}), {code:'SKILL_GUIDE_NOT_FOUND'});
|
|
12
|
+
}
|
|
13
|
+
if (!body.endsWith('\n')) body += '\n';
|
|
14
|
+
const label = {darwin:'macOS', win32:'Windows'}[platform];
|
|
15
|
+
if (!label) return body;
|
|
16
|
+
const supplement = await readFile(new URL(`../references/${label.toLowerCase()}${chinese ? '' : '.en'}.md`, import.meta.url), 'utf8')
|
|
17
|
+
.catch(error => { if (error.code !== 'ENOENT') throw error; });
|
|
18
|
+
if (!supplement) return body;
|
|
19
|
+
return `[open-browser:skill] ${t('Open Browser usage guide ({0})', label)}\n\n${body}\n${supplement}`;
|
|
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
|
-
|
|
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
|
package/studio/demo-site.mjs
CHANGED
|
@@ -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="
|
|
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 =
|
|
68
|
-
const viewLogin = invalid => demoDocument('
|
|
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('
|
|
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
|
}
|