@xiaoqiong0v0/opencode-browser-tool 1.7.0 → 1.10.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.
@@ -1,8 +1,20 @@
1
1
  import { readFileSync, existsSync, writeFileSync, mkdirSync } from "fs";
2
- import { resolve, dirname } from "path";
2
+ import { resolve, dirname, relative, isAbsolute, sep } from "path";
3
3
  import { homedir } from "os";
4
+ import { tf } from "../i18n/index.js";
5
+ import { log } from "../logger.js";
4
6
  const PLUGIN_NAME = "opencode-browser-tool";
5
7
  const CONFIG_FILE = "browser-tool.jsonc";
8
+ /** profile 名长度上限(字符) */
9
+ const PROFILE_NAME_MAX_LEN = 64;
10
+ /** profile 名禁止出现的字符(/ \ : NUL 与 Windows 非法文件名字符) */
11
+ const PROFILE_NAME_FORBIDDEN = /[\/\\:\u0000<>"|?*]/;
12
+ /** Windows 保留设备名(大小写不敏感;含带扩展名的形式,如 CON.txt) */
13
+ const WINDOWS_RESERVED_NAMES = new Set([
14
+ "CON", "PRN", "AUX", "NUL",
15
+ ...Array.from({ length: 9 }, (_, i) => `COM${i + 1}`),
16
+ ...Array.from({ length: 9 }, (_, i) => `LPT${i + 1}`),
17
+ ]);
6
18
  const defaults = { panelLang: "en", toolLang: "en" };
7
19
  let _config = { ...defaults };
8
20
  let _worktree = "";
@@ -30,9 +42,68 @@ export function getCacheDir() {
30
42
  export function getProfilesDir() {
31
43
  return resolve(getCacheDir(), "user-data");
32
44
  }
33
- /** 某个配置的 WebView2 用户数据目录 */
34
- export function getProfileDir(name) {
35
- return resolve(getProfilesDir(), name);
45
+ /**
46
+ * 校验 profile 名并返回原名(不合法则抛错,消息走 i18n `cli.err.profile_invalid_name`)
47
+ * 规则:非空、≤64 字符、不含 / \ : NUL 及 < > " | ? *、不等于 . / ..、不以 . 开头、
48
+ * 不是 Windows 保留设备名(CON/PRN/AUX/NUL/COM1-9/LPT1-9,大小写不敏感)。
49
+ */
50
+ export function assertSafeProfileName(name) {
51
+ const bad = () => {
52
+ throw new Error(tf("cli.err.profile_invalid_name", { name: String(name) }));
53
+ };
54
+ if (typeof name !== "string" || name.length === 0)
55
+ bad();
56
+ if (name.length > PROFILE_NAME_MAX_LEN)
57
+ bad();
58
+ if (PROFILE_NAME_FORBIDDEN.test(name))
59
+ bad();
60
+ if (name === "." || name === "..")
61
+ bad();
62
+ if (name.startsWith("."))
63
+ bad();
64
+ // Windows 保留名对带扩展名的写法同样生效(CON.txt 也不可创建)
65
+ if (WINDOWS_RESERVED_NAMES.has(name.split(".")[0].toUpperCase()))
66
+ bad();
67
+ return name;
68
+ }
69
+ /**
70
+ * 把 profile 名解析为绝对路径:先校验名字,再用 relative 断言结果位于 profiles 目录内
71
+ * (非空、不以 .. 开头、非绝对路径),防止 path traversal。
72
+ */
73
+ export function resolveProfilePath(name) {
74
+ const safe = assertSafeProfileName(name);
75
+ const base = getProfilesDir();
76
+ const full = resolve(base, safe);
77
+ const rel = relative(base, full);
78
+ if (!rel || rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {
79
+ throw new Error(tf("cli.err.profile_invalid_name", { name: String(name) }));
80
+ }
81
+ return full;
82
+ }
83
+ /**
84
+ * 判断 child 是否在 parent **内部**(不包含 parent 自身)。
85
+ * 用 path.relative 判定,避免 `startsWith` 的前缀误判(如 tmpX/a 对 tmp)。
86
+ */
87
+ export function isInsideDir(child, parent) {
88
+ const rel = relative(resolve(parent), resolve(child));
89
+ return !!rel && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
90
+ }
91
+ // ---- 会话隔离(1.9.0):每会话独立 shell 实例的数据目录 ----
92
+ // 路径: <cacheDir>/sessions/<profile>/<sid>
93
+ // 说明: 需求字面为 sessions/<sid>;此处多一层 <profile>,是为了保住 `profile --set` 的语义 ——
94
+ // 它现在的含义是「影响**后续新会话**的数据根(默认 profile)」,运行中的实例不受影响。
95
+ // 若要严格字面路径,去掉 profile 段即可(会话间隔离不受影响,只是 profile 失去作用)。
96
+ /** 会话数据根目录 */
97
+ export function getSessionsDir() {
98
+ return resolve(getCacheDir(), "sessions");
99
+ }
100
+ /** 某会话的独立 user-data-dir(WebView2 profile:cookie/localStorage/缓存全隔离) */
101
+ export function getSessionDataDir(sid) {
102
+ return resolve(getSessionsDir(), getActiveProfile(), sid);
103
+ }
104
+ /** 某会话的临时产物目录(截图落盘等;不再与其它会话/全局 tmp 共享) */
105
+ export function getSessionTmpDir(sid) {
106
+ return resolve(getSessionDataDir(sid), "tmp");
36
107
  }
37
108
  /** 导出目录(用户从 Edge/Chrome 导出的密码 CSV / 书签 HTML) */
38
109
  export function getExportsDir() {
@@ -46,12 +117,25 @@ export function getTmpDir() {
46
117
  function activeProfileFile() {
47
118
  return resolve(getCacheDir(), "active-profile");
48
119
  }
49
- /** 获取当前激活配置(默认 "default";不存在时回落默认) */
120
+ /** 已记录过「activeProfile 非法」告警的值(避免每次读取都刷日志) */
121
+ let _badActiveProfileLogged = "";
122
+ /** 获取当前激活配置(默认 "default";不存在或值非法时回落默认并记日志) */
50
123
  export function getActiveProfile() {
51
124
  try {
52
125
  const v = readFileSync(activeProfileFile(), "utf-8").trim();
53
- if (v)
54
- return v;
126
+ if (v) {
127
+ try {
128
+ return assertSafeProfileName(v);
129
+ }
130
+ catch {
131
+ // 状态文件被手工改坏时,启动路径不能因此抛错:回落 default(仅记一次日志)
132
+ if (_badActiveProfileLogged !== v) {
133
+ _badActiveProfileLogged = v;
134
+ log.error(`active-profile contains invalid name (${v.length} chars); falling back to "default"`);
135
+ }
136
+ return "default";
137
+ }
138
+ }
55
139
  }
56
140
  catch { }
57
141
  return "default";
@@ -89,9 +173,8 @@ function applyConfigFile(config, filePath) {
89
173
  .replace(/\/\/.*$/gm, "")
90
174
  .replace(/\/\*[\s\S]*?\*\//g, "")
91
175
  .replace(/,\s*}/g, "}");
176
+ // 只读取已知键:旧文件里的 browserType / sessionIsolation 等已移除项会被自然忽略(兼容,不报错)
92
177
  const fileConfig = JSON.parse(json);
93
- if (fileConfig.browserType !== undefined)
94
- config.browserType = fileConfig.browserType;
95
178
  if (fileConfig.browsersPath !== undefined)
96
179
  config.browsersPath = fileConfig.browsersPath;
97
180
  if (fileConfig.nodePath !== undefined)
@@ -102,8 +185,6 @@ function applyConfigFile(config, filePath) {
102
185
  config.toolLang = fileConfig.toolLang;
103
186
  if (fileConfig.disabledTools)
104
187
  config.disabledTools = fileConfig.disabledTools;
105
- if (fileConfig.sessionIsolation !== undefined)
106
- config.sessionIsolation = fileConfig.sessionIsolation;
107
188
  if (fileConfig.cacheDir !== undefined)
108
189
  config.cacheDir = fileConfig.cacheDir;
109
190
  }
@@ -144,20 +225,18 @@ function generateDefaultConfig(filePath) {
144
225
  // "browsersPath": "D:/browsers/chromium",
145
226
 
146
227
  // 缓存根目录(可选,默认 ~/.opencode/plugins-cache/opencode-browser-tool)
147
- // 下设 user-data/<profile> 用户配置、exports 导出、tmp 临时密码文件
228
+ // 下设 sessions/<profile>/<sid> 每会话独立浏览器数据、user-data/<profile> 旧目录、
229
+ // exports 导出、tmp 临时密码文件
148
230
  // "cacheDir": "D:/browser-cache",
149
231
 
150
232
  // 禁用的工具列表(可选,工具名不加 bt_ 前缀)
151
233
  // "disabledTools": ["close", "custom_user_agent"],
152
234
 
153
- // 会话隔离:为子会话创建独立 BrowserContext(默认 false,全部共享)
154
- // "sessionIsolation": false,
235
+ // 1.9.0 起「每会话独立浏览器实例」为唯一行为(原 sessionIsolation 开关从未生效,已移除);
236
+ // browserType 同理移除(--browser 从不被 bt-shell 解析)。旧配置里若仍写着这两项会被忽略。
155
237
 
156
238
  // Node.js 路径(可选,不设则从 PATH 查找 node)
157
239
  // "nodePath": "C:/Program Files/nodejs/node.exe",
158
-
159
- // 浏览器类型: "chromium" | "firefox" | "webkit"(默认 chromium)
160
- // "browserType": "firefox",
161
240
  }
162
241
  `, "utf-8");
163
242
  }
package/dist/i18n/en.js CHANGED
@@ -1,6 +1,6 @@
1
1
  const en = {
2
2
  tool: {
3
- "tool.cli.desc": "Browser automation via a CLI-style dispatcher: pass a single command string, e.g. \"navigate --url https://...\" or \"help\". Omit to list all commands. screenshot with --selector scrolls the element into view first.",
3
+ "tool.cli.desc": "Browser automation via a CLI-style dispatcher: pass a single command string, e.g. \"navigate --url https://...\" or \"help\". Omit to list all commands. screenshot with --selector scrolls the element into view first. The browser process is managed automatically by this tool — do not run the bt-shell executable directly (it causes multiple instances and file-lock conflicts).",
4
4
  "tool.cli.arg.args": "Command line string: \"<command> [--flag value ...]\", e.g. \"navigate --url https://...\" (\"help\" lists all)",
5
5
  "cli.header": "bt_cli — browser automation CLI",
6
6
  "cli.usage": "Usage: bt_cli({ args })\n args single command line string: \"<command> [--flag value ...]\"",
@@ -12,25 +12,28 @@ const en = {
12
12
  "cli.example.4": "bt_cli({ args: \"fill --selector #q --value \\\"hello world\\\"\" })",
13
13
  "cli.unknown": "Unknown command: {cmd}",
14
14
  "cli.invalid_args": "Invalid args for {cmd}: {msg}",
15
+ "cli.err.timeout_invalid": "--timeout must be a positive integer in ms (100-60000), got: {v}",
16
+ "cli.err.profile_invalid_name": "Invalid profile name: {name}. Use 1-64 chars, no / \\ : or < > \" | ? *, must not start with a dot, and must not be a Windows reserved name (CON/PRN/AUX/NUL/COM1-9/LPT1-9).",
17
+ "cli.err.file_outside_tmp": "Refusing to read @file outside the plugin temp directory: {path}",
15
18
  "cli.failed": "Command {cmd} failed: {msg}",
16
19
  "cli.cmd.navigate": "Navigate browser to a URL",
17
- "cli.cmd.click": "Click an element",
18
- "cli.cmd.fill": "Fill an input field",
19
- "cli.cmd.clear": "Clear an input field",
20
- "cli.cmd.select": "Select a dropdown option",
21
- "cli.cmd.hover": "Hover over an element",
22
- "cli.cmd.drag": "Drag element to a target",
23
- "cli.cmd.press_key": "Press a keyboard key",
24
- "cli.cmd.upload_file": "Upload a file to an input",
25
- "cli.cmd.screenshot": "Take a screenshot (returns image attachment; with --selector it scrolls the element into view first)",
26
- "cli.cmd.evaluate": "Execute JS in the page, return result",
20
+ "cli.cmd.click": "Click an element; optional --timeout ms (100-60000) caps this call's wait budget, timeout errors explicitly",
21
+ "cli.cmd.fill": "Fill an input field; optional --timeout ms (100-60000) caps this call's wait budget, timeout errors explicitly",
22
+ "cli.cmd.clear": "Clear an input field; optional --timeout ms (100-60000) caps this call's wait budget, timeout errors explicitly",
23
+ "cli.cmd.select": "Select a dropdown option; optional --timeout ms (100-60000) caps this call's wait budget, timeout errors explicitly",
24
+ "cli.cmd.hover": "Hover over an element; optional --timeout ms (100-60000) caps this call's wait budget, timeout errors explicitly",
25
+ "cli.cmd.drag": "Drag element to a target; optional --timeout ms (100-60000) caps this call's wait budget, timeout errors explicitly",
26
+ "cli.cmd.press_key": "Press a keyboard key; optional --timeout ms (100-60000) caps this call's wait budget, timeout errors explicitly",
27
+ "cli.cmd.upload_file": "Upload a file to an input; optional --timeout ms (100-60000) caps this call's wait budget, timeout errors explicitly",
28
+ "cli.cmd.screenshot": "Take a screenshot (returns image attachment; with --selector it scrolls the element into view first); optional --timeout ms (100-60000) caps this call's wait budget, timeout errors explicitly",
29
+ "cli.cmd.evaluate": "Execute JS in the page, return result; optional --timeout ms (100-60000) caps this call's wait budget, timeout errors explicitly",
27
30
  "cli.cmd.get_visible_text": "Get visible page text",
28
31
  "cli.cmd.get_visible_html": "Get page HTML structure",
29
32
  "cli.cmd.console_logs": "Get browser console logs",
30
33
  "cli.cmd.go_back": "Go back in history",
31
34
  "cli.cmd.go_forward": "Go forward in history",
32
- "cli.cmd.resize": "Resize the viewport",
33
- "cli.cmd.set_device": "Apply device preset (no name = list presets)",
35
+ "cli.cmd.resize": "Resize the page content area (viewport, not the OS window; window height = content + 72px toolbar; min 360x360, smaller values are clamped)",
36
+ "cli.cmd.set_device": "Apply device preset (no name = list presets; preset sizes are content-area/viewport sizes)",
34
37
  "cli.cmd.devtools": "Open/close devtools (open/close/toggle)",
35
38
  "cli.cmd.reload": "Reload the current page",
36
39
  "cli.cmd.open_window": "Open the browser window",
@@ -39,57 +42,138 @@ const en = {
39
42
  "cli.cmd.scroll": "Scroll the page",
40
43
  "cli.cmd.wait_for_selector": "Wait for an element to appear",
41
44
  "cli.cmd.click_and_switch_tab": "Click a link and switch to the new tab",
42
- "cli.cmd.iframe_click": "Click an element inside an iframe",
43
- "cli.cmd.iframe_fill": "Fill an input inside an iframe",
45
+ "cli.cmd.iframe_click": "Click an element inside an iframe; optional --timeout ms (100-60000) caps this call's wait budget, timeout errors explicitly",
46
+ "cli.cmd.iframe_fill": "Fill an input inside an iframe; optional --timeout ms (100-60000) caps this call's wait budget, timeout errors explicitly",
44
47
  "cli.cmd.get_browser_status": "Check if browser is open and current page",
45
48
  "cli.cmd.list_tabs": "List all open tabs",
46
49
  "cli.cmd.switch_tab": "Switch to a tab by index",
47
50
  "cli.cmd.new_tab": "Open a new tab",
48
51
  "cli.cmd.close_tab": "Close a tab (omit = current)",
49
- "cli.cmd.get_element_state": "Element exists/visible/size/state",
50
- "cli.cmd.scroll_to_element": "Scroll until element is visible",
51
- "cli.cmd.get_dropdown_options": "List dropdown options",
52
+ "cli.cmd.get_element_state": "Element exists/visible/size/state; optional --timeout ms (100-60000) caps this call's wait budget, timeout errors explicitly",
53
+ "cli.cmd.scroll_to_element": "Scroll until element is visible; optional --timeout ms (100-60000) caps this call's wait budget, timeout errors explicitly",
54
+ "cli.cmd.get_dropdown_options": "List dropdown options; optional --timeout ms (100-60000) caps this call's wait budget, timeout errors explicitly",
52
55
  "cli.cmd.custom_user_agent": "Set a custom User-Agent",
53
56
  "cli.cmd.expect_response": "Start expecting an HTTP response pattern",
54
57
  "cli.cmd.assert_response": "Check if expected response matched",
55
- "cli.cmd.get_accessibility_tree": "Get the accessibility tree",
58
+ "cli.cmd.get_accessibility_tree": "Get the accessibility tree; optional --timeout ms (100-60000) caps this call's wait budget, timeout errors explicitly",
56
59
  "cli.cmd.list_records": "List annotation records in the panel",
57
60
  "cli.cmd.read_record_content": "Read an annotation record by id",
58
61
  "cli.cmd.fake_audio": "Inject audio into fake mic (tone/seq/dtmf/noise/audio/ambient/stop)",
59
62
  "cli.cmd.fake_video": "Inject frames into fake camera (image/video/auto/stop)",
60
- "cli.cmd.profile": "List/switch/delete user profiles (--set <name> restarts browser; --delete removes a non-default, non-active profile)",
63
+ "cli.cmd.profile": "List/switch/delete user profiles (--set <name> switches the default for new sessions without restarting running browsers; --delete removes a non-default, non-active profile)",
61
64
  "cli.cmd.exports": "Show export dir + how to export Edge/Chrome passwords/bookmarks",
62
65
  "cli.cmd.lookup": "Find a password in a CSV export, return @file: path (not in context)",
66
+ // ---- Diagnostic notes appended to command output ----
67
+ "cli.note.degraded": " (degraded: {reason})",
68
+ "cli.note.not_ready": " (not ready after {ms}ms{rs})",
69
+ "cli.note.scroll_unstable": " (scroll position not stable after {ms}ms)",
70
+ "cli.note.reached": " (element reached={where} after {ms}ms{why})",
71
+ "cli.note.beyond": " (element larger than viewport, captured beyond viewport)",
72
+ "cli.note.timeout_clamped": " (clamped to {ms}ms)",
73
+ // ---- Command result strings ----
74
+ "cli.out.navigate.install_failed": "Installation failed: {error}. Retry.",
75
+ "cli.out.navigate.installing": "Installing {name} ({progress}). Try again.",
76
+ "cli.out.navigate.ok": "Navigated to: {url}",
77
+ "cli.out.click": "Clicked",
78
+ "cli.out.fill": "Filled",
79
+ "cli.out.clear": "Cleared",
80
+ "cli.out.select": "Selected",
81
+ "cli.out.hover": "Hovered",
82
+ "cli.out.drag": "Dragged",
83
+ "cli.out.press_key": "Pressed: {key}",
84
+ "cli.out.upload_file": "Uploaded",
85
+ "cli.out.screenshot": "Screenshot taken{where}",
86
+ "cli.out.screenshot.element": " (element: {sel})",
87
+ "cli.out.screenshot.fullpage": " (full page)",
88
+ "cli.out.no_visible_text": "(no visible text)",
89
+ "cli.out.no_visible_html": "(no visible html)",
90
+ "cli.out.html_truncated": "…(truncated at maxLength={n})",
91
+ "cli.out.no_logs": "(no logs)",
92
+ "cli.out.go_back": "Went back, current URL: {url}",
93
+ "cli.out.go_forward": "Went forward, current URL: {url}",
94
+ "cli.out.resize": "Resized content to {w}x{h}",
95
+ "cli.out.resize_clamped": " (clamped to 360x360 minimum)",
96
+ "cli.out.device_list_header": "Available device presets:",
97
+ "cli.out.device_applied": "Device preset applied: {name} ({w}x{h} content)\nUser-Agent: {ua}",
98
+ "cli.out.devtools_open": "Devtools opened",
99
+ "cli.out.devtools_closed": "Devtools closed",
100
+ // Windows/wry cannot actually close DevTools: report it instead of claiming success
101
+ "cli.out.devtools_unsupported": "Closing DevTools is not supported on this platform (wry limitation); toggle it with F12",
102
+ "cli.out.reload": "Page reloaded: {url}",
103
+ // Fallback when the backend response carries no url (no last-navigated URL on the tab) — keeps output from showing undefined
104
+ "cli.out.reload_nourl": "Page reloaded",
105
+ "cli.out.open_window": "Browser window opened",
106
+ "cli.out.close_already": "Browser already closed",
107
+ "cli.out.close_done": "Browser closed",
108
+ "cli.out.notify_shown": "Notification shown",
109
+ "cli.out.scroll": "Scrolled {dir} by {n}px",
110
+ "cli.out.wait_appeared": "Element appeared",
111
+ "cli.out.click_switch_tab": "Clicked {sel}, current URL: {url}",
112
+ "cli.out.iframe_click": "Clicked in iframe",
113
+ "cli.out.iframe_fill": "Filled in iframe",
114
+ "cli.out.status.not_running": "Browser is not running.\nbt-shell: {bin}\nCall open_window when needed (other tools will not reopen it automatically).",
115
+ "cli.out.status.installing": "Installing {list}.",
116
+ "cli.out.status.not_open": "The browser is running but has no window. Call open_window to open one.",
117
+ "cli.out.status.open": "Browser is open\nTitle: {title}\nURL: {url}\nTabs: {n}",
118
+ "cli.out.tabs_none": "(no tabs)",
119
+ "cli.out.tabs_header": "Tabs ({n}):",
120
+ "cli.out.switch_tab": "Switched to tab #{i}: {url}",
121
+ "cli.out.new_tab": "New tab opened: {url}",
122
+ "cli.out.close_tab": "Closed tab #{i}",
123
+ "cli.out.close_tab_current": "Closed current tab",
124
+ "cli.out.element_not_found": "Element not found: {sel}",
125
+ "cli.out.element_state": "Element <{tag}>: {sel}\nVisible: {visible}{text}\nRect: {rect}",
126
+ "cli.out.scroll_to_element": "Scrolled to element",
127
+ "cli.out.dropdown_none": "Select not found or no options: {sel}",
128
+ "cli.out.ua_set": "User-Agent set",
129
+ "cli.out.expect_response": "Now expecting response matching: {url}. Use command=assert_response to check.",
130
+ "cli.out.assert_matched": "Response matched: {url} ({status})",
131
+ "cli.out.assert_none": "No response yet",
132
+ "cli.out.no_ax": "(no accessibility info)",
133
+ "cli.out.no_records": "(no records)",
134
+ "cli.out.record_not_found": "(record #{id} not found)",
135
+ "cli.out.record_image": "\nimage: {kb}KB base64",
136
+ "cli.out.record_image_saved": "\nimage: {kb}KB base64 (saved: {path})",
137
+ "cli.out.record_note_none": "(none)",
138
+ "cli.out.fake_audio": "Fake mic audio: {injected}",
139
+ "cli.out.fake_video": "Fake camera video: {injected}",
140
+ "cli.out.profile_no_delete_default": "Cannot delete the default profile",
141
+ "cli.out.profile_no_delete_active": "Cannot delete the active profile; switch to another first (profile --set <name>)",
142
+ "cli.out.profile_not_found": "Profile not found: {name}",
143
+ "cli.out.profile_deleted": "Deleted profile: {name}",
144
+ "cli.out.profile_switched": "Switched default profile: {name} (affects browsers of NEW sessions only; running sessions are unaffected)",
145
+ "cli.out.profiles_none": "(no profiles yet)",
146
+ "cli.out.profiles_header": "Profiles:\n{list}\n\nActive: {active}\nSwitch: profile --set <name> (affects new sessions only; does not restart running browsers)\nDelete: profile --delete <name> (not default/active)",
147
+ "cli.out.exports": "Export directory: {dir}\n\nHow to export from Edge/Chrome:\n Passwords: Settings → Profiles → Passwords → ⋯ → Export passwords (CSV)\n Bookmarks: Settings → Profiles → Bookmarks → ⋯ → Export (HTML)\nPlace the exported files in the directory above, then the model can read them.\n\nRead passwords without leaking into context:\n lookup --csv <file.csv> --url <site>\n fill --selector <input> --value @file:<path>",
148
+ "cli.out.lookup_usage": "Usage: lookup --csv <path> --url <site>",
149
+ "cli.out.lookup_found": "Found: {user} @ {url}\nUse: fill --selector <input> --value @file:{tmp}\n(password in temp file, deleted after use)",
150
+ "cli.out.lookup_none": "No entry found for: {url}",
151
+ "cli.out.media_mode": "Media mode: {mode}",
152
+ "cli.read_file_failed": "Cannot read @file: {path}: {msg}",
153
+ // ---- Binary status (describeBinaryStatus; never embeds local absolute paths) ----
154
+ "bin.ready": "bt-shell is ready",
155
+ "bin.downloading": "bt-shell is downloading ({progress}%)… retry later",
156
+ "bin.failed": "bt-shell download failed: {reason}; set BT_SHELL_DOWNLOAD_BASE to change mirror, or BT_SHELL_PATH to point at a binary",
157
+ "bin.disabled": "bt-shell auto-download is disabled (BT_SHELL_NO_DOWNLOAD=1); set BT_SHELL_PATH to a binary (expected path is in the plugin log)",
158
+ "bin.unsupported": "bt-shell does not support this platform yet: {reason}",
159
+ "bin.not_ready": "bt-shell is not ready yet, retry later",
160
+ "bin.release_not_found": "No Release asset found for this version (tag={tag}); for a plugin-only change make sure the binary is still attached to the x.Y.0 Release, and for Rust changes bump the minor version and create/update that Release first",
161
+ // ---- client-layer errors surfaced to the model ----
162
+ "client.service_timeout": "Browser service not ready (timed out). bt-shell is managed automatically by the plugin — do not run the executable directly. Retry via bt_cli later (e.g. open_window).",
163
+ "client.attach_timeout": "External bt-shell at {url} is not ready (timed out). Check BT_SHELL_URL/BT_SHELL_PORT and that the shell is running.",
164
+ "client.not_configured": "Service not configured",
165
+ "client.service_error": "Service error",
166
+ "client.auth_rejected": "Local browser API rejected authentication (HTTP 401/403). Call open_window to reopen the browser.",
167
+ "client.bad_response": "Malformed response from the browser service (invalid JSON). The instance was not treated as closed; retry the call.",
168
+ "client.bt_shell_path_missing": "BT_SHELL_PATH points to a binary that does not exist (path is in the environment variable)",
169
+ "client.spawn_failed": "Failed to start the bt-shell process (retry via bt_cli later; do not run the executable directly)",
170
+ "client.session_closed_during_start": "A close request was received while the browser was starting; that instance was terminated. Call open_window if you need it again.",
171
+ "client.attach_gone": "Attached external bt-shell at {url} is gone (attach mode does not own that process; restart the shell yourself).",
172
+ "client.attach_need_token": "Attach mode requires an auth token: set BT_SHELL_TOKEN and start the external bt-shell with the same token (--token <token>, or the same environment variable).",
173
+ "client.attach_bad_token": "External bt-shell refused authentication: BT_SHELL_TOKEN does not match the --token/BT_SHELL_TOKEN the shell was started with.",
174
+ "client.browser_closed": "Browser is closed. Call open_window to open it first, then retry.",
63
175
  "tool.set_media_mode.desc": "Switch camera/microphone mode: 'simulate' (fake devices, default) or 'real' (real devices, falls back to simulate if unavailable). Call without mode to query the current mode.",
64
176
  "tool.set_media_mode.arg.mode": "Mode: simulate or real (omit to query current)",
65
177
  },
66
- panel: {
67
- "panel.title": "Tool Panel",
68
- "panel.pick_hint": "Hover to highlight elements\nClick to select for annotation",
69
- "panel.annotation_placeholder": "Add annotation...",
70
- "panel.action_none": "No action",
71
- "panel.action_click": "Click",
72
- "panel.action_fill": "Fill",
73
- "panel.action_value_placeholder": "Value...",
74
- "panel.send": "Send",
75
- "panel.send_all": "Send All",
76
- "panel.close": "Close",
77
- "panel.send_failed": "Send failed",
78
- "panel.annotate": "Annotate",
79
- "panel.screenshot_btn": "Screenshot",
80
- "panel.screenshot_sent": "Screenshot sent",
81
- "panel.screenshot_note": "Add description...",
82
- "panel.screenshot_hint": "Double click to select entire page",
83
- "panel.screenshot_stored": "Screenshot saved",
84
- "panel.screenshot_failed": "Screenshot failed",
85
- "panel.cancel": "Cancel",
86
- "panel.confirm": "Confirm",
87
- "panel.annotation_stored": "Annotation saved",
88
- "panel.annotation_required": "Please enter annotation text",
89
- "panel.no_records": "No records yet",
90
- "panel.sent_records": "Sent {n} records",
91
- "panel.send_records_failed": "Send failed",
92
- "panel.delete": "Delete",
93
- },
94
178
  };
95
179
  export default en;
@@ -1,24 +1,28 @@
1
1
  import { getConfig } from "../config/index.js";
2
+ import en from "./en.js";
2
3
  const _strings = {};
3
4
  /** 注册语言包 */
4
5
  export function registerLocale(lang, strings) {
5
6
  _strings[lang] = strings;
6
7
  }
8
+ /** 惰性兜底:任何入口(binary.ts 独立运行等)未走插件注册时至少有 en 可用,不输出裸键 */
9
+ function ensureFallback() {
10
+ if (!_strings.en)
11
+ _strings.en = en;
12
+ }
7
13
  /** 获取工具描述翻译 */
8
14
  export function t(key, lang) {
15
+ ensureFallback();
9
16
  const l = lang || getConfig().toolLang;
10
17
  const str = _strings[l] || _strings.en;
11
18
  return str?.tool[key] || _strings.en?.tool[key] || key;
12
19
  }
13
- /** 获取面板 UI 翻译 */
14
- export function panelT(key, lang) {
15
- const l = lang || getConfig().panelLang;
16
- const str = _strings[l] || _strings.en;
17
- return str?.panel[key] || _strings.en?.panel[key] || key;
18
- }
19
- /** 获取面板完整翻译对象(供注入) */
20
- export function getPanelStrings(lang) {
21
- const l = lang || getConfig().panelLang;
22
- const str = _strings[l] || _strings.en;
23
- return str?.panel || {};
20
+ /** 取工具文案并替换 `{name}` 占位符(缺失键回退 en,再缺返回键名本身,不崩溃) */
21
+ export function tf(key, vars, lang) {
22
+ let s = t(key, lang);
23
+ if (vars) {
24
+ for (const [k, v] of Object.entries(vars))
25
+ s = s.split(`{${k}}`).join(String(v));
26
+ }
27
+ return s;
24
28
  }