@xiaoqiong0v0/opencode-browser-tool 1.11.1 → 1.12.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/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { readFileSync, writeFileSync, readdirSync, unlinkSync, mkdirSync, rmSync, existsSync } from "fs";
1
+ import { readFileSync, writeFileSync, readdirSync, unlinkSync, mkdirSync, rmSync, existsSync, statSync } from "fs";
2
2
  import { resolve } from "path";
3
3
  import stringArgv from "string-argv";
4
4
  import { parseArgs } from "node:util";
@@ -6,10 +6,14 @@ import { loadConfig, getConfig, getBrowsersDir, getProfilesDir, getExportsDir, g
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, isStarting, closeSession, closeAllSessions, clearClosedState, service, probeStatus, clearAttachNotifyForSid, } from "./client.js";
9
+ import { configureService, setAppDirectory, getAppDirectory, 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
12
  import { sanitizeForModel } from "./util/sanitize.js";
13
+ import { EVAL_ITEM_MAX_BYTES, EVAL_TOTAL_MAX_BYTES, classifyEvalArgs, runEvalItems, } from "./util/eval-items.js";
14
+ import { INJECT_RULE_MAX_BYTES, buildInjectItems, formatInjectAdd, formatInjectList, formatInjectTest, injectAddIssue, injectRuleLimitIssue, normalizeInjectAction, } from "./util/inject-rules.js";
15
+ import { formatConsoleItems, formatNetworkItems, renderLogText, } from "./util/log-format.js";
16
+ import { TYPE_TEXT_MAX_BYTES, resolveTypeText, typeTextIssue, formatTypeOutput, } from "./util/type-text.js";
13
17
  import { tool } from "@opencode-ai/plugin";
14
18
  import { log } from "./logger.js";
15
19
  import { createSessionIDCache, extractSessionIDFromEvent } from "./session-id.js";
@@ -83,6 +87,318 @@ function timeoutNote(a) {
83
87
  a.timeout = c;
84
88
  return c === n ? "" : _t("cli.note.timeout_clamped", { ms: c });
85
89
  }
90
+ /** evaluate 请求体:脚本 + 会话 id + 已钳制的 timeout(CLI 专用 flag 不下发) */
91
+ function evalPayload(a, script) {
92
+ const p = { script, _sessionId: a._sessionId };
93
+ if (a.timeout !== undefined)
94
+ p.timeout = a.timeout;
95
+ return p;
96
+ }
97
+ /** `@file:` 允许目录:全局 tmp + 指定会话 tmp(sid 形态非法时回落 default 桶,防止路径越界) */
98
+ function allowedFileDirs(browserSid) {
99
+ const fileSid = SESSION_SID_RE.test(browserSid) ? browserSid : "default";
100
+ const globalTmpDir = getTmpDir();
101
+ return { globalTmpDir, dirs: [globalTmpDir, getSessionTmpDir(fileSid)] };
102
+ }
103
+ /** `evaluate` 文件项错误文案键 */
104
+ const EVAL_FILE_KEYS = {
105
+ outside: "cli.err.eval_file_outside",
106
+ tooLarge: "cli.err.eval_file_too_large",
107
+ totalTooLarge: "cli.err.eval_total_too_large",
108
+ notAFile: "cli.err.eval_not_a_file",
109
+ readFailed: "cli.read_file_failed",
110
+ };
111
+ /** `inject` 文件项错误文案键(读取/containment 逻辑复用 evaluate,上限换为单规则口径) */
112
+ const INJECT_FILE_KEYS = {
113
+ outside: "cli.err.inject_file_outside",
114
+ tooLarge: "cli.err.inject_file_too_large",
115
+ totalTooLarge: "cli.err.inject_rule_too_large",
116
+ notAFile: "cli.err.eval_not_a_file",
117
+ readFailed: "cli.err.inject_read_failed",
118
+ };
119
+ /** `type --text @file:` 错误文案键(读取/containment 逻辑复用 evaluate,文案前缀换成 type) */
120
+ const TYPE_FILE_KEYS = {
121
+ outside: "cli.err.type_file_outside",
122
+ tooLarge: "cli.err.type_file_too_large",
123
+ totalTooLarge: "cli.err.type_file_total_too_large",
124
+ notAFile: "cli.err.eval_not_a_file",
125
+ readFailed: "cli.err.type_read_failed",
126
+ };
127
+ /**
128
+ * 读取一个文件项(evaluate 的 `@file:<path>` / inject 的 `--file <path>`)。
129
+ *
130
+ * 安全边界:先做 containment 校验(工作区目录 / 全局 tmp / 会话 tmp 之内),不通过**直接拒绝且不读取**;
131
+ * 相对路径的基准是**工作区目录**(不是插件 cwd)。再校验单文件 ≤256KB、合计 ≤`totalMaxBytes`
132
+ * (默认 1MB;inject 传单规则上限)。
133
+ *
134
+ * @param pathArg 模型传入的路径(原样用于文案回显)
135
+ * @param ctx workspaceDir=工作区目录(可能为空)、allowedDirs=允许目录、usedBytes=已累计字节、
136
+ * totalMaxBytes=合计上限(缺省 `EVAL_TOTAL_MAX_BYTES`)
137
+ * @param keys 错误文案键集合(缺省 evaluate 的一套)
138
+ * @returns 读到的脚本文本与字节数,或错误文案
139
+ */
140
+ function readEvalFile(pathArg, ctx, keys = EVAL_FILE_KEYS) {
141
+ const abs = ctx.workspaceDir ? resolve(ctx.workspaceDir, pathArg) : resolve(pathArg);
142
+ if (!ctx.allowedDirs.some((d) => isInsideDir(abs, d))) {
143
+ return { error: _t(keys.outside, { path: pathArg }) };
144
+ }
145
+ const totalMax = ctx.totalMaxBytes && ctx.totalMaxBytes > 0 ? ctx.totalMaxBytes : EVAL_TOTAL_MAX_BYTES;
146
+ let size = 0;
147
+ try {
148
+ const st = statSync(abs);
149
+ if (!st.isFile()) {
150
+ return { error: _t(keys.readFailed, { path: pathArg, msg: _t(keys.notAFile) }) };
151
+ }
152
+ size = st.size;
153
+ }
154
+ catch (e) {
155
+ return { error: _t(keys.readFailed, { path: pathArg, msg: sanitizeForModel(e?.message || String(e)) }) };
156
+ }
157
+ if (size > EVAL_ITEM_MAX_BYTES) {
158
+ return { error: _t(keys.tooLarge, { path: pathArg, kb: EVAL_ITEM_MAX_BYTES / 1024 }) };
159
+ }
160
+ if (ctx.usedBytes + size > totalMax) {
161
+ return { error: _t(keys.totalTooLarge, { path: pathArg, kb: totalMax / 1024 }) };
162
+ }
163
+ try {
164
+ const buf = readFileSync(abs);
165
+ // stat 与 read 之间文件可能变大:以实际读到的字节数再判一次总量
166
+ if (ctx.usedBytes + buf.byteLength > totalMax) {
167
+ return { error: _t(keys.totalTooLarge, { path: pathArg, kb: totalMax / 1024 }) };
168
+ }
169
+ return { content: buf.toString("utf-8"), bytes: buf.byteLength };
170
+ }
171
+ catch (e) {
172
+ return { error: _t(keys.readFailed, { path: pathArg, msg: sanitizeForModel(e?.message || String(e)) }) };
173
+ }
174
+ }
175
+ /**
176
+ * `evaluate` 多客户端项的插件侧装配:把 IO(文件读取 / 浏览器调用)注入 `runEvalItems`。
177
+ *
178
+ * - 文件项在执行前统一读入(累计字节数受 `EVAL_TOTAL_MAX_BYTES` 约束):任一项失败整次不执行脚本
179
+ * - `--continue-on-error` 决定某项失败后是否继续执行后续项
180
+ *
181
+ * @param a 已解析命令参数(`_sessionId` / `timeout` / `continue-on-error`)
182
+ * @param items 有序执行项
183
+ * @returns 报告文本(不含 timeout 提示,由调用方追加)
184
+ */
185
+ async function runEvalCommand(a, items) {
186
+ const workspaceDir = getAppDirectory();
187
+ const { dirs: tmpDirs } = allowedFileDirs(a._sessionId);
188
+ const allowedDirs = workspaceDir ? [...tmpDirs, workspaceDir] : tmpDirs;
189
+ let usedBytes = 0;
190
+ return runEvalItems(items, {
191
+ readFile: (path) => {
192
+ const read = readEvalFile(path, { workspaceDir, allowedDirs, usedBytes });
193
+ if (!("error" in read))
194
+ usedBytes += read.bytes;
195
+ return read;
196
+ },
197
+ evaluate: (script) => service.evaluate(evalPayload(a, script)),
198
+ continued: a["continue-on-error"] === true,
199
+ });
200
+ }
201
+ /** 把 `parseArgs` 的 `multiple` 结果(单值 / 数组 / 未传)统一成非空字符串数组 */
202
+ function toStringList(v) {
203
+ if (v === undefined || v === null)
204
+ return [];
205
+ const arr = Array.isArray(v) ? v : [v];
206
+ return arr.map((x) => String(x)).filter((s) => s.length > 0);
207
+ }
208
+ /**
209
+ * 读取 inject 的文件项(复用 evaluate 的 containment / 体积校验,仅换文案与单规则上限)。
210
+ *
211
+ * @param a 已解析命令参数(用 `_sessionId` 定位会话 tmp 桶)
212
+ * @param files `--file` 路径列表(按传入顺序)
213
+ * @returns 读入成功的文件源列表,或可直接回模型的错误文案
214
+ */
215
+ function readInjectFiles(a, files) {
216
+ const workspaceDir = getAppDirectory();
217
+ const { dirs: tmpDirs } = allowedFileDirs(a._sessionId);
218
+ const allowedDirs = workspaceDir ? [...tmpDirs, workspaceDir] : tmpDirs;
219
+ const sources = [];
220
+ let usedBytes = 0;
221
+ for (const path of files) {
222
+ // 单规则上限 = items 合计上限(契约 256 KiB),故这里把「合计」直接按其判定
223
+ const read = readEvalFile(path, { workspaceDir, allowedDirs, usedBytes, totalMaxBytes: INJECT_RULE_MAX_BYTES }, INJECT_FILE_KEYS);
224
+ if ("error" in read)
225
+ return { error: read.error };
226
+ usedBytes += read.bytes;
227
+ sources.push({ path, code: read.content });
228
+ }
229
+ return { sources };
230
+ }
231
+ /**
232
+ * `inject add`:读文件 → 构造 items → 校验上限 → POST `/api/inject/rules`。
233
+ *
234
+ * - `--file` 只允许工作区目录 / 插件 tmp(与 evaluate 同 containment);单条 ≤256 KiB
235
+ * - 文件内容转成 `{kind:"text", code, name:"<basename>"}`,`--text` 的 name 固定 `text`;
236
+ * Rust 只收到内容,不接触路径
237
+ * - `--disabled` 等价 `enabled:false`;`--order` 缺省时不下发(由 Rust 取默认)
238
+ *
239
+ * @param a 已解析命令参数
240
+ * @returns 回模型的单行结果文本
241
+ */
242
+ async function runInjectAdd(a) {
243
+ const match = typeof a.match === "string" ? a.match.trim() : "";
244
+ const files = toStringList(a.file);
245
+ const texts = toStringList(a.text);
246
+ const issue = injectAddIssue(match, files.length, texts.length);
247
+ if (issue === "no_match")
248
+ return _t("cli.err.inject_match_required");
249
+ if (issue === "no_items")
250
+ return _t("cli.err.inject_no_items");
251
+ const read = readInjectFiles(a, files);
252
+ if ("error" in read)
253
+ return read.error;
254
+ const items = buildInjectItems(read.sources, texts);
255
+ const over = injectRuleLimitIssue(items);
256
+ if (over)
257
+ return _t("cli.err.inject_items_too_large", { kb: over.kb });
258
+ const payload = { action: "add", match, items, enabled: a.disabled !== true };
259
+ if (a.order !== undefined)
260
+ payload.order = a.order;
261
+ const data = (await service.injectRules(payload));
262
+ return formatInjectAdd(data?.rule);
263
+ }
264
+ /**
265
+ * `inject remove|enable|disable`:按 id 变更单条规则(`--id` 必填)。
266
+ *
267
+ * @param a 已解析命令参数
268
+ * @param action 子动作
269
+ * @returns 回模型的单行结果文本
270
+ */
271
+ async function runInjectMutate(a, action) {
272
+ const id = typeof a.id === "string" ? a.id.trim() : "";
273
+ if (!id)
274
+ return _t("cli.err.inject_id_required");
275
+ const data = (await service.injectRules({ action, id }));
276
+ const n = (data?.rules ?? []).length;
277
+ const key = action === "remove" ? "cli.out.inject_removed" : action === "enable" ? "cli.out.inject_enabled" : "cli.out.inject_disabled";
278
+ return _t(key, { id, n });
279
+ }
280
+ /**
281
+ * `inject` 子命令分发(未给子动作时按只读的 `list` 处理)。
282
+ *
283
+ * @param a 已解析命令参数
284
+ * @param positionals 位置参数(第一个是子动作)
285
+ * @returns 回模型的文本
286
+ */
287
+ async function runInject(a, positionals) {
288
+ const action = normalizeInjectAction(positionals[0]);
289
+ switch (action) {
290
+ case "add":
291
+ return runInjectAdd(a);
292
+ case "list": {
293
+ const data = (await service.injectRules({ action: "list" }));
294
+ return (data?.rules ?? []).length > 0 ? formatInjectList(data) : _t("cli.out.inject_empty");
295
+ }
296
+ case "remove":
297
+ case "enable":
298
+ case "disable":
299
+ return runInjectMutate(a, action);
300
+ case "clear":
301
+ await service.injectRules({ action: "clear" });
302
+ return _t("cli.out.inject_cleared");
303
+ case "test": {
304
+ const url = typeof a.url === "string" ? a.url.trim() : "";
305
+ if (!url)
306
+ return _t("cli.err.inject_url_required");
307
+ return formatInjectTest(await service.injectTest({ url }));
308
+ }
309
+ default:
310
+ return _t("cli.err.inject_unknown_action", { action });
311
+ }
312
+ }
313
+ /**
314
+ * `type`:向当前焦点插入文本(不清空),可选先聚焦 selector、插入后回车。
315
+ *
316
+ * `--text` 支持 `@file:<path>`:走 `evaluate` 同一套读取与 containment(工作区目录 / 插件 tmp),
317
+ * 内容不进模型上下文。文本校验(空 / 超 8 KiB)在插件侧先做一次,避免把注定失败的请求发下去。
318
+ *
319
+ * @param a 已解析命令参数(`text` / `selector` / `enter` / `timeout`)
320
+ * @returns 回模型的单行结果文本
321
+ */
322
+ async function runType(a) {
323
+ const tn = timeoutNote(a);
324
+ const raw = typeof a.text === "string" ? a.text : "";
325
+ if (!raw)
326
+ return _t("cli.err.type_text_required");
327
+ const workspaceDir = getAppDirectory();
328
+ const { dirs: tmpDirs } = allowedFileDirs(a._sessionId);
329
+ const allowedDirs = workspaceDir ? [...tmpDirs, workspaceDir] : tmpDirs;
330
+ const resolved = resolveTypeText(raw, (path) => readEvalFile(path, { workspaceDir, allowedDirs, usedBytes: 0 }, TYPE_FILE_KEYS));
331
+ if ("error" in resolved)
332
+ return resolved.error;
333
+ const issue = typeTextIssue(resolved.text);
334
+ if (issue === "required")
335
+ return _t("cli.err.type_text_required");
336
+ if (issue === "too_large")
337
+ return _t("cli.err.type_text_too_large", { kb: TYPE_TEXT_MAX_BYTES / 1024 });
338
+ const selector = typeof a.selector === "string" ? a.selector : "";
339
+ const entered = a.enter === true;
340
+ const r = await service.typeText({
341
+ text: resolved.text,
342
+ selector,
343
+ enter: entered,
344
+ _sessionId: a._sessionId,
345
+ ...(a.timeout !== undefined ? { timeout: a.timeout } : {}),
346
+ });
347
+ return formatTypeOutput(r?.inserted ?? 0, selector, entered) + tn;
348
+ }
349
+ /** console_logs 请求体:只挑契约字段(CLI 专用 flag 不下发;`--no-dedupe` 等价 `--group=none`) */
350
+ function consoleLogParams(a) {
351
+ const p = { _sessionId: a._sessionId };
352
+ if (a.type !== undefined)
353
+ p.type = a.type;
354
+ if (a["no-dedupe"] === true)
355
+ p.group = "none";
356
+ else if (a.group !== undefined)
357
+ p.group = a.group;
358
+ if (a.phase !== undefined)
359
+ p.phase = a.phase;
360
+ if (a.search !== undefined)
361
+ p.search = a.search;
362
+ if (a.limit !== undefined)
363
+ p.limit = a.limit;
364
+ if (a.tab !== undefined)
365
+ p.tab = a.tab;
366
+ if (a["include-internal"] === true)
367
+ p.includeInternal = true;
368
+ if (a.clear === true)
369
+ p.clear = true;
370
+ return p;
371
+ }
372
+ /** network_logs 请求体:`--status` 纯数字转 number(契约允许 `2xx|…|N`) */
373
+ function networkLogParams(a) {
374
+ const p = { _sessionId: a._sessionId };
375
+ if (a.type !== undefined)
376
+ p.type = a.type;
377
+ if (a.status !== undefined && a.status !== "") {
378
+ p.status = /^\d+$/.test(String(a.status)) ? Number(a.status) : a.status;
379
+ }
380
+ if (a.failed === true)
381
+ p.failed = true;
382
+ if (a.phase !== undefined)
383
+ p.phase = a.phase;
384
+ if (a.search !== undefined)
385
+ p.search = a.search;
386
+ if (a["no-dedupe"] === true)
387
+ p.group = "none";
388
+ else if (a.group !== undefined)
389
+ p.group = a.group;
390
+ if (a.limit !== undefined)
391
+ p.limit = a.limit;
392
+ if (a.tab !== undefined)
393
+ p.tab = a.tab;
394
+ if (a["include-headers"] === true)
395
+ p.includeHeaders = true;
396
+ if (a["reveal-secrets"] === true)
397
+ p.revealSecrets = true;
398
+ if (a.clear === true)
399
+ p.clear = true;
400
+ return p;
401
+ }
86
402
  const COMMANDS = {
87
403
  navigate: { usage: "--url", descKey: "cli.cmd.navigate", args: [{ flag: "url" }], run: async (a) => {
88
404
  const r = await service.navigate(a);
@@ -97,6 +413,8 @@ const COMMANDS = {
97
413
  hover: { usage: "--selector [--timeout ms]", descKey: "cli.cmd.hover", args: [{ flag: "selector" }, { flag: "timeout" }], run: async (a) => { const tn = timeoutNote(a); const r = await service.hover(a); return _t("cli.out.hover") + degradedNote(r) + tn; } },
98
414
  drag: { usage: "--sourceSelector --targetSelector [--timeout ms]", descKey: "cli.cmd.drag", args: [{ flag: "sourceSelector" }, { flag: "targetSelector" }, { flag: "timeout" }], run: async (a) => { const tn = timeoutNote(a); await service.drag(a); return _t("cli.out.drag") + tn; } },
99
415
  press_key: { usage: "--key [--selector] [--timeout ms]", descKey: "cli.cmd.press_key", args: [{ flag: "key" }, { flag: "selector" }, { flag: "timeout" }], run: async (a) => { const tn = timeoutNote(a); await service.pressKey(a); return _t("cli.out.press_key", { key: a.key }) + tn; } },
416
+ // type:向当前焦点插入文本(不清空);--text 支持 @file:<path>,--enter 插入后回车
417
+ type: { usage: "--text <text|@file:path> [--selector] [--enter] [--timeout ms]", descKey: "cli.cmd.type", args: [{ flag: "text" }, { flag: "selector" }, { flag: "enter", type: "boolean" }, { flag: "timeout" }], run: async (a) => runType(a) },
100
418
  upload_file: { usage: "--selector --filePath [--timeout ms]", descKey: "cli.cmd.upload_file", args: [{ flag: "selector" }, { flag: "filePath" }, { flag: "timeout" }], run: async (a) => { const tn = timeoutNote(a); await service.uploadFile(a); return _t("cli.out.upload_file") + tn; } },
101
419
  screenshot: { usage: "[--selector] [--timeout ms]", descKey: "cli.cmd.screenshot", args: [{ flag: "selector" }, { flag: "timeout" }], run: async (a) => {
102
420
  const tn = timeoutNote(a);
@@ -106,8 +424,35 @@ const COMMANDS = {
106
424
  const note = r?.beyondViewport ? _t("cli.note.beyond") : "";
107
425
  return { output: _t("cli.out.screenshot", { where }) + note + reachedNote(r) + stableNote(r) + tn, attachments: [{ type: "file", mime: r.mime || "image/png", url: `data:${r.mime || "image/png"};base64,${r.base64}` }] };
108
426
  } },
109
- // evaluate:超时最常用(脚本 await 慢操作);超时返回明确 eval timeout 错误,不再恒 5s
110
- evaluate: { usage: "--script [--timeout ms]", descKey: "cli.cmd.evaluate", args: [{ flag: "script" }, { flag: "timeout" }], run: async (a) => { const tn = timeoutNote(a); return JSON.stringify(await service.evaluate(a), null, 2) + tn; } },
427
+ // evaluate:支持「多文件 + 内联文本混合、按顺序串行执行」;只给 --script 时保持 1.12.0 的输出格式
428
+ evaluate: {
429
+ usage: "[--script <js>] [<js-text>|@file:<path>]... [--continue-on-error] [--timeout ms]",
430
+ descKey: "cli.cmd.evaluate",
431
+ args: [{ flag: "script" }, { flag: "continue-on-error", type: "boolean" }, { flag: "timeout" }],
432
+ run: async (a, positionals) => {
433
+ const tn = timeoutNote(a);
434
+ // 旧行为:单项 --script(位置参数与它互斥,同时给会有顺序歧义 → 报错)
435
+ if (a.script !== undefined && positionals.length === 0) {
436
+ return JSON.stringify(await service.evaluate(evalPayload(a, a.script)), null, 2) + tn;
437
+ }
438
+ const parsed = classifyEvalArgs(positionals, a.script !== undefined);
439
+ if (!parsed.ok) {
440
+ return _t(parsed.reason === "script_conflict" ? "cli.err.eval_script_conflict" : "cli.err.eval_no_items");
441
+ }
442
+ return (await runEvalCommand(a, parsed.items)) + tn;
443
+ },
444
+ },
445
+ // inject:持久注入规则(插件侧契约 + Rust 端点);子动作见 usage,add 支持重复 --file/--text
446
+ inject: {
447
+ usage: "[add --match <glob|re:...> [--file <path>]... [--text <code>]... [--order N] [--disabled] | list | remove|enable|disable --id <id> | clear | test --url <url>]",
448
+ descKey: "cli.cmd.inject",
449
+ args: [
450
+ { flag: "match" }, { flag: "file", multiple: true }, { flag: "text", multiple: true },
451
+ { flag: "order" }, { flag: "disabled", type: "boolean" },
452
+ { flag: "id" }, { flag: "url" },
453
+ ],
454
+ run: async (a, positionals) => runInject(a, positionals),
455
+ },
111
456
  get_visible_text: { usage: "[--selector]", descKey: "cli.cmd.get_visible_text", args: [{ flag: "selector" }], run: async (a) => (await service.visibleText(a))?.text || _t("cli.out.no_visible_text") },
112
457
  get_visible_html: { usage: "[--selector --removeScripts --removeComments --maxLength]", descKey: "cli.cmd.get_visible_html", args: [{ flag: "selector" }, { flag: "removeScripts", type: "boolean" }, { flag: "removeComments", type: "boolean" }, { flag: "maxLength" }], run: async (a) => {
113
458
  // 宿主要求 tool 返回字符串;服务端返回对象 {html,truncated},这里取出 html 文本本体
@@ -118,7 +463,34 @@ const COMMANDS = {
118
463
  // 被截断时追加提示:html.length 即服务端实际生效的 maxLength(已 slice),无需再传参
119
464
  return r?.truncated ? `${html}\n${_t("cli.out.html_truncated", { n: html.length })}` : html;
120
465
  } },
121
- console_logs: { usage: "[--type --search --limit --clear]", descKey: "cli.cmd.console_logs", args: [{ flag: "type" }, { flag: "search" }, { flag: "limit" }, { flag: "clear", type: "boolean" }], run: async (a) => { const r = await service.consoleLogs(a); return (r.logs || []).join("\n") || _t("cli.out.no_logs"); } },
466
+ console_logs: {
467
+ usage: "[--type --group burst|none --phase --search --limit --tab --include-internal --clear --no-dedupe]",
468
+ descKey: "cli.cmd.console_logs",
469
+ args: [
470
+ { flag: "type" }, { flag: "group" }, { flag: "phase" }, { flag: "search" }, { flag: "limit" },
471
+ { flag: "tab" }, { flag: "include-internal", type: "boolean" },
472
+ { flag: "clear", type: "boolean" }, { flag: "no-dedupe", type: "boolean" },
473
+ ],
474
+ run: async (a) => {
475
+ const r = await service.consoleLogs(consoleLogParams(a));
476
+ return renderLogText(formatConsoleItems(r?.items), r?.dropped) || _t("cli.out.console_empty");
477
+ },
478
+ },
479
+ network_logs: {
480
+ usage: "[--type --status 2xx|3xx|4xx|5xx|N --failed --search --group burst|key|none --phase --limit --tab --include-headers --reveal-secrets --clear --no-dedupe]",
481
+ descKey: "cli.cmd.network_logs",
482
+ args: [
483
+ { flag: "type" }, { flag: "status" }, { flag: "failed", type: "boolean" }, { flag: "search" }, { flag: "phase" },
484
+ { flag: "group" }, { flag: "limit" }, { flag: "tab" },
485
+ { flag: "include-headers", type: "boolean" }, { flag: "reveal-secrets", type: "boolean" },
486
+ { flag: "clear", type: "boolean" }, { flag: "no-dedupe", type: "boolean" },
487
+ ],
488
+ run: async (a) => {
489
+ const r = await service.networkLogs(networkLogParams(a));
490
+ const lines = formatNetworkItems(r?.items, { includeHeaders: a["include-headers"] === true });
491
+ return renderLogText(lines, r?.dropped) || _t("cli.out.network_empty");
492
+ },
493
+ },
122
494
  go_back: { usage: "", descKey: "cli.cmd.go_back", run: async (a) => { const r = await service.goBack(sidArgs(a)); return _t("cli.out.go_back", { url: r.url }) + readyNote(r); } },
123
495
  go_forward: { usage: "", descKey: "cli.cmd.go_forward", run: async (a) => { const r = await service.goForward(sidArgs(a)); return _t("cli.out.go_forward", { url: r.url }) + readyNote(r); } },
124
496
  // resize:宽高=内容区(视口)尺寸;被钳到下限时如实标注(服务端返回 clamped/content/window)
@@ -294,7 +666,7 @@ const COMMANDS = {
294
666
  /** 帮助全文(command=help 或未知命令时返回;命令描述与结构按 toolLang 本地化) */
295
667
  function buildHelp() {
296
668
  const lines = Object.entries(COMMANDS).map(([k, v]) => ` ${k.padEnd(22)} ${v.usage.padEnd(42)} ${_t(v.descKey)}`);
297
- const examples = [_t("cli.example.1"), _t("cli.example.2"), _t("cli.example.3"), _t("cli.example.4")]
669
+ const examples = [_t("cli.example.1"), _t("cli.example.2"), _t("cli.example.3"), _t("cli.example.4"), _t("cli.example.5")]
298
670
  .map((e) => ` ${e}`)
299
671
  .join("\n");
300
672
  return `${_t("cli.header")}\n\n${_t("cli.usage")}\n\n${_t("cli.usage.flags")}\n\n${_t("cli.commands")}\n${lines.join("\n")}\n\n${_t("cli.examples")}\n${examples}`;
@@ -304,18 +676,24 @@ const DESC_INDEX = Object.entries(COMMANDS).map(([k, v]) => `${k} ${v.usage}`).j
304
676
  /** 解析 --flag 风格参数(基于 node:util.parseArgs,未知 flag 报错;tokens 已由 string-argv 正确分词)
305
677
  * 全局 flag `--private-session` 对所有命令可用,由调用方消费(不进入命令业务参数)。
306
678
  *
679
+ * 位置参数不再丢弃:返回 `{ values, positionals }`,供 `evaluate` 按顺序执行多客户端项使用;
680
+ * 其它命令沿用旧行为(位置参数不参与执行)。
681
+ *
307
682
  * `parseArgs` 默认把值解析成字符串,而 Rust 端对下列 flag 用 `as_i64`/`as_f64` 读取
308
683
  * (取不到就落默认值/0):不转换会静默失效(如 `resize --width 800` 被钳到下限)。
309
684
  * 因此这里对已知数值 flag 统一转 number;非数字直接报错,不带着坏值进浏览器。 */
310
685
  function parseFlagArgs(tokens, def) {
311
686
  if (tokens.length === 0)
312
- return {};
687
+ return { values: {}, positionals: [] };
313
688
  // 全局 boolean flag 先声明,避免被当作未知参数;若它出现在某个 string flag 之后,
314
689
  // parseArgs 会把它当成该 flag 的值(与用户显式传值一致,不会误判为私有会话)。
315
690
  const options = { "private-session": { type: "boolean" } };
316
691
  for (const arg of def.args || [])
317
692
  options[arg.flag] = { type: arg.type || "string" };
318
- const { values } = parseArgs({ args: tokens, options, allowPositionals: true });
693
+ for (const arg of def.args || [])
694
+ if (arg.multiple)
695
+ options[arg.flag].multiple = true;
696
+ const { values, positionals } = parseArgs({ args: tokens, options, allowPositionals: true });
319
697
  for (const key of Object.keys(values)) {
320
698
  if (!NUMERIC_FLAGS.has(key))
321
699
  continue;
@@ -328,10 +706,10 @@ function parseFlagArgs(tokens, def) {
328
706
  }
329
707
  values[key] = n;
330
708
  }
331
- return values;
709
+ return { values, positionals };
332
710
  }
333
711
  /** 需要转成 number 的 flag(Rust 端按数值读取;新增数值参数时必须同步登记) */
334
- const NUMERIC_FLAGS = new Set(["width", "height", "index", "freq", "durMs"]);
712
+ const NUMERIC_FLAGS = new Set(["width", "height", "index", "freq", "durMs", "limit", "tab", "order"]);
335
713
  /** 简单 CSV 行解析(处理引号包裹的字段,Edge/Chrome 密码导出格式) */
336
714
  function splitCsvLine(line) {
337
715
  const out = [];
@@ -463,9 +841,12 @@ export const opencodeBrowserTool = async ({ client, worktree, directory }) => {
463
841
  return `${_t("cli.unknown").replace("{cmd}", cmdName)}\n\n${buildHelp()}`;
464
842
  // 剩余 token 交给 parseArgs 解析(未知 flag 会抛错,返回用法提示自愈)
465
843
  let params = {};
844
+ let positionals = [];
466
845
  if (tokens.length > 0) {
467
846
  try {
468
- params = parseFlagArgs(tokens, def);
847
+ const parsed = parseFlagArgs(tokens, def);
848
+ params = parsed.values;
849
+ positionals = parsed.positionals;
469
850
  }
470
851
  catch (e) {
471
852
  // 解析错误可能夹带底层异常文本:进模型前先脱敏(用法提示本身不含路径)
@@ -487,15 +868,15 @@ export const opencodeBrowserTool = async ({ client, worktree, directory }) => {
487
868
  // (密码等敏感值不进 LLM 上下文,如 fill --value @file:C:\...\secret.tmp)
488
869
  // 安全边界:只允许读全局 tmp(getTmpDir)或**该会话(归并后 key)** tmp(getSessionTmpDir)之内的文件;
489
870
  // 其余路径一律拒绝(不读取),避免模型借助 @file: 读取任意本地文件。
490
- // sid 形态校验:归并 key 来自会话树/外部传入值,任意字符串(含 .. 、路径分隔符)
491
- // 会把 getSessionTmpDir 带到 sessions 目录之外,从而左右 allowed dirs。不匹配 SESSION_SID_RE
492
- // 一律回退 "default" 桶("default" 本身合法,getSessionTmpDir("default") = sessions/<profile>/default/tmp,必在 sessions 内)。
493
- const fileSid = SESSION_SID_RE.test(browserSid) ? browserSid : "default";
494
- const globalTmpDir = getTmpDir();
495
- const allowedTmpDirs = [globalTmpDir, getSessionTmpDir(fileSid)];
871
+ // 允许目录由 allowedFileDirs 统一计算(其中做了 sid 形态校验,非法 sid 回落 default 桶)。
872
+ const { globalTmpDir, dirs: allowedTmpDirs } = allowedFileDirs(browserSid);
496
873
  for (const key of Object.keys(params)) {
497
874
  const v = params[key];
498
875
  if (typeof v === "string" && v.startsWith("@file:")) {
876
+ // `type` 的 `--text` 自带 evaluate 同款解析(允许工作区目录 + 插件 tmp,且不删文件),
877
+ // 故跳过这里的「仅插件 tmp」通用层,避免两套规则叠加(通用层还会删掉全局 tmp 文件)。
878
+ if (cmdName === "type" && key === "text")
879
+ continue;
499
880
  const p = v.slice(6);
500
881
  const abs = resolve(p);
501
882
  if (!allowedTmpDirs.some((d) => isInsideDir(abs, d))) {
@@ -518,7 +899,7 @@ export const opencodeBrowserTool = async ({ client, worktree, directory }) => {
518
899
  setAppDirectory(context?.directory || "");
519
900
  params._sessionId = browserSid;
520
901
  try {
521
- return await def.run(params);
902
+ return await def.run(params, positionals);
522
903
  }
523
904
  catch (e) {
524
905
  // 命令失败可能带 fs/网络错误文本:统一脱敏后再回模型