@xiaoqiong0v0/opencode-browser-tool 1.11.1 → 1.12.0

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.
@@ -0,0 +1,181 @@
1
+ /**
2
+ * `evaluate` 多客户端项的逻辑(分类 / 标签 / 串行执行编排 / 结果截断 / 报告格式化)。
3
+ *
4
+ * 文件读取、路径 containment、脚本执行的真实实现都在 `index.ts`(需要 fs 与浏览器服务);
5
+ * 这里通过 `EvalRunDeps` 注入,本模块自身不含任何 IO,便于 `tests/unit/eval-items.test.mjs` 直接调用。
6
+ */
7
+ import { sanitizeForModel } from "./sanitize.js";
8
+ /** 文件项前缀:`@file:<path>` = 读该文件内容作为脚本 */
9
+ export const EVAL_FILE_PREFIX = "@file:";
10
+ /** 单条结果(或失败信息)展示上限(字符) */
11
+ export const EVAL_RESULT_MAX_CHARS = 500;
12
+ /** 单个脚本文件字节上限(256 KiB) */
13
+ export const EVAL_ITEM_MAX_BYTES = 256 * 1024;
14
+ /** 一次调用内所有脚本文件合计字节上限(1 MiB) */
15
+ export const EVAL_TOTAL_MAX_BYTES = 1024 * 1024;
16
+ /** 结果列的状态文案(模型可读、简短,不随 toolLang 变化,保持报告结构稳定) */
17
+ const STATUS_OK = "ok";
18
+ const STATUS_FAILED = "FAILED";
19
+ /** 报告首行前缀 */
20
+ const REPORT_PREFIX = "evaluate";
21
+ /** 项类型展示文案 */
22
+ const KIND_LABEL_FILE = "file";
23
+ const KIND_LABEL_TEXT = "text";
24
+ /** 截断与换行折叠标记 */
25
+ const ELLIPSIS = "…";
26
+ const LINE_BREAK_RE = /\r?\n/g;
27
+ const FLAT_LINE_BREAK = "\\n";
28
+ /**
29
+ * 把位置参数分类为有序的 `evaluate` 项。
30
+ *
31
+ * 规则:以 `@file:` 开头的参数 = 文件项,其余 = 内联 JS 文本项。
32
+ * `--script` 只允许单独使用:与位置参数同时给出时无法确定顺序,直接报冲突。
33
+ *
34
+ * @param positionals 位置参数(已由 string-argv 分词)
35
+ * @param hasScriptFlag 是否传了 `--script`
36
+ * @returns 成功时给出有序项列表;失败时给出原因码(`script_conflict` / `no_items`)
37
+ */
38
+ export function classifyEvalArgs(positionals, hasScriptFlag) {
39
+ if (hasScriptFlag && positionals.length > 0) {
40
+ return { ok: false, reason: "script_conflict" };
41
+ }
42
+ if (positionals.length === 0) {
43
+ return { ok: false, reason: "no_items" };
44
+ }
45
+ const items = positionals.map((p) => p.startsWith(EVAL_FILE_PREFIX)
46
+ ? { kind: "file", path: p.slice(EVAL_FILE_PREFIX.length) }
47
+ : { kind: "text", text: p });
48
+ return { ok: true, items };
49
+ }
50
+ /**
51
+ * 项在报告里的标签(`file <path>` / `text`);绝对路径由调用方按需脱敏。
52
+ *
53
+ * @param item 待展示的项
54
+ * @returns 单行标签文本
55
+ */
56
+ export function evalItemLabel(item) {
57
+ return item.kind === "file" ? `${KIND_LABEL_FILE} ${item.path}` : KIND_LABEL_TEXT;
58
+ }
59
+ /**
60
+ * 把服务端返回的任意 JSON 值渲染成结果文本。
61
+ *
62
+ * 字符串结果原样输出(便于直接看页面取回的文本),其它值 `JSON.stringify`;
63
+ * 循环引用等序列化失败回退 `String()`,绝不抛错。
64
+ *
65
+ * @param value `/api/evaluate` 的返回值
66
+ * @returns 未截断的结果文本
67
+ */
68
+ export function formatEvalValue(value) {
69
+ if (value === undefined)
70
+ return "undefined";
71
+ if (typeof value === "string")
72
+ return value;
73
+ try {
74
+ const text = JSON.stringify(value);
75
+ return text === undefined ? String(value) : text;
76
+ }
77
+ catch {
78
+ return String(value);
79
+ }
80
+ }
81
+ /**
82
+ * 把多行文本折叠成单行(报告每条一行,便于模型按行读取)。
83
+ *
84
+ * @param text 原始文本
85
+ * @returns 换行替换为字面量 `\n` 的单行文本
86
+ */
87
+ export function flattenEvalText(text) {
88
+ return text.replace(LINE_BREAK_RE, FLAT_LINE_BREAK);
89
+ }
90
+ /**
91
+ * 截断文本到指定长度(含省略号)。
92
+ *
93
+ * @param text 原始文本
94
+ * @param max 上限(字符数,默认 500)
95
+ * @returns 不超过 `max` 个字符的文本
96
+ */
97
+ export function truncateEvalText(text, max = EVAL_RESULT_MAX_CHARS) {
98
+ const limit = Number.isFinite(max) && max > 0 ? Math.floor(max) : EVAL_RESULT_MAX_CHARS;
99
+ if (text.length <= limit)
100
+ return text;
101
+ return `${text.slice(0, Math.max(0, limit - 1))}${ELLIPSIS}`;
102
+ }
103
+ /**
104
+ * 渲染多客户端报告:首行汇总 + 每项一行(`[n] <label> <status> <ms>ms → <body>`)。
105
+ *
106
+ * 失败项的结果经 `sanitizeForModel` 脱敏(绝对路径 → `<path>`);所有结果统一折叠换行并截断到
107
+ * `EVAL_RESULT_MAX_CHARS`,保证每条占用一行且长度可控。
108
+ *
109
+ * @param entries 已执行项(顺序即执行顺序;提前停止时可能少于 `total`)
110
+ * @param options 汇总信息(总数 / 是否停止 / 是否 continue-on-error)
111
+ * @returns 多行报告文本
112
+ */
113
+ export function formatEvalReport(entries, options) {
114
+ const okCount = entries.filter((e) => e.ok).length;
115
+ const failedCount = entries.length - okCount;
116
+ const suffix = options.stopped ? " (stop)" : options.continued ? " (continued)" : "";
117
+ const header = `${REPORT_PREFIX}: ${options.total} item(s), ${okCount} ${STATUS_OK}` +
118
+ `${failedCount > 0 ? `, ${failedCount} failed` : ""}${suffix}`;
119
+ const labelWidth = entries.reduce((w, e) => Math.max(w, e.label.length), 0);
120
+ const rows = entries.map((e, i) => {
121
+ const label = e.label.padEnd(labelWidth);
122
+ const status = e.ok ? STATUS_OK : STATUS_FAILED;
123
+ return `[${i + 1}] ${label} ${status} ${e.ms}ms → ${entryBody(e)}`;
124
+ });
125
+ return [header, ...rows].join("\n");
126
+ }
127
+ /**
128
+ * 按顺序**串行**执行多客户端项,返回可直接回模型的报告。
129
+ *
130
+ * - 文件项在**任何脚本执行前**统一读入:任一路径越界 / 读取失败 / 超限 → 直接返回错误文案,
131
+ * **整次不执行任何脚本**(避免只跑了一半的副作用);脚本执行失败只影响该项。
132
+ * - 默认遇错即停;`deps.continued` 为 true(`--continue-on-error`)时继续执行后续项。
133
+ * - 输出由 `formatEvalReport` 渲染(失败信息脱敏、每条截断到 `EVAL_RESULT_MAX_CHARS`)。
134
+ *
135
+ * @param items 有序执行项
136
+ * @param deps 读文件 / 执行脚本 / 是否继续的依赖
137
+ * @returns 报告文本(不含 timeout 提示,由调用方追加)
138
+ */
139
+ export async function runEvalItems(items, deps) {
140
+ const resolved = [];
141
+ for (const item of items) {
142
+ if (item.kind === "text") {
143
+ resolved.push({ item, script: item.text });
144
+ continue;
145
+ }
146
+ const read = deps.readFile(item.path);
147
+ if ("error" in read)
148
+ return read.error;
149
+ resolved.push({ item, script: read.content });
150
+ }
151
+ const entries = [];
152
+ let stopped = false;
153
+ for (const { item, script } of resolved) {
154
+ const startedAt = Date.now();
155
+ const entry = { label: sanitizeForModel(evalItemLabel(item)), ok: true, ms: 0, output: "" };
156
+ try {
157
+ entry.output = formatEvalValue(await deps.evaluate(script));
158
+ }
159
+ catch (e) {
160
+ entry.ok = false;
161
+ entry.output = e?.message || String(e);
162
+ stopped = !deps.continued;
163
+ }
164
+ entry.ms = Date.now() - startedAt;
165
+ entries.push(entry);
166
+ if (stopped)
167
+ break;
168
+ }
169
+ return formatEvalReport(entries, { total: resolved.length, stopped, continued: deps.continued });
170
+ }
171
+ /**
172
+ * 单条结果体:折叠换行 → 失败项脱敏 → 截断。
173
+ *
174
+ * @param entry 已执行项
175
+ * @returns 单行结果文本(≤ `EVAL_RESULT_MAX_CHARS`)
176
+ */
177
+ function entryBody(entry) {
178
+ const flat = flattenEvalText(entry.output);
179
+ const safe = entry.ok ? flat : sanitizeForModel(flat, EVAL_RESULT_MAX_CHARS);
180
+ return truncateEvalText(safe, EVAL_RESULT_MAX_CHARS);
181
+ }
@@ -0,0 +1,227 @@
1
+ /**
2
+ * `inject`(持久注入规则)的纯逻辑:item 构造 / 上限判定 / 输出格式化。
3
+ *
4
+ * 文件读取与 containment 在 `index.ts`(复用 `evaluate` 的 `readEvalFile`),HTTP 在
5
+ * `client.ts`(`/api/inject/rules`、`/api/inject/test`);这里只做可单测的纯函数,
6
+ * 不含任何 IO,便于 `tests/unit/inject-rules.test.mjs` 直接调用。
7
+ *
8
+ * 字段全部以契约为准(`.tmp/scratch/inject-rules-contract.md`),不臆造 Rust 侧字段:
9
+ * 规则 = `{ id, match, enabled, order, items, last, failStreak }`,
10
+ * item 目前只有 `{ kind:"text", code, name }` 一种(文件内容在插件侧转成 text)。
11
+ */
12
+ import { basename } from "path";
13
+ import { sanitizeForModel } from "./sanitize.js";
14
+ /** 单条规则 items 合计字节上限(256 KiB,与契约同口径) */
15
+ export const INJECT_RULE_MAX_BYTES = 256 * 1024;
16
+ /** 规则条数上限(契约:≤ 20) */
17
+ export const INJECT_MAX_RULES = 20;
18
+ /** `failStreak` 达到该值后 Rust 自动禁用该规则(契约:>= 3) */
19
+ export const INJECT_FAIL_STREAK_LIMIT = 3;
20
+ /** `list` 时每条规则最多展开的 item 明细条数(超出只给数量) */
21
+ export const INJECT_LIST_MAX_ITEMS = 5;
22
+ /** `last.error` 展示上限(字符;进表格前先脱敏,避免回显执行栈里的本机路径) */
23
+ export const INJECT_ERROR_MAX_CHARS = 120;
24
+ /** 内联代码项的统一 name(没有文件名可用) */
25
+ const TEXT_ITEM_NAME = "text";
26
+ /** 字节展示换算(KiB) */
27
+ const BYTES_PER_KIB = 1024;
28
+ /** 字节展示保留位数 */
29
+ const KIB_DIGITS = 1;
30
+ /** 换行匹配(错误信息只取首行) */
31
+ const LINE_BREAK_RE = /\r?\n/;
32
+ /**
33
+ * 把参数分类成有序 item 列表:先 `--file`(按传入顺序,name=basename),后 `--text`
34
+ * (按传入顺序,name 固定 `text`)。Rust 侧不接触路径,只收到 `{kind,code,name}`。
35
+ *
36
+ * @param files 已读入的文件项
37
+ * @param texts 内联代码文本
38
+ * @returns 有序 item 列表(可能为空,由调用方判空报错)
39
+ */
40
+ export function buildInjectItems(files, texts) {
41
+ const items = files.map((f) => ({
42
+ kind: "text",
43
+ code: f.code,
44
+ name: basename(f.path) || f.path,
45
+ }));
46
+ for (const code of texts)
47
+ items.push({ kind: "text", code, name: TEXT_ITEM_NAME });
48
+ return items;
49
+ }
50
+ /**
51
+ * 单个 item 的 UTF-8 字节数(体积口径与 fs 一致,不用字符数)。
52
+ *
53
+ * @param item 注入项
54
+ * @returns 字节数
55
+ */
56
+ export function injectItemBytes(item) {
57
+ return Buffer.byteLength(item.code ?? "", "utf8");
58
+ }
59
+ /**
60
+ * items 合计字节数。
61
+ *
62
+ * @param items 注入项列表
63
+ * @returns 合计 UTF-8 字节数
64
+ */
65
+ export function injectItemsBytes(items) {
66
+ return items.reduce((sum, item) => sum + injectItemBytes(item), 0);
67
+ }
68
+ /**
69
+ * 单条规则 items 是否超上限(超过 `INJECT_RULE_MAX_BYTES` 即拒绝,不带坏规则进浏览器)。
70
+ *
71
+ * @param items 注入项列表
72
+ * @returns 超限时返回上限 KiB(供文案使用),未超限返回 null
73
+ */
74
+ export function injectRuleLimitIssue(items) {
75
+ return injectItemsBytes(items) > INJECT_RULE_MAX_BYTES ? { kb: INJECT_RULE_MAX_BYTES / BYTES_PER_KIB } : null;
76
+ }
77
+ /**
78
+ * `add` 子动作的参数校验(纯判定,不读文件)。
79
+ *
80
+ * @param match 已 trim 的 `--match` 值
81
+ * @param fileCount `--file` 个数
82
+ * @param textCount `--text` 个数
83
+ * @returns 原因码:`no_match` / `no_items`;通过返回 null
84
+ */
85
+ export function injectAddIssue(match, fileCount, textCount) {
86
+ if (!match)
87
+ return "no_match";
88
+ if (fileCount + textCount === 0)
89
+ return "no_items";
90
+ return null;
91
+ }
92
+ /**
93
+ * 规范化子动作名:未给出时按只读的 `list` 处理;未知名字原样返回,由调用方报错。
94
+ *
95
+ * @param raw 第一个位置参数
96
+ * @returns 子动作名
97
+ */
98
+ export function normalizeInjectAction(raw) {
99
+ const action = (raw || "").trim().toLowerCase();
100
+ return action || "list";
101
+ }
102
+ /**
103
+ * 字节数的人类可读形式(`512B` / `1.2KiB`)。
104
+ *
105
+ * @param bytes 字节数
106
+ * @returns 展示文本
107
+ */
108
+ export function formatInjectBytes(bytes) {
109
+ const n = Number.isFinite(bytes) && bytes > 0 ? bytes : 0;
110
+ if (n < BYTES_PER_KIB)
111
+ return `${n}B`;
112
+ return `${(n / BYTES_PER_KIB).toFixed(KIB_DIGITS)}KiB`;
113
+ }
114
+ /**
115
+ * `list` 输出:表头 + 每规则一行(id / order / enabled / match / items / last),
116
+ * 另附每条规则的 item 明细(**只给 name + 字节数,绝不输出脚本内容**)。
117
+ *
118
+ * 列名与状态文案固定英文(与 `formatEvalReport` 同约定:不随 toolLang 变化,保证结构稳定)。
119
+ *
120
+ * @param data 服务端 `data`(`rules` 可缺省)
121
+ * @returns 多行文本(空列表时只有汇总行,调用方另行给空文案)
122
+ */
123
+ export function formatInjectList(data) {
124
+ const rules = data?.rules ?? [];
125
+ const header = `inject: ${rules.length} rule(s), limit ${INJECT_MAX_RULES}`;
126
+ if (rules.length === 0)
127
+ return header;
128
+ const columns = ["id", "order", "enabled", "match", "items", "last"];
129
+ const rows = rules.map((rule) => [
130
+ String(rule.id ?? "-"),
131
+ rule.order === undefined ? "-" : String(rule.order),
132
+ rule.enabled === false ? "off" : "on",
133
+ String(rule.match ?? ""),
134
+ String((rule.items ?? []).length),
135
+ lastCell(rule),
136
+ ]);
137
+ const widths = columns.map((c, i) => rows.reduce((w, row) => Math.max(w, row[i].length), c.length));
138
+ /** 末列不补齐,避免行尾空白 */
139
+ const layout = (cells) => cells.map((cell, i) => (i === cells.length - 1 ? cell : cell.padEnd(widths[i]))).join(" ");
140
+ const lines = [header, layout(columns), ...rows.map(layout)];
141
+ for (const [i, rule] of rules.entries()) {
142
+ const detail = itemDetail(rule.items ?? []);
143
+ if (detail)
144
+ lines.push(` ${rows[i][0]}: ${detail}`);
145
+ }
146
+ return lines.join("\n");
147
+ }
148
+ /**
149
+ * `add` 输出:id + match + order + enabled + items 数(不含脚本内容)。
150
+ *
151
+ * @param rule 服务端返回的新建规则(缺省时退化为通用文案)
152
+ * @returns 单行文本
153
+ */
154
+ export function formatInjectAdd(rule) {
155
+ if (!rule || !rule.id)
156
+ return "inject: added";
157
+ const items = rule.items ?? [];
158
+ const enabled = rule.enabled === false ? "false" : "true";
159
+ const order = rule.order === undefined ? "-" : String(rule.order);
160
+ return `inject: added ${rule.id} match=${rule.match ?? ""} order=${order} enabled=${enabled} items=${items.length}`;
161
+ }
162
+ /**
163
+ * `test` 输出:命中的规则 id 与 item 总数(**只算不执行**)。
164
+ *
165
+ * @param data 服务端 `data`
166
+ * @returns 单行文本
167
+ */
168
+ export function formatInjectTest(data) {
169
+ const matched = data?.matched ?? [];
170
+ const items = data?.items ?? 0;
171
+ if (matched.length === 0)
172
+ return "inject test: no rule matched (not executed)";
173
+ return `inject test: ${matched.length} rule(s) matched [${matched.join(", ")}], ${items} item(s) (not executed)`;
174
+ }
175
+ /**
176
+ * 最近一次执行结果的展示:`ok/failed` + 错误首行;重试达到自动禁用阈值时一并标注。
177
+ *
178
+ * @param rule 规则
179
+ * @returns 单行文本(无执行记录时为 `-`)
180
+ */
181
+ function lastCell(rule) {
182
+ const parts = [];
183
+ const last = rule.last;
184
+ const hasLast = last !== undefined &&
185
+ (last.ts !== undefined || last.ok !== undefined || last.failed !== undefined || !!last.error);
186
+ if (!hasLast) {
187
+ parts.push("-");
188
+ }
189
+ else {
190
+ parts.push(`${last.ok ?? 0} ok / ${last.failed ?? 0} failed`);
191
+ const err = firstLine(last.error);
192
+ if (err)
193
+ parts.push(`error: ${sanitizeForModel(err, INJECT_ERROR_MAX_CHARS)}`);
194
+ }
195
+ const streak = rule.failStreak ?? 0;
196
+ if (streak >= INJECT_FAIL_STREAK_LIMIT)
197
+ parts.push(`failStreak=${streak}`);
198
+ return parts.join(" ");
199
+ }
200
+ /**
201
+ * item 明细:`name + 字节数`,超出展示上限只给 `+N more`。
202
+ *
203
+ * @param items 注入项列表
204
+ * @returns 单行明细(无 item 时返回空串)
205
+ */
206
+ function itemDetail(items) {
207
+ if (items.length === 0)
208
+ return "";
209
+ const shown = items
210
+ .slice(0, INJECT_LIST_MAX_ITEMS)
211
+ .map((item) => `${item.name} ${formatInjectBytes(injectItemBytes(item))}`);
212
+ const rest = items.length - INJECT_LIST_MAX_ITEMS;
213
+ if (rest > 0)
214
+ shown.push(`+${rest} more`);
215
+ return shown.join(", ");
216
+ }
217
+ /**
218
+ * 错误信息只保留首行(避免把多行堆栈塞进表格)。
219
+ *
220
+ * @param error 原始错误文本(可能缺省)
221
+ * @returns 首行(无内容返回空串)
222
+ */
223
+ function firstLine(error) {
224
+ if (!error)
225
+ return "";
226
+ return error.split(LINE_BREAK_RE)[0].trim();
227
+ }
@@ -0,0 +1,248 @@
1
+ /**
2
+ * console / network 日志流的输出格式化(纯函数,供 `bt_cli` 与单测复用)。
3
+ *
4
+ * 聚合由 shell 侧完成(console `group=burst|none`;network `group=burst|key|none`),
5
+ * 这里只把结构化 item 渲染成模型可读的紧凑文本:不改写计数、不二次聚合。
6
+ * 输出给模型的文本最后统一走 `sanitizeForModel`(绝对路径 → `<path>`)。
7
+ */
8
+ import { tf } from "../i18n/index.js";
9
+ import { sanitizeForModel } from "./sanitize.js";
10
+ /** 模型可见日志文本上限(字符):日志是多行正文,不能沿用默认 300 的短文案上限 */
11
+ export const MAX_LOG_TEXT_CHARS = 20000;
12
+ /** 聚合计数后缀:只有 count > 1 才显示,避免单条噪声 */
13
+ function countSuffix(count) {
14
+ return typeof count === "number" && count > 1 ? ` (x${count})` : "";
15
+ }
16
+ /** 取 stack 首行(异常条目只展示首行,完整栈不进上下文) */
17
+ function firstLine(text) {
18
+ return String(text).split(/\r?\n/, 1)[0].trim();
19
+ }
20
+ /** 渲染单条 console 日志:`[level] msg (xN) phase=… source=…`,异常追加 stack 首行 */
21
+ export function formatConsoleItem(item) {
22
+ const level = item.level || "log";
23
+ const msg = item.msg ?? "";
24
+ const parts = [`[${level}] ${msg}${countSuffix(item.count)}`];
25
+ if (item.phase)
26
+ parts.push(`phase=${item.phase}`);
27
+ if (item.source)
28
+ parts.push(`source=${item.source}`);
29
+ const line = parts.join(" ");
30
+ const stack = item.stack ? firstLine(item.stack) : "";
31
+ return stack ? `${line}\n stack: ${stack}` : line;
32
+ }
33
+ /** 批量渲染 console 条目(空数组返回空数组,由调用方给「空结果」文案) */
34
+ export function formatConsoleItems(items) {
35
+ return (items || []).map(formatConsoleItem);
36
+ }
37
+ /** 展示用 URL 上限(字符):超出保留 host + 末尾 60 字符 */
38
+ const MAX_URL_CHARS = 120;
39
+ /** 超长 URL 保留的末尾字符数(中间用 `…` 省略) */
40
+ const URL_TAIL_CHARS = 60;
41
+ /** 省略标记 */
42
+ const URL_ELLIPSIS = "…";
43
+ /**
44
+ * 判断 network 条目是否属于页面文档本身(用于推断同源基准)。
45
+ * shell 侧契约里文档请求的 `type` 是 `doc`(Windows `document` 已归一为 `doc`)。
46
+ */
47
+ function isDocumentType(type) {
48
+ const t = (type || "").toLowerCase();
49
+ return t === "doc" || t === "document";
50
+ }
51
+ /** 从同批条目推断页面 origin(取第一条文档请求);推断不出返回 `undefined` */
52
+ function inferPageOrigin(items) {
53
+ for (const it of items) {
54
+ if (!isDocumentType(it.type))
55
+ continue;
56
+ try {
57
+ return new URL(String(it.url || "")).origin;
58
+ }
59
+ catch {
60
+ // 该条 URL 不可解析:继续找下一条
61
+ }
62
+ }
63
+ return undefined;
64
+ }
65
+ /**
66
+ * 拼接并压到 `MAX_URL_CHARS` 内:超长时保留前缀(host)+ 末尾 `URL_TAIL_CHARS` 字符。
67
+ * @param prefix 前缀(同源为 `host`,跨域/绝对为 `scheme//host`)
68
+ * @param tail path + query
69
+ * @returns 紧凑展示串
70
+ */
71
+ function compactUrl(prefix, tail) {
72
+ const full = `${prefix}${tail}`;
73
+ if (full.length <= MAX_URL_CHARS)
74
+ return full;
75
+ const keepFrom = Math.max(0, tail.length - URL_TAIL_CHARS);
76
+ return `${prefix}/${URL_ELLIPSIS}${tail.slice(keepFrom)}`;
77
+ }
78
+ /**
79
+ * URL → 紧凑展示:同源去 scheme 保留 `host + path + query`(`web.zhihjy.cn/js/app.js`),
80
+ * 跨域保留完整 URL(`https://other.host/...`);超长保留 host + 末尾 60 字符。
81
+ *
82
+ * **绝不以 `/` 开头输出裸路径**——`sanitizeForModel` 会把裸 POSIX 路径掩码成 `<path>`
83
+ * (`/api/*`、`/notify/*` 例外),那是历史实测里 `[200] GET <path>` 的根因。
84
+ *
85
+ * @param raw 原始 URL(CDP 上报,通常为绝对 URL)
86
+ * @param opts.origin 页面 origin(用于判定同源;缺省时退化为去 scheme 形式)
87
+ * @returns 展示串;空输入返回空串
88
+ */
89
+ export function displayUrl(raw, opts) {
90
+ const s = (raw || "").trim();
91
+ if (!s)
92
+ return "";
93
+ let u;
94
+ try {
95
+ u = new URL(s);
96
+ }
97
+ catch {
98
+ // 相对/不可解析:加 `./` 前缀,既保留原信息又避免被当成绝对路径掩码
99
+ return s.startsWith("/") ? `.${s}` : s;
100
+ }
101
+ if (!u.host)
102
+ return s; // `data:` / `about:blank` 等无 host 的 URL 原样返回
103
+ const tail = `${u.pathname}${u.search}`;
104
+ const crossOrigin = Boolean(opts?.origin) && opts?.origin !== u.origin;
105
+ return crossOrigin
106
+ ? compactUrl(`${u.protocol}//${u.host}`, tail)
107
+ : compactUrl(u.host, tail);
108
+ }
109
+ /** initiator 前缀类型(Windows CDP 会带 `script ` / `fetch ` 等前缀) */
110
+ const INITIATOR_TYPES = new Set([
111
+ "document", "script", "stylesheet", "image", "font", "xhr", "fetch",
112
+ "other", "subresource", "media", "manifest", "texttrack", "websocket",
113
+ "parser", "preflight",
114
+ ]);
115
+ /** 只显示类型、不显示 URL 的 initiator(解析器/预检/文档本身) */
116
+ const INITIATOR_TYPE_ONLY = new Set(["parser", "preflight", "document"]);
117
+ /** 无归因时的占位(调用方据此不输出 `from`) */
118
+ const INITIATOR_FALLBACK = "other";
119
+ /** URL scheme 前缀(`https://` / `ws://` …) */
120
+ const URL_SCHEME_RE = /^[a-z][a-z0-9+.-]*:\/\//i;
121
+ /** `file:line` / `file:line:col` 的行号后缀 */
122
+ const LINE_SUFFIX_RE = /^(.*?):(\d+)(?::\d+)?$/;
123
+ /**
124
+ * initiator → 紧凑归因:去掉类型前缀与 scheme/host,只留**最后两段 + `:line`**
125
+ * (如 `js/chunk-vendors.js:3498`)。
126
+ *
127
+ * 健壮性:空值 / `other` / 解析不出文件名 / 行号为 `0`(CDP 无行号时的占位,如 `BASE_DIGITAL:0`)
128
+ * 统一返回 `other`;**绝不以 `/` 开头输出**(裸路径会被 `sanitizeForModel` 掩码)。
129
+ * Linux 的 `subresource` / `document` 无栈,原样保留。
130
+ *
131
+ * @param raw 原始 initiator(`<type> <url>:<line>` 或平台标记)
132
+ * @returns 归因串;无归因时为 `other`
133
+ */
134
+ export function shortInitiator(raw) {
135
+ let s = (raw || "").trim();
136
+ if (!s)
137
+ return INITIATOR_FALLBACK;
138
+ const sp = s.indexOf(" ");
139
+ const type = sp > 0 ? s.slice(0, sp).toLowerCase() : "";
140
+ if (type && INITIATOR_TYPE_ONLY.has(type))
141
+ return type;
142
+ if (sp > 0 && INITIATOR_TYPES.has(type))
143
+ s = s.slice(sp + 1).trim();
144
+ if (!s || s.toLowerCase() === INITIATOR_FALLBACK)
145
+ return INITIATOR_FALLBACK;
146
+ // 去 scheme + host(首段是主机名,不参与「最后两段」)
147
+ const hadHost = URL_SCHEME_RE.test(s);
148
+ s = s.replace(URL_SCHEME_RE, "").replace(/^\/+/, "");
149
+ s = s.split(/[?#]/, 1)[0] || "";
150
+ const segs = s.split(/[\\/]/).filter(Boolean);
151
+ if (hadHost && segs.length)
152
+ segs.shift();
153
+ if (!segs.length)
154
+ return INITIATOR_FALLBACK;
155
+ const m = LINE_SUFFIX_RE.exec(segs[segs.length - 1]);
156
+ const line = m ? m[2] : "";
157
+ const file = m ? m[1] : segs[segs.length - 1];
158
+ if (!file)
159
+ return INITIATOR_FALLBACK;
160
+ if (line && Number(line) === 0)
161
+ return INITIATOR_FALLBACK;
162
+ const tail = [segs.length >= 2 ? segs[segs.length - 2] : "", file].filter(Boolean).join("/");
163
+ return line ? `${tail}:${line}` : tail;
164
+ }
165
+ /**
166
+ * 渲染 headers(形状按契约未定:对象 / 数组 / 字符串均容错)。
167
+ * 默认已由服务端脱敏(Authorization/Cookie/Set-Cookie → `<redacted>`);
168
+ * `--reveal-secrets` 时展示原值,风险见 README。
169
+ */
170
+ export function formatHeaders(headers) {
171
+ if (headers === undefined || headers === null)
172
+ return "";
173
+ if (typeof headers === "string")
174
+ return headers.trim();
175
+ if (Array.isArray(headers))
176
+ return headers.map((h) => String(h)).join("; ");
177
+ if (typeof headers === "object") {
178
+ return Object.entries(headers)
179
+ .map(([k, v]) => `${k}: ${Array.isArray(v) ? v.join(", ") : String(v)}`)
180
+ .join("; ");
181
+ }
182
+ return String(headers);
183
+ }
184
+ /** `from` 归因的展示值:`other` 视为无归因,不输出(避免每行都挂 `from other`) */
185
+ function initiatorLabel(raw) {
186
+ const s = shortInitiator(raw);
187
+ return s === INITIATOR_FALLBACK ? "" : s;
188
+ }
189
+ /**
190
+ * 渲染单条 network 请求:`[status] METHOD host/path (xN) 30ms avg 失败: … from file:line phase=…`
191
+ * @param item network 条目
192
+ * @param opts.includeHeaders 是否附加 headers
193
+ * @param opts.pageOrigin 页面 origin(判定同源用;缺省退化为去 scheme 形式)
194
+ */
195
+ export function formatNetworkItem(item, opts) {
196
+ const statusNum = typeof item.status === "number" ? item.status : Number(item.status);
197
+ const status = Number.isFinite(statusNum) ? statusNum : 0;
198
+ const badge = `[${status}]`.padEnd(5);
199
+ const method = (item.method || "?").toUpperCase();
200
+ const url = displayUrl(item.url, { origin: opts?.pageOrigin });
201
+ const count = typeof item.count === "number" && item.count > 1 ? item.count : 0;
202
+ // shell 聚合只保留同组**最后一条**的耗时(无 avg/min/max 字段),因此标注 `last`,
203
+ // 不谎报平均值(契约示例里的 `avg (min-max)` 需要契约外字段,见交付说明)。
204
+ const duration = typeof item.durationMs === "number" && Number.isFinite(item.durationMs)
205
+ ? `${Math.round(item.durationMs)}ms${count ? " last" : ""}`
206
+ : "";
207
+ const failed = item.failure
208
+ ? tf("cli.log.failed", { reason: item.failure })
209
+ : status === 0 ? tf("cli.log.failed_unknown") : "";
210
+ const from = initiatorLabel(item.initiator);
211
+ const parts = [`${badge} ${method} ${url}${countSuffix(item.count)}`];
212
+ if (duration)
213
+ parts.push(duration);
214
+ if (failed)
215
+ parts.push(failed);
216
+ if (from)
217
+ parts.push(`from ${from}`);
218
+ if (item.phase)
219
+ parts.push(`phase=${item.phase}`);
220
+ const line = parts.join(" ");
221
+ const headers = opts?.includeHeaders ? formatHeaders(item.headers) : "";
222
+ return headers ? `${line}\n headers: ${headers}` : line;
223
+ }
224
+ /**
225
+ * 批量渲染 network 条目;页面 origin 由同批的文档请求(`type=doc`)推断,
226
+ * 用于把同源 URL 压成 `host/path`、跨域 URL 保留完整形式。
227
+ */
228
+ export function formatNetworkItems(items, opts) {
229
+ const list = items || [];
230
+ const pageOrigin = opts?.pageOrigin ?? inferPageOrigin(list);
231
+ return list.map((item) => formatNetworkItem(item, { includeHeaders: opts?.includeHeaders, pageOrigin }));
232
+ }
233
+ /** 缓冲逐出说明:有丢弃才追加,避免正常输出噪声 */
234
+ export function droppedNote(dropped) {
235
+ return typeof dropped === "number" && dropped > 0 ? tf("cli.log.dropped", { n: dropped }) : "";
236
+ }
237
+ /**
238
+ * 拼装最终文本:多行 + 可选「丢弃条目」说明,再统一脱敏(绝对路径 → `<path>`)。
239
+ * 空结果返回空串,由命令层给「可能无日志/已导航/在其它标签」的明确文案。
240
+ */
241
+ export function renderLogText(lines, dropped) {
242
+ const body = [lines.join("\n"), droppedNote(dropped)].filter(Boolean).join("\n");
243
+ if (!body)
244
+ return "";
245
+ // `file:///C:/x` / `file:///home/x` 里的绝对路径 sanitizeForModel 不会命中(URL 保护 + 前导 `/`),
246
+ // 在日志出口先整体掩码;http(s) URL 仍原样保留(模型需要看接口地址)。
247
+ return sanitizeForModel(body.replace(/\bfile:\/\/[^\s"'<>]+/gi, "<path>"), MAX_LOG_TEXT_CHARS);
248
+ }