@xiaoqiong0v0/opencode-browser-tool 1.9.0 → 1.10.2

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,51 @@ 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);
36
90
  }
37
91
  // ---- 会话隔离(1.9.0):每会话独立 shell 实例的数据目录 ----
38
92
  // 路径: <cacheDir>/sessions/<profile>/<sid>
@@ -63,12 +117,25 @@ export function getTmpDir() {
63
117
  function activeProfileFile() {
64
118
  return resolve(getCacheDir(), "active-profile");
65
119
  }
66
- /** 获取当前激活配置(默认 "default";不存在时回落默认) */
120
+ /** 已记录过「activeProfile 非法」告警的值(避免每次读取都刷日志) */
121
+ let _badActiveProfileLogged = "";
122
+ /** 获取当前激活配置(默认 "default";不存在或值非法时回落默认并记日志) */
67
123
  export function getActiveProfile() {
68
124
  try {
69
125
  const v = readFileSync(activeProfileFile(), "utf-8").trim();
70
- if (v)
71
- 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
+ }
72
139
  }
73
140
  catch { }
74
141
  return "default";
package/dist/i18n/en.js CHANGED
@@ -13,6 +13,8 @@ const en = {
13
13
  "cli.unknown": "Unknown command: {cmd}",
14
14
  "cli.invalid_args": "Invalid args for {cmd}: {msg}",
15
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}",
16
18
  "cli.failed": "Command {cmd} failed: {msg}",
17
19
  "cli.cmd.navigate": "Navigate browser to a URL",
18
20
  "cli.cmd.click": "Click an element; optional --timeout ms (100-60000) caps this call's wait budget, timeout errors explicitly",
@@ -58,7 +60,7 @@ const en = {
58
60
  "cli.cmd.read_record_content": "Read an annotation record by id",
59
61
  "cli.cmd.fake_audio": "Inject audio into fake mic (tone/seq/dtmf/noise/audio/ambient/stop)",
60
62
  "cli.cmd.fake_video": "Inject frames into fake camera (image/video/auto/stop)",
61
- "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)",
62
64
  "cli.cmd.exports": "Show export dir + how to export Edge/Chrome passwords/bookmarks",
63
65
  "cli.cmd.lookup": "Find a password in a CSV export, return @file: path (not in context)",
64
66
  // ---- Diagnostic notes appended to command output ----
@@ -95,6 +97,8 @@ const en = {
95
97
  "cli.out.device_applied": "Device preset applied: {name} ({w}x{h} content)\nUser-Agent: {ua}",
96
98
  "cli.out.devtools_open": "Devtools opened",
97
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",
98
102
  "cli.out.reload": "Page reloaded: {url}",
99
103
  // Fallback when the backend response carries no url (no last-navigated URL on the tab) — keeps output from showing undefined
100
104
  "cli.out.reload_nourl": "Page reloaded",
@@ -107,9 +111,9 @@ const en = {
107
111
  "cli.out.click_switch_tab": "Clicked {sel}, current URL: {url}",
108
112
  "cli.out.iframe_click": "Clicked in iframe",
109
113
  "cli.out.iframe_fill": "Filled in iframe",
110
- "cli.out.status.not_running": "Browser is not running.\nbt-shell: {bin}\n(Any other tool call will start it; or use open_window. If you have closed the browser, use open_window)",
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).",
111
115
  "cli.out.status.installing": "Installing {list}.",
112
- "cli.out.status.not_open": "Browser is not open. Use command=open_window or navigate.",
116
+ "cli.out.status.not_open": "The browser is running but has no window. Call open_window to open one.",
113
117
  "cli.out.status.open": "Browser is open\nTitle: {title}\nURL: {url}\nTabs: {n}",
114
118
  "cli.out.tabs_none": "(no tabs)",
115
119
  "cli.out.tabs_header": "Tabs ({n}):",
@@ -139,7 +143,7 @@ const en = {
139
143
  "cli.out.profile_deleted": "Deleted profile: {name}",
140
144
  "cli.out.profile_switched": "Switched default profile: {name} (affects browsers of NEW sessions only; running sessions are unaffected)",
141
145
  "cli.out.profiles_none": "(no profiles yet)",
142
- "cli.out.profiles_header": "Profiles:\n{list}\n\nActive: {active}\nSwitch: profile --set <name> (restarts browser, current tabs lost)\nDelete: profile --delete <name> (not default/active)",
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)",
143
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>",
144
148
  "cli.out.lookup_usage": "Usage: lookup --csv <path> --url <site>",
145
149
  "cli.out.lookup_found": "Found: {user} @ {url}\nUse: fill --selector <input> --value @file:{tmp}\n(password in temp file, deleted after use)",
@@ -159,41 +163,17 @@ const en = {
159
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.",
160
164
  "client.not_configured": "Service not configured",
161
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.",
162
168
  "client.bt_shell_path_missing": "BT_SHELL_PATH points to a binary that does not exist (path is in the environment variable)",
163
169
  "client.spawn_failed": "Failed to start the bt-shell process (retry via bt_cli later; do not run the executable directly)",
164
- "client.session_closed_during_start": "Session was closed while the browser was starting; that instance was recycled (not registered). Call the tool again to reopen.",
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.",
165
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.",
166
174
  "client.browser_closed": "Browser is closed. Call open_window to open it first, then retry.",
167
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.",
168
176
  "tool.set_media_mode.arg.mode": "Mode: simulate or real (omit to query current)",
169
177
  },
170
- panel: {
171
- "panel.title": "Tool Panel",
172
- "panel.pick_hint": "Hover to highlight elements\nClick to select for annotation",
173
- "panel.annotation_placeholder": "Add annotation...",
174
- "panel.action_none": "No action",
175
- "panel.action_click": "Click",
176
- "panel.action_fill": "Fill",
177
- "panel.action_value_placeholder": "Value...",
178
- "panel.send": "Send",
179
- "panel.send_all": "Send All",
180
- "panel.close": "Close",
181
- "panel.send_failed": "Send failed",
182
- "panel.annotate": "Annotate",
183
- "panel.screenshot_btn": "Screenshot",
184
- "panel.screenshot_sent": "Screenshot sent",
185
- "panel.screenshot_note": "Add description...",
186
- "panel.screenshot_hint": "Double click to select entire page",
187
- "panel.screenshot_stored": "Screenshot saved",
188
- "panel.screenshot_failed": "Screenshot failed",
189
- "panel.cancel": "Cancel",
190
- "panel.confirm": "Confirm",
191
- "panel.annotation_stored": "Annotation saved",
192
- "panel.annotation_required": "Please enter annotation text",
193
- "panel.no_records": "No records yet",
194
- "panel.sent_records": "Sent {n} records",
195
- "panel.send_records_failed": "Send failed",
196
- "panel.delete": "Delete",
197
- },
198
178
  };
199
179
  export default en;
@@ -26,16 +26,3 @@ export function tf(key, vars, lang) {
26
26
  }
27
27
  return s;
28
28
  }
29
- /** 获取面板 UI 翻译 */
30
- export function panelT(key, lang) {
31
- ensureFallback();
32
- const l = lang || getConfig().panelLang;
33
- const str = _strings[l] || _strings.en;
34
- return str?.panel[key] || _strings.en?.panel[key] || key;
35
- }
36
- /** 获取面板完整翻译对象(供注入) */
37
- export function getPanelStrings(lang) {
38
- const l = lang || getConfig().panelLang;
39
- const str = _strings[l] || _strings.en;
40
- return str?.panel || {};
41
- }
package/dist/i18n/zh.js CHANGED
@@ -13,6 +13,8 @@ const zh = {
13
13
  "cli.unknown": "未知命令: {cmd}",
14
14
  "cli.invalid_args": "参数无效 {cmd}: {msg}",
15
15
  "cli.err.timeout_invalid": "--timeout 须为正整数(毫秒,100~60000),收到:{v}",
16
+ "cli.err.profile_invalid_name": "配置名无效:{name}。要求 1~64 个字符,不含 / \\ : 及 < > \" | ? *,不以点开头,且不是 Windows 保留名(CON/PRN/AUX/NUL/COM1-9/LPT1-9)。",
17
+ "cli.err.file_outside_tmp": "拒绝读取插件临时目录之外的 @file: {path}",
16
18
  "cli.failed": "命令 {cmd} 失败: {msg}",
17
19
  "cli.cmd.navigate": "导航浏览器到 URL",
18
20
  "cli.cmd.click": "点击页面元素;可选 --timeout ms(100~60000)限定本次等待上限,超时明确报错",
@@ -58,7 +60,7 @@ const zh = {
58
60
  "cli.cmd.read_record_content": "按 id 读取批注记录",
59
61
  "cli.cmd.fake_audio": "向 fake 麦克风注入音频(tone/seq/dtmf/noise/audio/ambient/stop)",
60
62
  "cli.cmd.fake_video": "向 fake 摄像头注入画面(image/video/auto/stop)",
61
- "cli.cmd.profile": "列出/切换/删除用户配置(--set <name> 重启浏览器;--delete 删除非 default、非当前激活配置)",
63
+ "cli.cmd.profile": "列出/切换/删除用户配置(--set <name> 切换默认配置,影响后续新会话、不重启运行中的浏览器;--delete 删除非 default、非当前激活配置)",
62
64
  "cli.cmd.exports": "显示导出目录 + Edge/Chrome 密码/书签导出引导",
63
65
  "cli.cmd.lookup": "在密码 CSV 中查找站点,返回 @file: 路径(密码不进上下文)",
64
66
  // ---- 诊断型 note(命令输出的追加说明) ----
@@ -95,6 +97,8 @@ const zh = {
95
97
  "cli.out.device_applied": "已应用设备预设: {name}({w}x{h} 内容区)\nUser-Agent: {ua}",
96
98
  "cli.out.devtools_open": "开发者工具已打开",
97
99
  "cli.out.devtools_closed": "开发者工具已关闭",
100
+ // Windows(wry)无法真正关闭 DevTools:如实反馈,提示用 F12 手动切换
101
+ "cli.out.devtools_unsupported": "当前平台不支持关闭 DevTools(wry 限制);可用 F12 手动切换",
98
102
  "cli.out.reload": "页面已刷新: {url}",
99
103
  // 后端返回体无 url(Rust 侧标签无最后导航 URL)时的降级文案,避免输出 undefined
100
104
  "cli.out.reload_nourl": "页面已刷新",
@@ -107,9 +111,9 @@ const zh = {
107
111
  "cli.out.click_switch_tab": "已点击 {sel},当前 URL: {url}",
108
112
  "cli.out.iframe_click": "已在 iframe 内点击",
109
113
  "cli.out.iframe_fill": "已在 iframe 内填写",
110
- "cli.out.status.not_running": "浏览器未运行。\nbt-shell: {bin}\n(执行任意其它工具会自动启动;也可用 open_window 显式启动。若已手动关闭,请用 open_window)",
114
+ "cli.out.status.not_running": "浏览器未运行。\nbt-shell: {bin}\n需要时请调用 open_window 打开(其它工具不会自动重开)。",
111
115
  "cli.out.status.installing": "正在安装 {list}。",
112
- "cli.out.status.not_open": "浏览器未打开。请用 command=open_window 或 navigate。",
116
+ "cli.out.status.not_open": "浏览器在运行但没有窗口。请调用 open_window 打开。",
113
117
  "cli.out.status.open": "浏览器已打开\n标题: {title}\nURL: {url}\n标签数: {n}",
114
118
  "cli.out.tabs_none": "(无标签)",
115
119
  "cli.out.tabs_header": "标签({n}):",
@@ -139,7 +143,7 @@ const zh = {
139
143
  "cli.out.profile_deleted": "已删除配置: {name}",
140
144
  "cli.out.profile_switched": "已切换默认配置: {name}(仅影响后续新会话的浏览器;正在运行的会话不受影响)",
141
145
  "cli.out.profiles_none": "(暂无配置)",
142
- "cli.out.profiles_header": "配置:\n{list}\n\n当前: {active}\n切换: profile --set <name>(重启浏览器,当前标签会丢失)\n删除: profile --delete <name>(非 default、非当前激活)",
146
+ "cli.out.profiles_header": "配置:\n{list}\n\n当前: {active}\n切换: profile --set <name>(影响后续新会话,不重启运行中的浏览器)\n删除: profile --delete <name>(非 default、非当前激活)",
143
147
  "cli.out.exports": "导出目录: {dir}\n\n如何从 Edge/Chrome 导出:\n 密码: 设置 → 个人资料 → 密码 → ⋯ → 导出密码(CSV)\n 书签: 设置 → 个人资料 → 书签 → ⋯ → 导出(HTML)\n把导出的文件放到上面的目录,然后模型可以直接读取。\n\n不把密码读进上下文的用法:\n lookup --csv <file.csv> --url <site>\n fill --selector <input> --value @file:<path>",
144
148
  "cli.out.lookup_usage": "用法: lookup --csv <路径> --url <站点>",
145
149
  "cli.out.lookup_found": "找到: {user} @ {url}\n用法: fill --selector <input> --value @file:{tmp}\n(密码在临时文件中,用完即删)",
@@ -159,41 +163,17 @@ const zh = {
159
163
  "client.attach_timeout": "外部 bt-shell 在 {url} 未就绪(超时)。请检查 BT_SHELL_URL/BT_SHELL_PORT,且 shell 正在运行。",
160
164
  "client.not_configured": "服务未配置",
161
165
  "client.service_error": "服务错误",
166
+ "client.auth_rejected": "本地浏览器 API 拒绝鉴权(HTTP 401/403)。请调用 open_window 重新打开浏览器。",
167
+ "client.bad_response": "浏览器服务返回了无法解析的响应(非 JSON)。未判定为已关闭,请重试该调用。",
162
168
  "client.bt_shell_path_missing": "BT_SHELL_PATH 指向的二进制不存在(路径见环境变量配置)",
163
169
  "client.spawn_failed": "bt-shell 进程启动失败(请稍后经 bt_cli 重试;勿直接执行二进制文件)",
164
- "client.session_closed_during_start": "该会话在浏览器启动过程中被关闭,实例已回收(未注册)。如需浏览器请重新调用工具。",
170
+ "client.session_closed_during_start": "启动期间已收到关闭指令,该浏览器实例已终止。如需使用请调用 open_window。",
165
171
  "client.attach_gone": "附着的外部 bt-shell 在 {url} 已断开(附着模式不接管进程,请自行重启该 shell)。",
172
+ "client.attach_need_token": "附着模式需要鉴权令牌:请设置环境变量 BT_SHELL_TOKEN,并让外部 bt-shell 用同一令牌启动(启动参数 --token <token>,或设置同值的 BT_SHELL_TOKEN)。",
173
+ "client.attach_bad_token": "外部 shell 拒绝鉴权:BT_SHELL_TOKEN 与 shell 启动时的 --token/BT_SHELL_TOKEN 不一致。",
166
174
  "client.browser_closed": "浏览器已关闭。请先调用 open_window 打开后再试。",
167
175
  "tool.set_media_mode.desc": "切换摄像头/麦克风模式:simulate(模拟设备,默认)或 real(真实设备,无设备自动回退模拟)。不带参数时查询当前模式。",
168
176
  "tool.set_media_mode.arg.mode": "模式:simulate 或 real(省略则查询当前)",
169
177
  },
170
- panel: {
171
- "panel.title": "工具面板",
172
- "panel.pick_hint": "悬停高亮页面元素\n点击选中进行标注",
173
- "panel.annotation_placeholder": "添加批注...",
174
- "panel.action_none": "无操作",
175
- "panel.action_click": "点击",
176
- "panel.action_fill": "填写",
177
- "panel.action_value_placeholder": "值...",
178
- "panel.send": "发送",
179
- "panel.send_all": "发送全部",
180
- "panel.close": "关闭",
181
- "panel.send_failed": "发送失败",
182
- "panel.annotate": "批注",
183
- "panel.screenshot_btn": "截图",
184
- "panel.screenshot_sent": "截图已发送",
185
- "panel.screenshot_note": "添加说明...",
186
- "panel.screenshot_hint": "双击截取全屏",
187
- "panel.screenshot_stored": "截图已保存",
188
- "panel.screenshot_failed": "截图失败",
189
- "panel.cancel": "取消",
190
- "panel.confirm": "确认",
191
- "panel.annotation_required": "请输入批注文字",
192
- "panel.annotation_stored": "批注已保存",
193
- "panel.no_records": "当前记录为空",
194
- "panel.sent_records": "已发送 {n} 条记录",
195
- "panel.send_records_failed": "发送失败",
196
- "panel.delete": "删除",
197
- },
198
178
  };
199
179
  export default zh;
package/dist/index.js CHANGED
@@ -2,13 +2,14 @@ import { readFileSync, writeFileSync, readdirSync, unlinkSync, mkdirSync, rmSync
2
2
  import { resolve } from "path";
3
3
  import stringArgv from "string-argv";
4
4
  import { parseArgs } from "node:util";
5
- import { loadConfig, getConfig, getBrowsersDir, getProfilesDir, getProfileDir, getExportsDir, getTmpDir, getActiveProfile, setActiveProfile, getSessionDataDir, getSessionTmpDir, } from "./config/index.js";
5
+ import { loadConfig, getConfig, getBrowsersDir, getProfilesDir, getExportsDir, getTmpDir, getActiveProfile, setActiveProfile, getSessionDataDir, getSessionTmpDir, getSessionsDir, resolveProfilePath, isInsideDir, } from "./config/index.js";
6
6
  import { registerLocale, tf } from "./i18n/index.js";
7
7
  import en from "./i18n/en.js";
8
8
  import zh from "./i18n/zh.js";
9
- import { configureService, setAppDirectory, setServiceReadyHandler, setSessionIdResolver, setTitleResolver, resolveSessionId, openWindow, isRunning, closeSession, closeAllSessions, clearClosedState, service, probeStatus, } from "./client.js";
9
+ import { configureService, setAppDirectory, setServiceReadyHandler, setSessionIdResolver, setTitleResolver, resolveSessionId, openWindow, isRunning, isStarting, closeSession, closeAllSessions, clearClosedState, service, probeStatus, clearAttachNotifyForSid, } from "./client.js";
10
10
  import { startNotifyServer } from "./notify-server.js";
11
11
  import { startDownload, getBinaryStatus, describeBinaryStatus } from "./binary.js";
12
+ import { sanitizeForModel } from "./util/sanitize.js";
12
13
  import { tool } from "@opencode-ai/plugin";
13
14
  import { log } from "./logger.js";
14
15
  import { createSessionIDCache, extractSessionIDFromEvent } from "./session-id.js";
@@ -124,11 +125,23 @@ const COMMANDS = {
124
125
  const r = await service.device({ name: a.name });
125
126
  return _t("cli.out.device_applied", { name: r.device, w: r.width, h: r.height, ua: r.ua });
126
127
  } },
127
- devtools: { usage: "[--action]", descKey: "cli.cmd.devtools", args: [{ flag: "action" }], run: async (a) => { const r = await service.devtools({ action: a.action || "toggle" }); return r.open ? _t("cli.out.devtools_open") : _t("cli.out.devtools_closed"); } },
128
+ devtools: { usage: "[--action]", descKey: "cli.cmd.devtools", args: [{ flag: "action" }], run: async (a) => {
129
+ const r = await service.devtools({ action: a.action || "toggle" });
130
+ // supported=false:该平台无法真正关闭(Windows/wry 空实现)→ 如实提示,不接受误导性的「已关闭」
131
+ if (r?.supported === false)
132
+ return _t("cli.out.devtools_unsupported");
133
+ return r.open ? _t("cli.out.devtools_open") : _t("cli.out.devtools_closed");
134
+ } },
128
135
  reload: { usage: "", descKey: "cli.cmd.reload", run: async (a) => { const r = await service.reload(sidArgs(a)); return r?.url ? _t("cli.out.reload", { url: r.url }) : _t("cli.out.reload_nourl"); } },
129
136
  open_window: { usage: "", descKey: "cli.cmd.open_window", run: async (a) => { await openWindow(sidOf(a)); return _t("cli.out.open_window"); } },
130
- close: { usage: "", descKey: "cli.cmd.close", run: async (a) => { const sid = sidOf(a); if (!isRunning(sid))
131
- return _t("cli.out.close_already"); await closeSession(sid); return _t("cli.out.close_done"); } },
137
+ close: { usage: "", descKey: "cli.cmd.close", run: async (a) => {
138
+ const sid = sidOf(a);
139
+ // 运行中或**启动中**都算「有实例可关」:启动中的实例由 closeSession 置 closedSids,启动链随后自毁
140
+ if (!isRunning(sid) && !isStarting(sid))
141
+ return _t("cli.out.close_already");
142
+ await closeSession(sid);
143
+ return _t("cli.out.close_done");
144
+ } },
132
145
  show_notification: { usage: "--message [--type]", descKey: "cli.cmd.show_notification", args: [{ flag: "message" }, { flag: "type" }], run: async (a) => { await service.notify(a); return _t("cli.out.notify_shown"); } },
133
146
  scroll: { usage: "[--direction --amount]", descKey: "cli.cmd.scroll", args: [{ flag: "direction" }, { flag: "amount" }], run: async (a) => { const r = await service.scroll(a); return _t("cli.out.scroll", { dir: a.direction || "down", n: a.amount || 300 }) + stableNote(r); } },
134
147
  wait_for_selector: { usage: "--selector [--timeout ms]", descKey: "cli.cmd.wait_for_selector", args: [{ flag: "selector" }, { flag: "timeout" }], run: async (a) => { const tn = timeoutNote(a); await service.waitForSelector(a); return _t("cli.out.wait_appeared") + tn; } },
@@ -173,7 +186,7 @@ const COMMANDS = {
173
186
  return _t("cli.out.no_records");
174
187
  } } },
175
188
  read_record_content: { usage: "--id", descKey: "cli.cmd.read_record_content", args: [{ flag: "id" }], run: async (a) => { try {
176
- const records = await service.annotateRecords(sidArgs(a));
189
+ const records = await service.annotateRecords({ ...sidArgs(a), includeImages: true });
177
190
  const rec = (records || []).find((r) => r.index === a.id);
178
191
  if (!rec)
179
192
  return _t("cli.out.record_not_found", { id: a.id });
@@ -191,30 +204,46 @@ const COMMANDS = {
191
204
  fake_audio: { usage: "--kind [--data --freq --durMs --notes --digits --loop]", descKey: "cli.cmd.fake_audio", args: [{ flag: "kind" }, { flag: "data" }, { flag: "freq" }, { flag: "durMs" }, { flag: "notes" }, { flag: "digits" }, { flag: "loop", type: "boolean" }], run: async (a) => { const r = await service.mediaAudio(a); return _t("cli.out.fake_audio", { injected: r.injected }); } },
192
205
  fake_video: { usage: "--kind [--data --url --loop]", descKey: "cli.cmd.fake_video", args: [{ flag: "kind" }, { flag: "data" }, { flag: "url" }, { flag: "loop", type: "boolean" }], run: async (a) => { const r = await service.mediaVideo(a); return _t("cli.out.fake_video", { injected: r.injected }); } },
193
206
  profile: { usage: "[--set <name> | --delete <name>]", descKey: "cli.cmd.profile", args: [{ flag: "set" }, { flag: "delete" }], run: async (a) => {
194
- mkdirSync(getProfilesDir(), { recursive: true });
195
207
  const active = getActiveProfile();
208
+ /** 解析 profile 路径;名字非法时返回错误文案(不 mkdir、不 rm) */
209
+ const resolveOrError = (raw) => {
210
+ const name = String(raw);
211
+ try {
212
+ return { dir: resolveProfilePath(name), name };
213
+ }
214
+ catch {
215
+ return { name, err: _t("cli.err.profile_invalid_name", { name }) };
216
+ }
217
+ };
196
218
  if (a.delete) {
197
- const name = String(a.delete);
219
+ const r = resolveOrError(a.delete);
220
+ if (r.err)
221
+ return r.err;
222
+ const name = r.name;
198
223
  if (name === "default")
199
224
  return _t("cli.out.profile_no_delete_default");
200
225
  if (name === active)
201
226
  return _t("cli.out.profile_no_delete_active");
202
- const dir = getProfileDir(name);
227
+ const dir = r.dir;
203
228
  if (!existsSync(dir))
204
229
  return _t("cli.out.profile_not_found", { name });
205
230
  rmSync(dir, { recursive: true, force: true });
206
231
  return _t("cli.out.profile_deleted", { name });
207
232
  }
208
233
  if (a.set) {
209
- const name = String(a.set);
234
+ const r = resolveOrError(a.set);
235
+ if (r.err)
236
+ return r.err;
237
+ const name = r.name;
210
238
  // 目标配置目录不存在则创建(允许 "profile --set <新名>" 直接新建并切换)
211
- mkdirSync(getProfileDir(name), { recursive: true });
239
+ mkdirSync(r.dir, { recursive: true });
212
240
  setActiveProfile(name);
213
241
  // 1.9.0 会话隔离:profile 作用域改为「影响**后续新会话**的数据根(sessions/<profile>/<sid>)」。
214
242
  // **不再重启共享 shell** —— 运行中的会话各自持有独立实例,切换互不打扰(旧实现会杀掉全局唯一窗口)。
215
243
  return _t("cli.out.profile_switched", { name });
216
244
  }
217
245
  // 列出 user-data 下的配置目录
246
+ mkdirSync(getProfilesDir(), { recursive: true });
218
247
  const dirs = readdirSync(getProfilesDir(), { withFileTypes: true })
219
248
  .filter((d) => d.isDirectory())
220
249
  .map((d) => d.name);
@@ -303,9 +332,7 @@ function splitCsvLine(line) {
303
332
  out.push(cur);
304
333
  return out;
305
334
  }
306
- export const opencodeBrowserTool = async ({ client, worktree, directory, serverUrl }) => {
307
- // 插件上下文(仅用于诊断:定位 session.list() 为空时是哪个实例/目录)
308
- pluginCtx = { directory: directory || "", worktree: worktree || "", serverUrl: serverUrl ? String(serverUrl) : "" };
335
+ export const opencodeBrowserTool = async ({ client, worktree, directory }) => {
309
336
  // 供 resolveShellBinary 定位本地 Rust 构建(publish-local 到缓存目录后仍能找到仓库)
310
337
  setAppDirectory(directory || "");
311
338
  registerLocale("en", en);
@@ -344,12 +371,16 @@ export const opencodeBrowserTool = async ({ client, worktree, directory, serverU
344
371
  if (event.type === "session.deleted") {
345
372
  // 删除会话(1.9.0 语义升级):清钩子缓存 + **回收该会话自己的浏览器实例**。
346
373
  // 仍是「绝不因删除而 spawn」:closeSession 只在注册表里有该 sid 时才动进程,
347
- // 没有实例就直接返回(不会再走 callApi → ensureService 那条会弹窗的老路)。
374
+ // 没有实例就直接返回(不会再走 callApi → ensureInstance 那条会弹窗的老路)。
348
375
  const delId = extractSessionIDFromEvent(event);
349
376
  if (delId) {
350
377
  sessionCache.clearIf(delId);
351
378
  await closeSession(delId);
352
379
  clearClosedState(delId);
380
+ // 清该 sid 的附着 notify 记录(附着模式共享 shell,避免残留 key 无限增长)
381
+ clearAttachNotifyForSid(delId);
382
+ // 回收该会话的数据目录(P1:否则退出后磁盘目录永不释放)
383
+ removeSessionDataDir(delId);
353
384
  }
354
385
  return;
355
386
  }
@@ -389,26 +420,40 @@ export const opencodeBrowserTool = async ({ client, worktree, directory, serverU
389
420
  params = parseFlagArgs(tokens, def);
390
421
  }
391
422
  catch (e) {
392
- return `${_t("cli.invalid_args").replace("{cmd}", cmdName).replace("{msg}", e.message)}\n\nUsage: bt_cli({ args: "${cmdName} ${def.usage}" })`;
423
+ // 解析错误可能夹带底层异常文本:进模型前先脱敏(用法提示本身不含路径)
424
+ return `${_t("cli.invalid_args").replace("{cmd}", cmdName).replace("{msg}", sanitizeForModel(e?.message || String(e)))}\n\nUsage: bt_cli({ args: "${cmdName} ${def.usage}" })`;
393
425
  }
394
426
  }
395
427
  // @file: 引用解析:值以 @file:<path> 开头时读文件内容作为实际值
396
428
  // (密码等敏感值不进 LLM 上下文,如 fill --value @file:C:\...\secret.tmp)
397
- // 仅删除临时目录(getTmpDir)内的文件,避免误删用户文件
398
- const tmpDir = resolve(getTmpDir());
429
+ // 安全边界:只允许读全局 tmp(getTmpDir)或**该会话** tmp(getSessionTmpDir)之内的文件;
430
+ // 其余路径一律拒绝(不读取),避免模型借助 @file: 读取任意本地文件。
431
+ // sid 形态校验:resolveSessionId 会原样返回外部传入的 sessionID,任意字符串(含 .. 、路径分隔符)
432
+ // 会把 getSessionTmpDir 带到 sessions 目录之外,从而左右 allowed dirs。不匹配 SESSION_SID_RE
433
+ // 一律回退 "default" 桶(而非 resolveSessionId(""):后者仍可能返回同一个非法的钩子缓存值)。
434
+ // "default" 本身合法,getSessionTmpDir("default") = sessions/<profile>/default/tmp,必在 sessions 内。
435
+ const fileSidRaw = resolveSessionId(context?.sessionID || "");
436
+ const fileSid = SESSION_SID_RE.test(fileSidRaw) ? fileSidRaw : "default";
437
+ const globalTmpDir = getTmpDir();
438
+ const allowedTmpDirs = [globalTmpDir, getSessionTmpDir(fileSid)];
399
439
  for (const key of Object.keys(params)) {
400
440
  const v = params[key];
401
441
  if (typeof v === "string" && v.startsWith("@file:")) {
402
442
  const p = v.slice(6);
443
+ const abs = resolve(p);
444
+ if (!allowedTmpDirs.some((d) => isInsideDir(abs, d))) {
445
+ return _t("cli.err.file_outside_tmp", { path: p });
446
+ }
403
447
  try {
404
- params[key] = readFileSync(p, "utf-8").replace(/\r?\n$/, "");
405
- // 用完即删(仅限 lookup 生成的临时密码文件)
406
- if (resolve(p).startsWith(tmpDir)) {
407
- unlinkSync(p);
448
+ params[key] = readFileSync(abs, "utf-8").replace(/\r?\n$/, "");
449
+ // 用完即删(仅限 lookup 生成的全局 tmp 临时密码文件;会话 tmp 内的截图等保留)
450
+ if (isInsideDir(abs, globalTmpDir)) {
451
+ unlinkSync(abs);
408
452
  }
409
453
  }
410
454
  catch (e) {
411
- return _t("cli.read_file_failed", { path: p, msg: e.message });
455
+ // {path} 是模型自己传入的值,保持原样;{msg} 来自 fs 错误,必须脱敏
456
+ return _t("cli.read_file_failed", { path: p, msg: sanitizeForModel(e?.message || String(e)) });
412
457
  }
413
458
  }
414
459
  }
@@ -420,7 +465,8 @@ export const opencodeBrowserTool = async ({ client, worktree, directory, serverU
420
465
  return await def.run(params);
421
466
  }
422
467
  catch (e) {
423
- return `${_t("cli.failed").replace("{cmd}", cmdName).replace("{msg}", e.message || e)}`;
468
+ // 命令失败可能带 fs/网络错误文本:统一脱敏后再回模型
469
+ return `${_t("cli.failed").replace("{cmd}", cmdName).replace("{msg}", sanitizeForModel(e?.message || String(e)))}`;
424
470
  }
425
471
  },
426
472
  }),
@@ -480,19 +526,15 @@ function filterDisabled(tools, disabled) {
480
526
  }
481
527
  return result;
482
528
  }
483
- /** 轮询批注发送队列:面板"发送全部"/截图"发送"后,拉取记录推送当前对话
484
- * 注意:插件函数会随会话/切目录多次执行,轮询器必须进程级单例,
485
- * 否则同一进程会累积多个 interval 空转(server 与 TUI 进程各一份,互不共享)
529
+ /** 事件驱动投递:shell 面板"发送全部"/截图"发送"后 POST 插件本地 /notify/<sid> 触发 drain
530
+ * 注意:插件函数会随会话/切目录多次执行,notify server 与 drain 状态必须进程级单例,
531
+ * 否则同一进程会累积多个监听/重复投递(server 与 TUI 进程各一份,互不共享)
486
532
  */
487
533
  let annotateClient = null;
488
534
  /** drain 进行中(按 sid 隔离:会话 A 的 drain 不会挡住会话 B 的投递) */
489
535
  const drainingSid = new Set();
490
536
  /** 最近一次见到的会话 id 缓存(来自 event/chat.message/tool.execute.before 钩子) */
491
537
  const sessionCache = createSessionIDCache();
492
- /** 已记录过的 sid(避免重复刷屏) */
493
- let lastLoggedSessionID = "";
494
- /** 插件上下文(诊断用) */
495
- let pluginCtx = { directory: "", worktree: "", serverUrl: "" };
496
538
  /** 把截图 base64 落盘为临时 PNG,返回路径(失败返回 null);用于发送时保留图片与给出可读路径
497
539
  * 1.9.0:落盘到**该会话**的临时目录 sessions/<profile>/<sid>/tmp(不再与其它会话共享全局 tmp) */
498
540
  function saveShotImage(log, sid, index, b64) {
@@ -508,6 +550,72 @@ function saveShotImage(log, sid, index, b64) {
508
550
  return null;
509
551
  }
510
552
  }
553
+ /** 合法会话 id 形态(opencode 生成的 sid);不匹配则不删目录,避免意外路径 */
554
+ const SESSION_SID_RE = /^[A-Za-z0-9_-]{1,128}$/;
555
+ /** 会话目录删除失败后的重试延迟(ms;Windows 上文件常被短暂占用) */
556
+ const SESSION_DIR_RETRY_MS = 800;
557
+ /** 同步删除某 sid 的数据目录(失败仅记录,由调用方决定是否重试) */
558
+ function rmSessionDir(dir) {
559
+ try {
560
+ rmSync(dir, { recursive: true, force: true });
561
+ log.info(`[session] removed data dir for deleted session: ${dir}`);
562
+ return true;
563
+ }
564
+ catch (e) {
565
+ log.error(`[session] failed to remove data dir ${dir}: ${e.message}`, e);
566
+ return false;
567
+ }
568
+ }
569
+ /**
570
+ * 会话删除后回收**所有 profile 下**属于该 sid 的数据目录(sessions/<profile>/<sid>)。
571
+ * 用户切换过 activeProfile 时,老 profile 目录里的同名会话也要清掉,故枚举 sessions 根的直接子目录。
572
+ * 约束:sid 必须合法;每个目标必须在 getSessionsDir() 之内,且不等于 sessions 根或 profile 根
573
+ * (只删名为 <sid> 的目录,profile 目录本身永不删除)。
574
+ * Windows 文件锁导致失败时 800ms 后对失败列表重试一次;全部成功则不设定时器。
575
+ */
576
+ function removeSessionDataDir(sid) {
577
+ if (!SESSION_SID_RE.test(sid)) {
578
+ log.error(`[session] skip data dir cleanup: invalid session id (${sid.length} chars)`);
579
+ return;
580
+ }
581
+ const sessionsDir = getSessionsDir();
582
+ // 枚举直接子目录:每个 = 一个 profile;读不到(根不存在/无权限)视为无可回收目录
583
+ let profileNames;
584
+ try {
585
+ profileNames = readdirSync(sessionsDir, { withFileTypes: true })
586
+ .filter((e) => e.isDirectory())
587
+ .map((e) => e.name);
588
+ }
589
+ catch {
590
+ return;
591
+ }
592
+ const targets = [];
593
+ for (const name of profileNames) {
594
+ const profileDir = resolve(sessionsDir, name);
595
+ const target = resolve(profileDir, sid);
596
+ // 路径断言:仍在 sessions 根内,且不是 sessions 根/profile 根本身
597
+ if (!isInsideDir(target, sessionsDir) || target === sessionsDir || target === profileDir)
598
+ continue;
599
+ if (!existsSync(target))
600
+ continue;
601
+ targets.push(target);
602
+ }
603
+ if (!targets.length)
604
+ return;
605
+ const failed = targets.filter((t) => !rmSessionDir(t));
606
+ if (!failed.length) {
607
+ log.info(`[session] cleaned data dir for sid=${sid} across ${targets.length} profile dir(s)`);
608
+ return;
609
+ }
610
+ const timer = setTimeout(() => {
611
+ const stillFailing = failed.filter((t) => !rmSessionDir(t));
612
+ if (stillFailing.length) {
613
+ log.error(`[session] data dir cleanup still failing after retry (sid=${sid}): ${stillFailing.length} dir(s)`);
614
+ }
615
+ }, SESSION_DIR_RETRY_MS);
616
+ // 不让重试定时器拖住进程退出
617
+ timer.unref?.();
618
+ }
511
619
  /** 事件驱动投递:插件本地监听 shell 通知(收到即 drain),不再 setInterval 轮询 */
512
620
  function setupAnnotateDelivery(client) {
513
621
  // 更新 client 引用(插件重载后使用最新 client)