@xiaoqiong0v0/opencode-browser-tool 1.11.0 → 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,121 @@
1
+ // 会话树归并(纯逻辑,便于单测):把子代理会话归并到根会话的浏览器实例。
2
+ //
3
+ // 背景:浏览器实例按 session 隔离,但 task 子代理会话也是 session。若直接用钩子里的
4
+ // sessionID 作路由键,子代理一调 bt_cli 就会另起一个 shell 与数据目录。
5
+ // 目标语义(用户确认):
6
+ // 1. 默认归并到根会话:沿 Session.parentID 回溯到最顶层,以根 sid 作 browserKey;
7
+ // 2. --private-session:用调用者自己的 sid 建私有实例,并且**粘住**(之后不带标志也继续私有);
8
+ // 3. 根会话自己带 --private-session 等价于自己,不报错。
9
+ //
10
+ // 失败/超时不抛异常:回退 raw sid,且**不缓存**该结果(下一次调用可重试)。
11
+ /** 默认单跳查询超时(ms) */
12
+ const DEFAULT_QUERY_TIMEOUT_MS = 1500;
13
+ /** 默认最大回溯跳数 */
14
+ const DEFAULT_MAX_HOPS = 5;
15
+ /** 拿不到任何 sid 时的兜底桶(与 client.resolveSessionId 同口径) */
16
+ const DEFAULT_SESSION_BUCKET = "default";
17
+ /** 规范化会话 id:去空白;空值落到 default 桶 */
18
+ function normalizeSid(raw) {
19
+ const sid = (raw || "").trim();
20
+ return sid || DEFAULT_SESSION_BUCKET;
21
+ }
22
+ /** 创建会话树归并器(无副作用,不做 IO;IO 由 fetchParent 注入) */
23
+ export function createSessionTree(opts) {
24
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_QUERY_TIMEOUT_MS;
25
+ const maxHops = opts.maxHops ?? DEFAULT_MAX_HOPS;
26
+ /** raw sid → 根 sid(仅缓存成功解析的结果) */
27
+ const rootCache = new Map();
28
+ /** 已标记私有的 raw sid */
29
+ const privateSids = new Set();
30
+ /** 有界查询 parentID;超时/异常 → undefined(区别于 null=确认无父) */
31
+ async function fetchParentSafe(sid) {
32
+ let timer;
33
+ try {
34
+ const query = Promise.resolve().then(() => opts.fetchParent(sid));
35
+ const timeout = new Promise((resolveTimeout) => {
36
+ timer = setTimeout(() => resolveTimeout(undefined), timeoutMs);
37
+ });
38
+ const parent = await Promise.race([query, timeout]);
39
+ if (parent === undefined)
40
+ return undefined;
41
+ if (parent === null)
42
+ return null;
43
+ const p = String(parent).trim();
44
+ return p || null;
45
+ }
46
+ catch (e) {
47
+ opts.onWarn?.(`[session-tree] parent lookup failed sid=${sid}: ${e?.message || String(e)}`);
48
+ return undefined;
49
+ }
50
+ finally {
51
+ if (timer)
52
+ clearTimeout(timer);
53
+ }
54
+ }
55
+ function knownKey(raw) {
56
+ const sid = normalizeSid(raw);
57
+ if (privateSids.has(sid))
58
+ return sid;
59
+ return rootCache.get(sid) || sid;
60
+ }
61
+ async function browserKey(raw) {
62
+ const sid = normalizeSid(raw);
63
+ if (privateSids.has(sid))
64
+ return sid;
65
+ const cached = rootCache.get(sid);
66
+ if (cached)
67
+ return cached;
68
+ // 沿 parentID 向上回溯;路径上的节点在成功时一并缓存
69
+ const path = [sid];
70
+ const seen = new Set([sid]);
71
+ let current = sid;
72
+ for (let hop = 0; hop < maxHops; hop++) {
73
+ const parent = await fetchParentSafe(current);
74
+ if (parent === undefined) {
75
+ opts.onWarn?.(`[session-tree] resolve failed at sid=${current}; fallback to raw sid=${sid}`);
76
+ return sid; // 失败不缓存,下次重试
77
+ }
78
+ if (parent === null) {
79
+ // current 是根:路径上所有节点都归并到它
80
+ for (const node of path)
81
+ rootCache.set(node, current);
82
+ return current;
83
+ }
84
+ if (seen.has(parent)) {
85
+ opts.onWarn?.(`[session-tree] cycle detected (sid=${sid}, repeated=${parent}); fallback to raw sid`);
86
+ return sid;
87
+ }
88
+ if (hop === maxHops - 1) {
89
+ opts.onWarn?.(`[session-tree] exceeded maxHops=${maxHops} (sid=${sid}); fallback to raw sid`);
90
+ return sid;
91
+ }
92
+ seen.add(parent);
93
+ path.push(parent);
94
+ current = parent;
95
+ }
96
+ return sid;
97
+ }
98
+ function markPrivate(raw) {
99
+ const sid = (raw || "").trim();
100
+ if (sid)
101
+ privateSids.add(sid);
102
+ }
103
+ function isPrivate(raw) {
104
+ return privateSids.has((raw || "").trim());
105
+ }
106
+ function forget(sid) {
107
+ if (!sid)
108
+ return;
109
+ privateSids.delete(sid);
110
+ rootCache.delete(sid);
111
+ // 删除所有映射到该会话的后代缓存(sid 是根/某层祖先时)
112
+ for (const [node, root] of [...rootCache]) {
113
+ if (root === sid)
114
+ rootCache.delete(node);
115
+ }
116
+ }
117
+ function cachedRoot(raw) {
118
+ return rootCache.get((raw || "").trim());
119
+ }
120
+ return { browserKey, knownKey, markPrivate, isPrivate, forget, cachedRoot };
121
+ }
@@ -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
+ }