@shgroup/dsh-serenity-hooks 1.128.2 → 1.129.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.
- package/dsh.plugin.json +1 -1
- package/lib/browser/cdp.d.ts +83 -0
- package/lib/browser/extend.d.ts +124 -0
- package/lib/browser/home.d.ts +43 -0
- package/lib/browser/ledger.d.ts +27 -14
- package/lib/browser/process.d.ts +68 -6
- package/lib/browser/service.d.ts +58 -2
- package/lib/browser/state.d.ts +10 -0
- package/lib/index.js +974 -85
- package/package.json +1 -1
package/lib/index.js
CHANGED
|
@@ -19,10 +19,10 @@ import { a as registerImAccountImpl, i as normalizeAccountChannel, n as getImAcc
|
|
|
19
19
|
import { createRequire } from "node:module";
|
|
20
20
|
import z from "@deepseek-ai/schemastery";
|
|
21
21
|
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
22
|
-
import { basename, dirname, extname, join, relative, resolve } from "node:path";
|
|
22
|
+
import { basename, dirname, extname, join, relative, resolve, sep } from "node:path";
|
|
23
23
|
import { appendFileSync, chmodSync, closeSync, cpSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, rmdirSync, statSync, unlinkSync, utimesSync, writeFileSync } from "node:fs";
|
|
24
24
|
import { execFileSync, spawn } from "node:child_process";
|
|
25
|
-
import { platform } from "node:os";
|
|
25
|
+
import { homedir, platform } from "node:os";
|
|
26
26
|
import { fileURLToPath } from "node:url";
|
|
27
27
|
import { createHash, randomBytes } from "node:crypto";
|
|
28
28
|
import { Resvg, initWasm } from "@resvg/resvg-wasm";
|
|
@@ -14860,7 +14860,7 @@ async function runWeixinHook(root, hookRel, event, timeoutMs = WEIXIN_HOOK_TIMEO
|
|
|
14860
14860
|
const json = JSON.stringify(event);
|
|
14861
14861
|
const runners = [["bun", [scriptAbs]], [process.execPath, [scriptAbs]]];
|
|
14862
14862
|
for (const [cmd, args] of runners) try {
|
|
14863
|
-
const res = await runOnce(cmd, args, json, timeoutMs);
|
|
14863
|
+
const res = await runOnce$1(cmd, args, json, timeoutMs);
|
|
14864
14864
|
if (!res.ok && res.code === "ENOENT") continue;
|
|
14865
14865
|
return res;
|
|
14866
14866
|
} catch {
|
|
@@ -14872,7 +14872,7 @@ async function runWeixinHook(root, hookRel, event, timeoutMs = WEIXIN_HOOK_TIMEO
|
|
|
14872
14872
|
};
|
|
14873
14873
|
}
|
|
14874
14874
|
/** 单次 spawn 执行(Promise 化 + 超时 kill + 输出截断) */
|
|
14875
|
-
function runOnce(cmd, args, json, timeoutMs) {
|
|
14875
|
+
function runOnce$1(cmd, args, json, timeoutMs) {
|
|
14876
14876
|
return new Promise((resolvePromise) => {
|
|
14877
14877
|
let settled = false;
|
|
14878
14878
|
let stdout = "";
|
|
@@ -18273,7 +18273,7 @@ const TEXT_TAGS = [
|
|
|
18273
18273
|
"text"
|
|
18274
18274
|
];
|
|
18275
18275
|
/** 属性值 → 数字;缺失或非数字返回 undefined(不抛) */
|
|
18276
|
-
function num(v) {
|
|
18276
|
+
function num$1(v) {
|
|
18277
18277
|
if (v === void 0) return void 0;
|
|
18278
18278
|
const t = v.trim();
|
|
18279
18279
|
if (t === "") return void 0;
|
|
@@ -18284,7 +18284,7 @@ function num(v) {
|
|
|
18284
18284
|
function quad(v) {
|
|
18285
18285
|
const parts = v.split(",");
|
|
18286
18286
|
if (parts.length !== 4) return void 0;
|
|
18287
|
-
const [x0, y0, x1, y1] = parts.map(num);
|
|
18287
|
+
const [x0, y0, x1, y1] = parts.map(num$1);
|
|
18288
18288
|
if (x0 === void 0 || y0 === void 0 || x1 === void 0 || y1 === void 0) return void 0;
|
|
18289
18289
|
return {
|
|
18290
18290
|
x0,
|
|
@@ -18413,8 +18413,8 @@ function parseDsl(source) {
|
|
|
18413
18413
|
}
|
|
18414
18414
|
i = next;
|
|
18415
18415
|
if (tag === "diagram") {
|
|
18416
|
-
const w = num(attrs.width);
|
|
18417
|
-
const h = num(attrs.height);
|
|
18416
|
+
const w = num$1(attrs.width);
|
|
18417
|
+
const h = num$1(attrs.height);
|
|
18418
18418
|
if (w !== void 0) model.W = w;
|
|
18419
18419
|
if (h !== void 0) model.H = h;
|
|
18420
18420
|
if (attrs.domain !== void 0) {
|
|
@@ -18450,9 +18450,9 @@ function parseDsl(source) {
|
|
|
18450
18450
|
}
|
|
18451
18451
|
if (tag === "legend") {
|
|
18452
18452
|
model.legend = {
|
|
18453
|
-
x: num(attrs.x) ?? 0,
|
|
18454
|
-
y: num(attrs.y) ?? 0,
|
|
18455
|
-
size: num(attrs.size) ?? 12
|
|
18453
|
+
x: num$1(attrs.x) ?? 0,
|
|
18454
|
+
y: num$1(attrs.y) ?? 0,
|
|
18455
|
+
size: num$1(attrs.size) ?? 12
|
|
18456
18456
|
};
|
|
18457
18457
|
continue;
|
|
18458
18458
|
}
|
|
@@ -18480,7 +18480,7 @@ function parseDsl(source) {
|
|
|
18480
18480
|
y0: Math.min(b.y0, b.y1),
|
|
18481
18481
|
x1: Math.max(b.x0, b.x1),
|
|
18482
18482
|
y1: Math.max(b.y0, b.y1),
|
|
18483
|
-
size: num(attrs.size) ?? 13,
|
|
18483
|
+
size: num$1(attrs.size) ?? 13,
|
|
18484
18484
|
fill: attrs.fill ?? ""
|
|
18485
18485
|
};
|
|
18486
18486
|
if (label !== void 0) rect.label = label;
|
|
@@ -18502,15 +18502,15 @@ function parseDsl(source) {
|
|
|
18502
18502
|
ln
|
|
18503
18503
|
};
|
|
18504
18504
|
if (attrs.color !== void 0) seg.color = attrs.color;
|
|
18505
|
-
const w = num(attrs.width);
|
|
18505
|
+
const w = num$1(attrs.width);
|
|
18506
18506
|
if (w !== void 0) seg.width = w;
|
|
18507
18507
|
if (attrs.dash !== void 0) seg.dash = attrs.dash;
|
|
18508
18508
|
model.segments.push(seg);
|
|
18509
18509
|
continue;
|
|
18510
18510
|
}
|
|
18511
18511
|
if (tag === "text") {
|
|
18512
|
-
const x = num(attrs.x);
|
|
18513
|
-
const y = num(attrs.y);
|
|
18512
|
+
const x = num$1(attrs.x);
|
|
18513
|
+
const y = num$1(attrs.y);
|
|
18514
18514
|
if (x === void 0 || y === void 0) {
|
|
18515
18515
|
fail(tagIndex, ln, "text 缺 x 或 y");
|
|
18516
18516
|
continue;
|
|
@@ -18521,7 +18521,7 @@ function parseDsl(source) {
|
|
|
18521
18521
|
y,
|
|
18522
18522
|
text: content,
|
|
18523
18523
|
align: al === "center" || al === "middle" ? "center" : al === "right" || al === "end" ? "right" : "left",
|
|
18524
|
-
size: num(attrs.size) ?? 12.5,
|
|
18524
|
+
size: num$1(attrs.size) ?? 12.5,
|
|
18525
18525
|
ln
|
|
18526
18526
|
};
|
|
18527
18527
|
if (attrs.color !== void 0) t.color = attrs.color;
|
|
@@ -19176,25 +19176,90 @@ function findLeaseBySession(leases, sessionId) {
|
|
|
19176
19176
|
return leases.find((l) => l.sessionId === sessionId) ?? null;
|
|
19177
19177
|
}
|
|
19178
19178
|
//#endregion
|
|
19179
|
+
//#region src/browser/home.ts
|
|
19180
|
+
/**
|
|
19181
|
+
* browser/home.ts — 槽位体系的**全局**家目录(跨 CCC 唯一)
|
|
19182
|
+
*
|
|
19183
|
+
* 🔴🔴 **这个文件修的是一个根本性缺陷**(owner 2026-11-10 指出):
|
|
19184
|
+
*
|
|
19185
|
+
* 原实现把台账放在 `<CCC 根>/.opencode/browser-slots.json`,**每个 CCC 各一份**。
|
|
19186
|
+
* 而端口 `9301..9320` 是**全机唯一资源**,Chrome 进程也是**全机唯一**的。
|
|
19187
|
+
* ⇒ 同一台机器上跑两个 CCC 时:
|
|
19188
|
+
* · CCC-A 读自己的台账 ⇒ 认为 b1 空闲 ⇒ 起在 9301
|
|
19189
|
+
* · CCC-B 读自己的台账 ⇒ **也**认为 b1 空闲 ⇒ **也想在 9301**
|
|
19190
|
+
* 而 `portHolders` 只能事后发现端口被占,**无法阻止两个 CCC 同时决定用同一个槽**。
|
|
19191
|
+
*
|
|
19192
|
+
* 判据(这条比修法值钱):**资源的唯一性必须由"状态载体的唯一性"保证**,
|
|
19193
|
+
* ⛔ 不能靠"每个使用者各自记一份、然后指望它们对得上"。
|
|
19194
|
+
* —— 2026-11-09 那次「槽位租到了却没人能操作」是**同一族**的另一个形态:
|
|
19195
|
+
* 两处各记一份端口表,于是必然漂。那次漂在**端口区间**,这次漂在**归属**。
|
|
19196
|
+
*
|
|
19197
|
+
* ## 落点
|
|
19198
|
+
*
|
|
19199
|
+
* `~/.dsh/serenity-browser-slots/` ← 默认(宿主存储家,天然跨 CCC)
|
|
19200
|
+
* ledger.json 唯一台账
|
|
19201
|
+
* b1/{user-data,identity.json,shots,chrome.log}
|
|
19202
|
+
*
|
|
19203
|
+
* 🔴 **为什么不放某个 CCC 里**:放谁家就等于让那个 CCC 当"主",
|
|
19204
|
+
* 其余 CCC 的权力关系会隐式绑定到目录归属上 —— 那是治理问题,不是技术问题。
|
|
19205
|
+
* 放宿主家 = 中立,且随宿主(而不是随某个 CCC 的 git)存活。
|
|
19206
|
+
*
|
|
19207
|
+
* 🔴 **为什么 profile 也必须是全局的**(不只台账):
|
|
19208
|
+
* 槽位 b1 今天给 CCC-A、明天给 CCC-B。若 profile 跟着 CCC 走,
|
|
19209
|
+
* 那"b1 的登录态"就会有两份,而**两份登录态在读数上无法区分** ——
|
|
19210
|
+
* 你会以为自己登着,其实是另一个 profile。⇒ 一个槽位**只有一份** profile。
|
|
19211
|
+
*
|
|
19212
|
+
* ⚠️ 覆盖:`SERENITY_BROWSER_SLOTS_DIR`(测试用;也便于把它挪到别的盘)。
|
|
19213
|
+
*/
|
|
19214
|
+
/** 环境变量名(覆盖全局家目录) */
|
|
19215
|
+
const SLOTS_DIR_ENV = "SERENITY_BROWSER_SLOTS_DIR";
|
|
19216
|
+
/**
|
|
19217
|
+
* 槽位体系的全局家目录。
|
|
19218
|
+
*
|
|
19219
|
+
* 判据:**不含任何 CCC 根** —— 这正是它跨 CCC 的唯一原因。
|
|
19220
|
+
* ⛔ 不要给它加一个 `cccRoot` 参数(那会立刻退回"每个 CCC 各一份"的原缺陷)。
|
|
19221
|
+
*/
|
|
19222
|
+
function slotsHomeDir(env = process.env) {
|
|
19223
|
+
const override = env[SLOTS_DIR_ENV];
|
|
19224
|
+
if (override && override.trim() !== "") return override;
|
|
19225
|
+
return join(homedir(), ".dsh", "serenity-browser-slots");
|
|
19226
|
+
}
|
|
19227
|
+
//#endregion
|
|
19179
19228
|
//#region src/browser/ledger.ts
|
|
19180
19229
|
/**
|
|
19181
|
-
* browser/ledger.ts —
|
|
19230
|
+
* browser/ledger.ts — 槽位台账(**全局唯一**真相源:谁租了哪个槽)
|
|
19231
|
+
*
|
|
19232
|
+
* 落点:`<全局家目录>/ledger.json`(默认 `~/.dsh/serenity-browser-slots/`)
|
|
19233
|
+
*
|
|
19234
|
+
* 🔴🔴 **它就是全局的,不跟着 CCC 走**(2026-11-10 owner 纠正后改)。
|
|
19182
19235
|
*
|
|
19183
|
-
*
|
|
19236
|
+
* 原落点是 `<CCC>/.opencode/browser-slots.json` —— **每个 CCC 各一份**,
|
|
19237
|
+
* 而 20 个槽位 / 端口 9301..9320 / Chrome 进程都是**全机唯一**的。
|
|
19238
|
+
* 一个宿主实测服务 **3 个 CCC** ⇒ 三份台账各自认为"b1 空闲" ⇒ 抢同一个端口。
|
|
19239
|
+
* ⇒ 判据:**资源的唯一性必须由状态载体的唯一性保证**,⛔ 不能靠各自记账再指望对上。
|
|
19184
19240
|
*
|
|
19185
|
-
* 🔴
|
|
19186
|
-
*
|
|
19187
|
-
* (它找不到自己的条目),槽位就永久泄漏。台账必须比它的进程活得久。
|
|
19241
|
+
* 🔴 **为什么台账必须比它的进程活得久**:丢了之后占用者再也无法 release
|
|
19242
|
+
* (它找不到自己的条目),槽位就永久泄漏。
|
|
19188
19243
|
*
|
|
19189
|
-
* 🔴
|
|
19244
|
+
* 🔴 **并发**:20 个槽位会被**多条轨迹 + 多个 CCC 同时**争抢(本机 13 个 live 会话)。
|
|
19190
19245
|
* 整文件读改写会**静默丢键**(仓里 `localstore.json` 已为同一个病付过一次代价)。
|
|
19191
19246
|
* ⇒ 这里用 `O_EXCL` 排他锁 + temp→rename 原子替换,并带**持锁者崩溃自动回收**。
|
|
19192
19247
|
*
|
|
19193
19248
|
* ⚠️ 已知边界(如实登记):锁是**单机文件锁**,只在同一台机器、同一个文件系统上成立。
|
|
19194
|
-
*
|
|
19249
|
+
* 槽位天然只属于本机(Chrome 是本地进程),故够用;⛔ 不要据此推断它支持多机。
|
|
19195
19250
|
*/
|
|
19196
|
-
/**
|
|
19197
|
-
const
|
|
19251
|
+
/** 台账文件名(在全局家目录内) */
|
|
19252
|
+
const LEDGER_FILENAME = "ledger.json";
|
|
19253
|
+
/**
|
|
19254
|
+
* 台账绝对路径。
|
|
19255
|
+
*
|
|
19256
|
+
* 🔴 签名里**刻意没有 `root`**:这个台账不属于任何 CCC。
|
|
19257
|
+
* 任何想按 CCC 分家的改动都会立刻退回原缺陷(见文件头)。
|
|
19258
|
+
* `root`(CCC 根)只作为**租约里的一个字段**记录,用来回答"谁租的"。
|
|
19259
|
+
*/
|
|
19260
|
+
function ledgerPath() {
|
|
19261
|
+
return join(slotsHomeDir(), LEDGER_FILENAME);
|
|
19262
|
+
}
|
|
19198
19263
|
/** 锁文件后缀 */
|
|
19199
19264
|
const LOCK_SUFFIX = ".lock";
|
|
19200
19265
|
/** 锁的存活上限:超过即视为持锁者已崩溃(必须是"远大于一次读改写的耗时") */
|
|
@@ -19202,17 +19267,14 @@ const LOCK_STALE_MS = 1e4;
|
|
|
19202
19267
|
/** 持锁自旋:最多等这么久(超过即放弃并报错,⛔ 不无限等) */
|
|
19203
19268
|
const LOCK_WAIT_MS = 8e3;
|
|
19204
19269
|
const EMPTY = {
|
|
19205
|
-
version:
|
|
19270
|
+
version: 2,
|
|
19206
19271
|
leases: {},
|
|
19207
19272
|
updatedAt: 0,
|
|
19208
19273
|
backoff: {}
|
|
19209
19274
|
};
|
|
19210
|
-
|
|
19211
|
-
|
|
19212
|
-
|
|
19213
|
-
/** 读台账。文件缺失/损坏 ⇒ 返回空台账(⛔ 不抛错:一次坏文件不该炸掉整条轨迹的所有槽位操作) */
|
|
19214
|
-
function readLedger(root) {
|
|
19215
|
-
const p = ledgerPath(root);
|
|
19275
|
+
/** 读台账。文件缺失/损坏 ⇒ 返回空台账(⛔ 不抛错:一次坏文件不该炸掉所有槽位操作) */
|
|
19276
|
+
function readLedger() {
|
|
19277
|
+
const p = ledgerPath();
|
|
19216
19278
|
if (!existsSync(p)) return {
|
|
19217
19279
|
...EMPTY,
|
|
19218
19280
|
leases: {}
|
|
@@ -19229,6 +19291,7 @@ function readLedger(root) {
|
|
|
19229
19291
|
slot: n,
|
|
19230
19292
|
sessionId: typeof l.sessionId === "string" ? l.sessionId : "",
|
|
19231
19293
|
trajectory: typeof l.trajectory === "string" ? l.trajectory : "",
|
|
19294
|
+
cccRoot: typeof l.cccRoot === "string" ? l.cccRoot : "",
|
|
19232
19295
|
leasedAt: Number(l.leasedAt) || 0,
|
|
19233
19296
|
lastActionAt: Number(l.lastActionAt) || Number(l.leasedAt) || 0,
|
|
19234
19297
|
nudges: Number(l.nudges) || 0,
|
|
@@ -19248,7 +19311,7 @@ function readLedger(root) {
|
|
|
19248
19311
|
};
|
|
19249
19312
|
}
|
|
19250
19313
|
return {
|
|
19251
|
-
version: Number(raw.version) ||
|
|
19314
|
+
version: Number(raw.version) || 2,
|
|
19252
19315
|
leases,
|
|
19253
19316
|
updatedAt: Number(raw.updatedAt) || 0,
|
|
19254
19317
|
backoff
|
|
@@ -19261,8 +19324,8 @@ function readLedger(root) {
|
|
|
19261
19324
|
}
|
|
19262
19325
|
}
|
|
19263
19326
|
/** 原子写:temp → rename(rename 在同文件系统内是原子的) */
|
|
19264
|
-
function writeLedger(
|
|
19265
|
-
const p = ledgerPath(
|
|
19327
|
+
function writeLedger(ledger) {
|
|
19328
|
+
const p = ledgerPath();
|
|
19266
19329
|
mkdirSync(dirname(p), { recursive: true });
|
|
19267
19330
|
const tmp = `${p}.tmp-${process.pid}-${Date.now()}`;
|
|
19268
19331
|
const body = JSON.stringify({
|
|
@@ -19287,8 +19350,8 @@ function tryBreakStaleLock(lock) {
|
|
|
19287
19350
|
* 调用方忘记 unlock(或在中途抛错)会**永久锁死**整个槽位系统,而这**没有任何信号**。
|
|
19288
19351
|
* 把锁的生命周期绑在一个同步函数的执行期上,是唯一不依赖调用方纪律的做法。
|
|
19289
19352
|
*/
|
|
19290
|
-
function withLedger(
|
|
19291
|
-
const p = ledgerPath(
|
|
19353
|
+
function withLedger(update) {
|
|
19354
|
+
const p = ledgerPath();
|
|
19292
19355
|
mkdirSync(dirname(p), { recursive: true });
|
|
19293
19356
|
const lock = p + LOCK_SUFFIX;
|
|
19294
19357
|
const deadline = Date.now() + LOCK_WAIT_MS;
|
|
@@ -19304,8 +19367,8 @@ function withLedger(root, update) {
|
|
|
19304
19367
|
}
|
|
19305
19368
|
if (!acquired) throw new Error(`槽位台账被占用超过 ${LOCK_WAIT_MS}ms,放弃本次操作(锁文件:${lock})。\n 判据:持锁者若已崩溃,锁会在 ${LOCK_STALE_MS}ms 后自动回收;请稍后重试。\n ⛔ 不要手工删锁 —— 那可能与一个正在写的进程撞车。`);
|
|
19306
19369
|
try {
|
|
19307
|
-
const { ledger, result } = update(readLedger(
|
|
19308
|
-
writeLedger(
|
|
19370
|
+
const { ledger, result } = update(readLedger());
|
|
19371
|
+
writeLedger(ledger);
|
|
19309
19372
|
return result;
|
|
19310
19373
|
} finally {
|
|
19311
19374
|
rmSync(lock, { force: true });
|
|
@@ -19332,18 +19395,57 @@ function listLeases(ledger) {
|
|
|
19332
19395
|
* 3. **进程必须能被独立杀死**(`--user-data-dir` 指向槽位专属目录 ⇒ 可按目录精确认领,
|
|
19333
19396
|
* 不会误杀 user 自己的浏览器 —— 这是本次事故里我差点犯的第二个错)。
|
|
19334
19397
|
*/
|
|
19335
|
-
|
|
19336
|
-
const
|
|
19337
|
-
function slotPaths(root, n) {
|
|
19338
|
-
const home = join(root, SLOTS_REL, slotLabel(n));
|
|
19398
|
+
function slotPaths(n, homeDir) {
|
|
19399
|
+
const home = join(homeDir ?? slotsHomeDir(), slotLabel(n));
|
|
19339
19400
|
return {
|
|
19340
19401
|
home,
|
|
19341
19402
|
profile: join(home, "user-data"),
|
|
19403
|
+
identity: join(home, "identity.json"),
|
|
19342
19404
|
shots: join(home, "shots"),
|
|
19343
19405
|
log: join(home, "chrome.log"),
|
|
19344
19406
|
pidFile: join(home, "pid")
|
|
19345
19407
|
};
|
|
19346
19408
|
}
|
|
19409
|
+
/** 读槽位身份(不存在/损坏 ⇒ null,⛔ 不抛) */
|
|
19410
|
+
function readSlotIdentity(n, homeDir) {
|
|
19411
|
+
const p = slotPaths(n, homeDir).identity;
|
|
19412
|
+
try {
|
|
19413
|
+
const raw = JSON.parse(readFileSync(p, "utf8"));
|
|
19414
|
+
if (!raw || typeof raw !== "object") return null;
|
|
19415
|
+
return {
|
|
19416
|
+
slot: Number(raw.slot) || n,
|
|
19417
|
+
label: typeof raw.label === "string" ? raw.label : slotLabel(n),
|
|
19418
|
+
port: Number(raw.port) || slotPort(n),
|
|
19419
|
+
cccRoot: typeof raw.cccRoot === "string" ? raw.cccRoot : "",
|
|
19420
|
+
sessionId: typeof raw.sessionId === "string" ? raw.sessionId : "",
|
|
19421
|
+
trajectory: typeof raw.trajectory === "string" ? raw.trajectory : "",
|
|
19422
|
+
leasedAt: Number(raw.leasedAt) || 0,
|
|
19423
|
+
writtenAt: Number(raw.writtenAt) || 0
|
|
19424
|
+
};
|
|
19425
|
+
} catch {
|
|
19426
|
+
return null;
|
|
19427
|
+
}
|
|
19428
|
+
}
|
|
19429
|
+
/**
|
|
19430
|
+
* 写槽位身份(**原子写**:temp → rename)。
|
|
19431
|
+
*
|
|
19432
|
+
* ⚠️ 与台账同一个纪律:**只写事实,不写状态** —— 状态由 `state.ts` 现算。
|
|
19433
|
+
* 这里写的是"这个 profile 属于谁",那是**租出那一刻的事实**,不会随闲置时长变化。
|
|
19434
|
+
*/
|
|
19435
|
+
function writeSlotIdentity(ident, homeDir) {
|
|
19436
|
+
const p = slotPaths(ident.slot, homeDir).identity;
|
|
19437
|
+
mkdirSync(dirname(p), { recursive: true });
|
|
19438
|
+
const tmp = `${p}.tmp-${process.pid}-${Date.now()}`;
|
|
19439
|
+
writeFileSync(tmp, JSON.stringify({
|
|
19440
|
+
...ident,
|
|
19441
|
+
writtenAt: Date.now()
|
|
19442
|
+
}, null, 2), "utf8");
|
|
19443
|
+
renameSync(tmp, p);
|
|
19444
|
+
}
|
|
19445
|
+
/** 释放时清掉身份(⛔ 保留 profile 本身 —— 登录态是槽位的资产) */
|
|
19446
|
+
function clearSlotIdentity(n, homeDir) {
|
|
19447
|
+
rmSync(slotPaths(n, homeDir).identity, { force: true });
|
|
19448
|
+
}
|
|
19347
19449
|
/**
|
|
19348
19450
|
* 挑 Chrome 可执行文件。
|
|
19349
19451
|
*
|
|
@@ -19450,15 +19552,19 @@ function buildArgs(n, paths, display) {
|
|
|
19450
19552
|
/**
|
|
19451
19553
|
* 启动一个槽位(**不等待 CDP 就绪** —— 就绪判定走 {@link waitCdp},与既有实现同款纪律:
|
|
19452
19554
|
* `launch` 立即返回,不让调用方卡在一个可能永远不返回的等待上)。
|
|
19555
|
+
*
|
|
19556
|
+
* 🔴 v1.129.0:签名里**删掉了 `root`** —— 它曾是一个**完全没被读过**的参数
|
|
19557
|
+
* (槽位目录已全局化,见 `home.ts`)。留着一个不读的参数是**声明与行为分叉**:
|
|
19558
|
+
* 下一个人读签名会以为"启动是跟着某个 CCC 走的",而事实相反(D289 同族)。
|
|
19453
19559
|
*/
|
|
19454
|
-
function launchSlot(
|
|
19560
|
+
function launchSlot(n) {
|
|
19455
19561
|
const chrome = findChrome();
|
|
19456
19562
|
if (!chrome) return {
|
|
19457
19563
|
ok: false,
|
|
19458
19564
|
pid: 0,
|
|
19459
19565
|
detail: "未找到 Chrome/Chromium。候选路径:" + CHROME_CANDIDATES.join(" / ") + "\n ⇒ 装一个或用 `browser_slot` 的 --chrome 指定路径(该选项尚未实现)。"
|
|
19460
19566
|
};
|
|
19461
|
-
const paths = slotPaths(
|
|
19567
|
+
const paths = slotPaths(n);
|
|
19462
19568
|
if (!existsSync(paths.home)) mkdirSync(paths.home, { recursive: true });
|
|
19463
19569
|
if (!existsSync(paths.profile)) mkdirSync(paths.profile, { recursive: true });
|
|
19464
19570
|
if (!existsSync(paths.shots)) mkdirSync(paths.shots, { recursive: true });
|
|
@@ -19663,9 +19769,11 @@ function killPid(pid, waitMs = 1500) {
|
|
|
19663
19769
|
*
|
|
19664
19770
|
* 顺序不可换:先按 profile 认领(进程可能换过 pid,台账里那个未必还准)→ 杀 →
|
|
19665
19771
|
* 清 pid 文件 → **保留 profile 目录**(登录态是槽位的资产,⛔ 不因一次回收就丢)。
|
|
19772
|
+
*
|
|
19773
|
+
* 🔴 v1.129.0:同样删掉未被读的 `root` 参数(理由同 {@link launchSlot})。
|
|
19666
19774
|
*/
|
|
19667
|
-
function destroySlot(
|
|
19668
|
-
const paths = slotPaths(
|
|
19775
|
+
function destroySlot(n, pidHint = 0) {
|
|
19776
|
+
const paths = slotPaths(n);
|
|
19669
19777
|
const pids = new Set(findPidsByProfile(paths.profile));
|
|
19670
19778
|
if (pidHint > 0) pids.add(pidHint);
|
|
19671
19779
|
const killed = [];
|
|
@@ -19742,7 +19850,7 @@ async function waitCdp(root, n, timeoutMs = 2e4, stableMs = 2500) {
|
|
|
19742
19850
|
} else consecutive = 0;
|
|
19743
19851
|
await new Promise((r) => setTimeout(r, 300));
|
|
19744
19852
|
}
|
|
19745
|
-
const paths = slotPaths(
|
|
19853
|
+
const paths = slotPaths(n);
|
|
19746
19854
|
if (!everReady) return {
|
|
19747
19855
|
ok: false,
|
|
19748
19856
|
kind: "never_ready",
|
|
@@ -19769,6 +19877,484 @@ function normalizeSlotId(raw) {
|
|
|
19769
19877
|
return slotNumber(s);
|
|
19770
19878
|
}
|
|
19771
19879
|
//#endregion
|
|
19880
|
+
//#region src/browser/cdp.ts
|
|
19881
|
+
/**
|
|
19882
|
+
* browser/cdp.ts — 槽位的 CDP 客户端(页面操作的唯一实现)
|
|
19883
|
+
*
|
|
19884
|
+
* 🔴🔴 **这个文件的存在理由**(owner 2026-11-10 令):
|
|
19885
|
+
* 「我希望所有浏览器能力都集中到这个 browser_slot」
|
|
19886
|
+
*
|
|
19887
|
+
* 在此之前能力被**切在两处**:`browser_slot` 管槽位(端口/进程/归属),
|
|
19888
|
+
* `browser` MSM 管页面(goto/eval/shot)。而两者**各写一份端口表**,
|
|
19889
|
+
* 于是 2026-11-09 出现「槽位租到了、没有任何工具能操作它」——
|
|
19890
|
+
* 两段端口一个数都不重叠。**那不是配置不一致,是同一件事有两个实现。**
|
|
19891
|
+
*
|
|
19892
|
+
* ⇒ 本文件把页面操作搬进 ACC,`browser` MSM 随之退场(只留一条退役指引)。
|
|
19893
|
+
*
|
|
19894
|
+
* ## 为什么零依赖(不引 `ws` 包)
|
|
19895
|
+
*
|
|
19896
|
+
* 运行时自带 `WebSocket`(Node ≥21 / bun 都有),CDP 只需要
|
|
19897
|
+
* 「发一条 JSON、按 id 收一条结果」这一个能力。引第三方 ws 包会让
|
|
19898
|
+
* 装机面多一个运行时依赖,而它换来的是本文件 40 行就能写完的东西。
|
|
19899
|
+
* (先例:`home-browser/scripts/browser.ts` 的注释里也记着同一个取舍。)
|
|
19900
|
+
*
|
|
19901
|
+
* ## 与既有实现的关系
|
|
19902
|
+
*
|
|
19903
|
+
* 语义逐条对齐 `home-browser/scripts/browser.ts` 的 12 个子命令 ——
|
|
19904
|
+
* 那些行为有真实使用与踩坑记录(4 条轨迹的手册在用)。搬的时候**不为好看改语义**。
|
|
19905
|
+
*/
|
|
19906
|
+
/** 连一个 WS 端点(带超时;超时即拒绝,⛔ 不无限等) */
|
|
19907
|
+
async function wsConnect(url, timeoutMs = 8e3) {
|
|
19908
|
+
const ws = new WebSocket(url);
|
|
19909
|
+
await new Promise((res, rej) => {
|
|
19910
|
+
const t = setTimeout(() => rej(/* @__PURE__ */ new Error(`WebSocket 连接超时: ${url}`)), timeoutMs);
|
|
19911
|
+
ws.onopen = () => {
|
|
19912
|
+
clearTimeout(t);
|
|
19913
|
+
res();
|
|
19914
|
+
};
|
|
19915
|
+
ws.onerror = (ev) => {
|
|
19916
|
+
clearTimeout(t);
|
|
19917
|
+
rej(/* @__PURE__ */ new Error(`WebSocket 连接失败: ${String(ev?.message ?? "error")}`));
|
|
19918
|
+
};
|
|
19919
|
+
});
|
|
19920
|
+
return ws;
|
|
19921
|
+
}
|
|
19922
|
+
/** 挂上 id→promise 相关器 */
|
|
19923
|
+
function attach(ws) {
|
|
19924
|
+
const conn = {
|
|
19925
|
+
ws,
|
|
19926
|
+
nextId: 1,
|
|
19927
|
+
pending: /* @__PURE__ */ new Map()
|
|
19928
|
+
};
|
|
19929
|
+
ws.onmessage = (ev) => {
|
|
19930
|
+
let msg;
|
|
19931
|
+
try {
|
|
19932
|
+
msg = JSON.parse(typeof ev.data === "string" ? ev.data : String(ev.data));
|
|
19933
|
+
} catch {
|
|
19934
|
+
return;
|
|
19935
|
+
}
|
|
19936
|
+
if (msg.id && conn.pending.has(msg.id)) {
|
|
19937
|
+
const p = conn.pending.get(msg.id);
|
|
19938
|
+
conn.pending.delete(msg.id);
|
|
19939
|
+
if (msg.error) p.rej(/* @__PURE__ */ new Error(`${msg.error.message ?? "CDP error"}${msg.error.data ? ` (${msg.error.data})` : ""}`));
|
|
19940
|
+
else p.res(msg.result);
|
|
19941
|
+
}
|
|
19942
|
+
};
|
|
19943
|
+
return conn;
|
|
19944
|
+
}
|
|
19945
|
+
/** 发一条 CDP 方法调用并等结果 */
|
|
19946
|
+
function cdpRaw(conn, method, params = {}, timeoutMs = 3e4) {
|
|
19947
|
+
const id = conn.nextId++;
|
|
19948
|
+
return new Promise((res, rej) => {
|
|
19949
|
+
const t = setTimeout(() => {
|
|
19950
|
+
conn.pending.delete(id);
|
|
19951
|
+
rej(/* @__PURE__ */ new Error(`CDP ${method} 超时 ${timeoutMs}ms`));
|
|
19952
|
+
}, timeoutMs);
|
|
19953
|
+
conn.pending.set(id, {
|
|
19954
|
+
res: (v) => {
|
|
19955
|
+
clearTimeout(t);
|
|
19956
|
+
res(v);
|
|
19957
|
+
},
|
|
19958
|
+
rej: (e) => {
|
|
19959
|
+
clearTimeout(t);
|
|
19960
|
+
rej(e);
|
|
19961
|
+
}
|
|
19962
|
+
});
|
|
19963
|
+
conn.ws.send(JSON.stringify({
|
|
19964
|
+
id,
|
|
19965
|
+
method,
|
|
19966
|
+
params
|
|
19967
|
+
}));
|
|
19968
|
+
});
|
|
19969
|
+
}
|
|
19970
|
+
/** 取 `/json/version`(浏览器级 WS 端点) */
|
|
19971
|
+
async function httpJson(port, path) {
|
|
19972
|
+
const r = await fetch(`http://127.0.0.1:${port}${path}`, { signal: AbortSignal.timeout(8e3) });
|
|
19973
|
+
if (!r.ok) throw new Error(`CDP 端点 ${path} 返回 ${r.status}(端口 ${port})`);
|
|
19974
|
+
return await r.json();
|
|
19975
|
+
}
|
|
19976
|
+
/** 列 targets */
|
|
19977
|
+
async function listTargets(slot) {
|
|
19978
|
+
return (await httpJson(slotPort(slot), "/json/list")).map((t) => ({
|
|
19979
|
+
id: String(t.id ?? t.targetId ?? ""),
|
|
19980
|
+
type: String(t.type ?? ""),
|
|
19981
|
+
title: String(t.title ?? ""),
|
|
19982
|
+
url: String(t.url ?? "")
|
|
19983
|
+
}));
|
|
19984
|
+
}
|
|
19985
|
+
/**
|
|
19986
|
+
* 找页面 target 的 WS 端点。
|
|
19987
|
+
*
|
|
19988
|
+
* 🔴 `slot` 与 `targetId` **必须同时给**:只给 targetId 会让「哪个槽位」变成隐含状态,
|
|
19989
|
+
* 而槽位是循环复用的(b1 今天给 A 用、明天给 B 用)⇒ 那条 targetId 可能属于**另一个人**。
|
|
19990
|
+
* ⇒ 调用方必须先亮明槽位,这一层再在这个槽位的端口上找。
|
|
19991
|
+
*/
|
|
19992
|
+
async function pageWsUrl(slot, targetId) {
|
|
19993
|
+
const port = slotPort(slot);
|
|
19994
|
+
const list = await httpJson(port, "/json/list");
|
|
19995
|
+
const t = list.find((x) => x.id === targetId || x.targetId === targetId);
|
|
19996
|
+
if (!t) throw new Error(`槽位 b${slot}(端口 ${port})上没有这个 target: ${targetId}\n ⇒ 现有 target:\n${list.map((x) => ` ${String(x.type)} ${String(x.id)} ${String(x.url)}`).join("\n")}`);
|
|
19997
|
+
const ws = t.webSocketDebuggerUrl;
|
|
19998
|
+
if (!ws) throw new Error(`target ${targetId} 没有 webSocketDebuggerUrl(type=${String(t.type)})`);
|
|
19999
|
+
return String(ws);
|
|
20000
|
+
}
|
|
20001
|
+
async function browserWsUrl(slot) {
|
|
20002
|
+
const port = slotPort(slot);
|
|
20003
|
+
const v = await httpJson(port, "/json/version");
|
|
20004
|
+
if (!v.webSocketDebuggerUrl) throw new Error(`/json/version 未给 webSocketDebuggerUrl(端口 ${port})`);
|
|
20005
|
+
return String(v.webSocketDebuggerUrl);
|
|
20006
|
+
}
|
|
20007
|
+
/** 在页面里求值(`awaitPromise` + `returnByValue`,与既有实现同口径) */
|
|
20008
|
+
async function evalInPage(slot, targetId, expression, timeoutMs = 3e4) {
|
|
20009
|
+
const conn = attach(await wsConnect(await pageWsUrl(slot, targetId)));
|
|
20010
|
+
try {
|
|
20011
|
+
const r = await cdpRaw(conn, "Runtime.evaluate", {
|
|
20012
|
+
expression,
|
|
20013
|
+
awaitPromise: true,
|
|
20014
|
+
returnByValue: true,
|
|
20015
|
+
userGesture: true
|
|
20016
|
+
}, timeoutMs);
|
|
20017
|
+
const ex = r.exceptionDetails;
|
|
20018
|
+
if (ex) throw new Error(`页面内求值抛错:${ex.text ?? ""}\n ${ex.exception?.description?.slice(0, 500) ?? ""}`);
|
|
20019
|
+
return r.result?.value;
|
|
20020
|
+
} finally {
|
|
20021
|
+
conn.ws.close();
|
|
20022
|
+
}
|
|
20023
|
+
}
|
|
20024
|
+
/** 导航 */
|
|
20025
|
+
async function navigate(slot, targetId, url) {
|
|
20026
|
+
const conn = attach(await wsConnect(await pageWsUrl(slot, targetId)));
|
|
20027
|
+
try {
|
|
20028
|
+
await cdpRaw(conn, "Page.enable");
|
|
20029
|
+
await cdpRaw(conn, "Page.navigate", { url });
|
|
20030
|
+
} finally {
|
|
20031
|
+
conn.ws.close();
|
|
20032
|
+
}
|
|
20033
|
+
}
|
|
20034
|
+
/** 新建标签页,返回 targetId */
|
|
20035
|
+
async function openTab(slot, url) {
|
|
20036
|
+
const conn = attach(await wsConnect(await browserWsUrl(slot)));
|
|
20037
|
+
try {
|
|
20038
|
+
const r = await cdpRaw(conn, "Target.createTarget", { url });
|
|
20039
|
+
return String(r.targetId ?? "");
|
|
20040
|
+
} finally {
|
|
20041
|
+
conn.ws.close();
|
|
20042
|
+
}
|
|
20043
|
+
}
|
|
20044
|
+
/** 关标签页(`all=true` 关全部 page 类型的) */
|
|
20045
|
+
async function closeTab(slot, targetId, all = false) {
|
|
20046
|
+
const conn = attach(await wsConnect(await browserWsUrl(slot)));
|
|
20047
|
+
try {
|
|
20048
|
+
const list = await httpJson(slotPort(slot), "/json/list");
|
|
20049
|
+
const victims = all ? list.filter((t) => t.type === "page") : list.filter((t) => String(t.id) === targetId);
|
|
20050
|
+
if (victims.length === 0) throw new Error(`没有匹配的 target(given=${all ? "--all" : targetId})`);
|
|
20051
|
+
const closed = [];
|
|
20052
|
+
for (const v of victims) {
|
|
20053
|
+
await cdpRaw(conn, "Target.closeTarget", { targetId: String(v.id) });
|
|
20054
|
+
closed.push(String(v.id));
|
|
20055
|
+
}
|
|
20056
|
+
return closed;
|
|
20057
|
+
} finally {
|
|
20058
|
+
conn.ws.close();
|
|
20059
|
+
}
|
|
20060
|
+
}
|
|
20061
|
+
/** 正文(`document.body.innerText`) */
|
|
20062
|
+
async function pageText(slot, targetId) {
|
|
20063
|
+
const v = await evalInPage(slot, targetId, "document.body ? document.body.innerText : ''");
|
|
20064
|
+
return String(v ?? "");
|
|
20065
|
+
}
|
|
20066
|
+
/** HTML(默认截断 4000,同既有实现) */
|
|
20067
|
+
async function pageHtml(slot, targetId, max = 4e3) {
|
|
20068
|
+
const v = await evalInPage(slot, targetId, "document.documentElement.outerHTML");
|
|
20069
|
+
const s = String(v ?? "");
|
|
20070
|
+
return s.length > max ? `${s.slice(0, max)}\n… [truncated, ${s.length} chars total]` : s;
|
|
20071
|
+
}
|
|
20072
|
+
/**
|
|
20073
|
+
* 截图并存盘。
|
|
20074
|
+
*
|
|
20075
|
+
* 🔴 落点**必须在 CCC 根内**(`resolveInside` 语义在这里手写,因为本层不知道 CCC 根):
|
|
20076
|
+
* 调用方传进来的 `outAbs` 必须已经通过越界检查 —— 本函数只负责写。
|
|
20077
|
+
* ⛔ 不在这里自己算根:那会造出第二个「根在哪」的判定点。
|
|
20078
|
+
*/
|
|
20079
|
+
async function screenshot(slot, targetId, outAbs) {
|
|
20080
|
+
const conn = attach(await wsConnect(await pageWsUrl(slot, targetId)));
|
|
20081
|
+
try {
|
|
20082
|
+
const r = await cdpRaw(conn, "Page.captureScreenshot", { format: "png" }, 2e4);
|
|
20083
|
+
mkdirSync(dirname(outAbs), { recursive: true });
|
|
20084
|
+
writeFileSync(outAbs, Buffer.from(String(r.data ?? ""), "base64"));
|
|
20085
|
+
} finally {
|
|
20086
|
+
conn.ws.close();
|
|
20087
|
+
}
|
|
20088
|
+
}
|
|
20089
|
+
/** 重载,可选先装「新文档脚本」(要在应用发请求之前挂探针时用) */
|
|
20090
|
+
async function reloadPage(slot, targetId, script, timeoutMs = 25e3) {
|
|
20091
|
+
const conn = attach(await wsConnect(await pageWsUrl(slot, targetId)));
|
|
20092
|
+
try {
|
|
20093
|
+
await cdpRaw(conn, "Page.enable");
|
|
20094
|
+
if (script) await cdpRaw(conn, "Page.addScriptToEvaluateOnNewDocument", { source: script });
|
|
20095
|
+
await cdpRaw(conn, "Page.reload", { ignoreCache: true });
|
|
20096
|
+
const deadline = Date.now() + timeoutMs;
|
|
20097
|
+
let state = "";
|
|
20098
|
+
while (Date.now() < deadline) {
|
|
20099
|
+
await new Promise((r) => setTimeout(r, 400));
|
|
20100
|
+
try {
|
|
20101
|
+
const r = await cdpRaw(conn, "Runtime.evaluate", {
|
|
20102
|
+
expression: "document.readyState",
|
|
20103
|
+
returnByValue: true
|
|
20104
|
+
}, 5e3);
|
|
20105
|
+
state = String(r.result?.value ?? "");
|
|
20106
|
+
if (state === "complete") break;
|
|
20107
|
+
} catch {}
|
|
20108
|
+
}
|
|
20109
|
+
return state;
|
|
20110
|
+
} finally {
|
|
20111
|
+
conn.ws.close();
|
|
20112
|
+
}
|
|
20113
|
+
}
|
|
20114
|
+
/** 把相对落点解析成绝对路径,并做越界检查(截图用) */
|
|
20115
|
+
function resolveShotPath(cccRoot, relOrAbs) {
|
|
20116
|
+
const abs = resolve(cccRoot, relOrAbs);
|
|
20117
|
+
const rootResolved = resolve(cccRoot);
|
|
20118
|
+
if (abs !== rootResolved && !abs.startsWith(rootResolved + sep)) throw new Error(`截图落点越界(必须在 CCC 根内):${relOrAbs}`);
|
|
20119
|
+
return abs;
|
|
20120
|
+
}
|
|
20121
|
+
//#endregion
|
|
20122
|
+
//#region src/browser/extend.ts
|
|
20123
|
+
/**
|
|
20124
|
+
* browser/extend.ts — CCC 给 `browser_slot` 写扩展的唯一通道
|
|
20125
|
+
*
|
|
20126
|
+
* 🔴🔴 owner 2026-11-10 令(逐字):
|
|
20127
|
+
* 「我希望所有浏览器能力都集中到这个 browser_slot,同时这个 browser_slot 支持
|
|
20128
|
+
* CCC 给它写扩展,这样各个 CCC 可以用上最好的浏览器操作能力」
|
|
20129
|
+
*
|
|
20130
|
+
* ═══════════════════════════════════════════════════════════════════
|
|
20131
|
+
* ## 契约:**ACC 只 spawn,从不 import**(照 CRO 的 B 案,2026-09-19 owner 裁「B 是设计」)
|
|
20132
|
+
*
|
|
20133
|
+
* `cro/core.ts` 把理由写得很清楚,这里逐条适用,一条不少:
|
|
20134
|
+
* ① ACC **import** 用户的 TS ⇒ ACC 依赖 CCC 的**源码路径**,而 npm 装机版在别处
|
|
20135
|
+
* ⇒ 两条路径都要活 = **两个真相源**。
|
|
20136
|
+
* ② 用户程序**语法错会让 ACC 启动失败** ⇒ 一个用户程序的错误放倒整个容器。
|
|
20137
|
+
* ⇒ 进程边界把两件事同时挡掉:路径只需一个(文件系统),错误被隔离在子进程里。
|
|
20138
|
+
*
|
|
20139
|
+
* ⚠️ 并且浏览器扩展比 CRO 更需要在进程边界外:它要**驱动一个真浏览器**,
|
|
20140
|
+
* 而 Chrome 的失败形态(sandbox / 显示层 / 自杀窗口)已经在 2026-11-09 付过一次代价。
|
|
20141
|
+
* 让那些失败只死在一个子进程里,⛔ 不牵连宿主。
|
|
20142
|
+
*
|
|
20143
|
+
* ## 落点(文件在 = 启用,不在 = 禁用;无 enabled 字段、无注册表)
|
|
20144
|
+
*
|
|
20145
|
+
* <CCC 根>/AGENT_SESSIONS/… ← 轨迹级不看这里
|
|
20146
|
+
* <CCC 根>/browser-ext/<name>.ts ← CCC 级扩展(本模块扫这里)
|
|
20147
|
+
*
|
|
20148
|
+
* 判据(为什么放在 CCC 根而不是 `.opencode/skills`):扩展要跟着 **CCC 的 git** 走
|
|
20149
|
+
* —— `browser-ext/` 就在根上,clone 下来即可用;放进某个 skill 的 scripts 会把它
|
|
20150
|
+
* 绑死到那个 skill 的目录约定上,而扩展是**跨 skill** 的浏览器能力。
|
|
20151
|
+
*
|
|
20152
|
+
* ## 协议(stdin JSON 进、stdout JSON 出、退出码说话)
|
|
20153
|
+
*
|
|
20154
|
+
* 输入(stdin,单行 JSON):
|
|
20155
|
+
* { "name": "my-ext", "slot": 1, "port": 9301,
|
|
20156
|
+
* "args": { …调用方 --ext-arg 传的键值… },
|
|
20157
|
+
* "cccRoot": "/…", "timeoutMs": 30000 }
|
|
20158
|
+
*
|
|
20159
|
+
* 输出(stdout,**最后一个非空行**必须是 JSON):
|
|
20160
|
+
* { "ok": true, "result": <任意 JSON> }
|
|
20161
|
+
* { "ok": false, "error": "人话原因" } ← ok:false = 扩展自己报的失败
|
|
20162
|
+
*
|
|
20163
|
+
* 判据(为什么规定"最后一个非空行"):扩展可以自由 `console.log` 调试输出,
|
|
20164
|
+
* ⛔ 不要求它保持 stdout 干净 —— 那会让"加一句 debug"变成破坏契约的动作。
|
|
20165
|
+
* 反例先例:CRO 的 `parseCroOutput` 也是取最后一行 JSON。
|
|
20166
|
+
*
|
|
20167
|
+
* ## 铁律:扩展的任何失败,绝不影响 `browser_slot` 的既有动作
|
|
20168
|
+
*
|
|
20169
|
+
* 超时 kill / 非 0 退出 / spawn 失败 / stdout 不是 JSON ⇒ **仅日志 + 结构化失败返回,绝不抛**。
|
|
20170
|
+
* (先例 = `im/hook.ts` 的旁路容忍 + `cro/core.ts` 的同一条铁律。)
|
|
20171
|
+
*/
|
|
20172
|
+
/** 扩展目录(相对 CCC 根) */
|
|
20173
|
+
const EXT_DIR_REL = "browser-ext";
|
|
20174
|
+
/** 单次扩展硬超时(比 CRO 的 60s 短:它要驱动浏览器,长任务应自己分批) */
|
|
20175
|
+
const EXT_TIMEOUT_MS = 45e3;
|
|
20176
|
+
/** stdout 上限(防一个坏扩展把日志撑爆) */
|
|
20177
|
+
const EXT_STDOUT_MAX = 65536;
|
|
20178
|
+
/**
|
|
20179
|
+
* 扫一个 CCC 的扩展目录。
|
|
20180
|
+
*
|
|
20181
|
+
* ⛔ **不抛**:目录不存在、读不动 ⇒ 空数组("没有扩展"是合法状态,不是错误)。
|
|
20182
|
+
* ⚠️ 只收 `.ts` / `.mjs` / `.js`:不要收 `.test.ts` —— 那会让测试文件变成可调用的"扩展"。
|
|
20183
|
+
*/
|
|
20184
|
+
function listExtensions(cccRoot) {
|
|
20185
|
+
const dir = join(cccRoot, EXT_DIR_REL);
|
|
20186
|
+
let names;
|
|
20187
|
+
try {
|
|
20188
|
+
names = readdirSync(dir);
|
|
20189
|
+
} catch {
|
|
20190
|
+
return [];
|
|
20191
|
+
}
|
|
20192
|
+
const out = [];
|
|
20193
|
+
for (const n of names) {
|
|
20194
|
+
if (n.includes(".test.")) continue;
|
|
20195
|
+
const m = /^(.+)\.(ts|mjs|js)$/.exec(n);
|
|
20196
|
+
if (!m) continue;
|
|
20197
|
+
out.push({
|
|
20198
|
+
name: m[1],
|
|
20199
|
+
path: join(dir, n)
|
|
20200
|
+
});
|
|
20201
|
+
}
|
|
20202
|
+
return out.sort((a, b) => a.name.localeCompare(b.name));
|
|
20203
|
+
}
|
|
20204
|
+
/** 按名字找扩展(名字非法或不存在 ⇒ null,⛔ 不抛) */
|
|
20205
|
+
function findExtension(cccRoot, name) {
|
|
20206
|
+
if (!/^[A-Za-z0-9._-]{1,64}$/.test(name)) return null;
|
|
20207
|
+
return listExtensions(cccRoot).find((e) => e.name === name) ?? null;
|
|
20208
|
+
}
|
|
20209
|
+
/**
|
|
20210
|
+
* 跑一个扩展(**永不抛** —— 旁路容忍铁律)。
|
|
20211
|
+
*
|
|
20212
|
+
* runner 顺序照 `cro/core.ts`:`bun` → `process.execPath`。
|
|
20213
|
+
* 判据:`ENOENT`(二进制不存在)⇒ 试下一个;**其余失败视为最终结果**
|
|
20214
|
+
* (扩展自己报错就是报错,⛔ 不该用另一个 runner 掩盖)。
|
|
20215
|
+
*/
|
|
20216
|
+
async function runExtension(entry, payload, timeoutMs = EXT_TIMEOUT_MS) {
|
|
20217
|
+
const stdinJson = JSON.stringify(payload);
|
|
20218
|
+
const runners = [["bun", [entry.path]], [process.execPath, [entry.path]]];
|
|
20219
|
+
for (const [cmd, args] of runners) {
|
|
20220
|
+
const res = await runOnce(cmd, args, stdinJson, timeoutMs);
|
|
20221
|
+
if (!res.ok && res.code === "ENOENT") continue;
|
|
20222
|
+
return res;
|
|
20223
|
+
}
|
|
20224
|
+
return {
|
|
20225
|
+
ok: false,
|
|
20226
|
+
error: "扩展执行失败(bun 与 node 均不可用)",
|
|
20227
|
+
code: "ext-no-runner"
|
|
20228
|
+
};
|
|
20229
|
+
}
|
|
20230
|
+
/** 单次 spawn(Promise 化 + 超时 kill + 输出截断 + 绝不抛) */
|
|
20231
|
+
function runOnce(cmd, args, stdinJson, timeoutMs) {
|
|
20232
|
+
return new Promise((resolvePromise) => {
|
|
20233
|
+
let settled = false;
|
|
20234
|
+
let stdout = "";
|
|
20235
|
+
let stderr = "";
|
|
20236
|
+
let child = null;
|
|
20237
|
+
try {
|
|
20238
|
+
child = spawn(cmd, args, {
|
|
20239
|
+
stdio: [
|
|
20240
|
+
"pipe",
|
|
20241
|
+
"pipe",
|
|
20242
|
+
"pipe"
|
|
20243
|
+
],
|
|
20244
|
+
env: { ...process.env }
|
|
20245
|
+
});
|
|
20246
|
+
} catch (err) {
|
|
20247
|
+
return resolvePromise({
|
|
20248
|
+
ok: false,
|
|
20249
|
+
error: String(err),
|
|
20250
|
+
code: "SPAWN_ERR"
|
|
20251
|
+
});
|
|
20252
|
+
}
|
|
20253
|
+
const finish = (r) => {
|
|
20254
|
+
if (settled) return;
|
|
20255
|
+
settled = true;
|
|
20256
|
+
clearTimeout(timer);
|
|
20257
|
+
resolvePromise(r);
|
|
20258
|
+
};
|
|
20259
|
+
const timer = setTimeout(() => {
|
|
20260
|
+
child?.kill("SIGKILL");
|
|
20261
|
+
finish({
|
|
20262
|
+
ok: false,
|
|
20263
|
+
error: `扩展执行超时(>${Math.round(timeoutMs / 1e3)}s,已 kill)`,
|
|
20264
|
+
code: "ext-timeout",
|
|
20265
|
+
stdout
|
|
20266
|
+
});
|
|
20267
|
+
}, timeoutMs);
|
|
20268
|
+
child.stdin?.on("error", () => {});
|
|
20269
|
+
try {
|
|
20270
|
+
child.stdin?.write(stdinJson);
|
|
20271
|
+
child.stdin?.end();
|
|
20272
|
+
} catch {}
|
|
20273
|
+
child.stdout?.on("data", (d) => {
|
|
20274
|
+
stdout = (stdout + d.toString()).slice(0, EXT_STDOUT_MAX);
|
|
20275
|
+
});
|
|
20276
|
+
child.stderr?.on("data", (d) => {
|
|
20277
|
+
stderr = (stderr + d.toString()).slice(0, EXT_STDOUT_MAX);
|
|
20278
|
+
});
|
|
20279
|
+
child.on("error", (err) => {
|
|
20280
|
+
finish({
|
|
20281
|
+
ok: false,
|
|
20282
|
+
error: String(err.message ?? err),
|
|
20283
|
+
code: err.code,
|
|
20284
|
+
stdout
|
|
20285
|
+
});
|
|
20286
|
+
});
|
|
20287
|
+
child.on("close", (code) => {
|
|
20288
|
+
if (code !== 0) return finish({
|
|
20289
|
+
ok: false,
|
|
20290
|
+
error: `扩展退出码 ${code}${stderr ? `:${stderr.slice(-500)}` : ""}`,
|
|
20291
|
+
code: "ext-nonzero",
|
|
20292
|
+
stdout
|
|
20293
|
+
});
|
|
20294
|
+
const parsed = parseExtOutput(stdout);
|
|
20295
|
+
if (!parsed.ok || !parsed.value) return finish({
|
|
20296
|
+
ok: false,
|
|
20297
|
+
error: `扩展没有在 stdout 最后一行给出合法 JSON(${parsed.error ?? "解析失败"})`,
|
|
20298
|
+
code: "ext-bad-output",
|
|
20299
|
+
stdout
|
|
20300
|
+
});
|
|
20301
|
+
const value = parsed.value;
|
|
20302
|
+
if (value.ok === false) return finish({
|
|
20303
|
+
ok: false,
|
|
20304
|
+
error: String(value.error ?? "扩展自报失败(未给原因)"),
|
|
20305
|
+
code: "ext-reported-failure",
|
|
20306
|
+
stdout
|
|
20307
|
+
});
|
|
20308
|
+
finish({
|
|
20309
|
+
ok: true,
|
|
20310
|
+
result: value.result,
|
|
20311
|
+
stdout
|
|
20312
|
+
});
|
|
20313
|
+
});
|
|
20314
|
+
});
|
|
20315
|
+
}
|
|
20316
|
+
/**
|
|
20317
|
+
* 解析扩展输出:取**最后一个非空行**当 JSON。
|
|
20318
|
+
*
|
|
20319
|
+
* 判据:扩展可以自由 `console.log` 调试,⛔ 不要求 stdout 干净 ——
|
|
20320
|
+
* 否则"加一句 debug"就会破坏契约,而那种代价会让人**不敢调试**。
|
|
20321
|
+
*/
|
|
20322
|
+
function parseExtOutput(stdout) {
|
|
20323
|
+
const lines = stdout.split("\n").map((l) => l.trim()).filter((l) => l !== "");
|
|
20324
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
20325
|
+
const l = lines[i];
|
|
20326
|
+
if (!l.startsWith("{")) continue;
|
|
20327
|
+
try {
|
|
20328
|
+
const v = JSON.parse(l);
|
|
20329
|
+
if (v !== null && typeof v === "object" && !Array.isArray(v)) return {
|
|
20330
|
+
ok: true,
|
|
20331
|
+
value: v
|
|
20332
|
+
};
|
|
20333
|
+
} catch {}
|
|
20334
|
+
}
|
|
20335
|
+
return {
|
|
20336
|
+
ok: false,
|
|
20337
|
+
error: "没有任何一行可解析为 JSON 对象"
|
|
20338
|
+
};
|
|
20339
|
+
}
|
|
20340
|
+
/**
|
|
20341
|
+
* 组装给扩展的输入。
|
|
20342
|
+
*
|
|
20343
|
+
* 🔴 扩展拿到的**只有槽位号、端口、cccRoot 与它自己的 args** —— ⛔ 不塞进程表、
|
|
20344
|
+
* ⛔ 不塞别人的台账。判据:扩展可以驱动浏览器,但**不该知道别人的槽位在干什么**;
|
|
20345
|
+
* 知道得越多,「我的读数是怎么来的」就越难重建(R↓)。
|
|
20346
|
+
*/
|
|
20347
|
+
function buildExtPayload(opts) {
|
|
20348
|
+
return {
|
|
20349
|
+
name: opts.name,
|
|
20350
|
+
slot: opts.slot,
|
|
20351
|
+
port: opts.port,
|
|
20352
|
+
cccRoot: opts.cccRoot,
|
|
20353
|
+
args: opts.args,
|
|
20354
|
+
timeoutMs: opts.timeoutMs ?? 45e3
|
|
20355
|
+
};
|
|
20356
|
+
}
|
|
20357
|
+
//#endregion
|
|
19772
20358
|
//#region src/browser/service.ts
|
|
19773
20359
|
/**
|
|
19774
20360
|
* browser/service.ts — 槽位管理器的动作实现(ACC 级)
|
|
@@ -19782,20 +20368,43 @@ function normalizeSlotId(raw) {
|
|
|
19782
20368
|
* 槽位异常(长期不动 / CPU 过高)⇒ **反过来向占用它的会话注入一条消息**。
|
|
19783
20369
|
* 注入走 `sendToCognitiveTrajectory`(现成通道,语义 = 已注入,不证已执行)。
|
|
19784
20370
|
*/
|
|
19785
|
-
/**
|
|
20371
|
+
/**
|
|
20372
|
+
* 动作枚举(对外暴露的唯一清单)
|
|
20373
|
+
*
|
|
20374
|
+
* 🔴 v1.129.0(owner 2026-11-10 令「所有浏览器能力都集中到这个 browser_slot」):
|
|
20375
|
+
* **前 6 个管槽位,后 9 个管页面,最后 2 个管扩展** —— 三组各归一层,⛔ 不混。
|
|
20376
|
+
*
|
|
20377
|
+
* 分组不是装饰:它们失效的面完全不同(槽位层看进程/端口,页面层看 CDP,
|
|
20378
|
+
* 扩展层看子进程)。一个读数在哪个组里,决定了它坏了该往哪儿查。
|
|
20379
|
+
*
|
|
20380
|
+
* ⚠️ 页面组**必须带 `--slot`**(⛔ 不用裸端口):槽位号是循环复用的,
|
|
20381
|
+
* 裸端口会让「这是谁的浏览器」变成一个隐含状态。
|
|
20382
|
+
* 先例 `browser` MSM 收 `--port=` —— 那正是它和槽位体系断开的那个口子。
|
|
20383
|
+
*/
|
|
19786
20384
|
const SLOT_ACTIONS = [
|
|
19787
20385
|
"acquire",
|
|
19788
20386
|
"release",
|
|
19789
20387
|
"list",
|
|
19790
20388
|
"status",
|
|
19791
20389
|
"reap",
|
|
19792
|
-
"doctor"
|
|
20390
|
+
"doctor",
|
|
20391
|
+
"targets",
|
|
20392
|
+
"open",
|
|
20393
|
+
"goto",
|
|
20394
|
+
"eval",
|
|
20395
|
+
"text",
|
|
20396
|
+
"html",
|
|
20397
|
+
"shot",
|
|
20398
|
+
"reload",
|
|
20399
|
+
"close",
|
|
20400
|
+
"ext-list",
|
|
20401
|
+
"ext"
|
|
19793
20402
|
];
|
|
19794
20403
|
/** 一次采样缓存(进程内):CPU 是增量读数,必须有上一次才成立 */
|
|
19795
20404
|
const sampleCache = /* @__PURE__ */ new Map();
|
|
19796
20405
|
/** 按 profile 目录采一次样(有 prev 才给出瞬时 CPU) */
|
|
19797
20406
|
function readProcFor(root, n, now, pidHint = 0) {
|
|
19798
|
-
const pids = findPidsByProfile(slotPaths(
|
|
20407
|
+
const pids = findPidsByProfile(slotPaths(n).profile);
|
|
19799
20408
|
const cur = sampleProcTree(pids, sampleCache.get(n) ?? null, now);
|
|
19800
20409
|
sampleCache.set(n, cur);
|
|
19801
20410
|
/**
|
|
@@ -19841,20 +20450,24 @@ function toView(root, n, lease, proc, now, policy) {
|
|
|
19841
20450
|
async function acquireSlot(input) {
|
|
19842
20451
|
input.policy ?? policyFromEnv();
|
|
19843
20452
|
const now = Date.now();
|
|
19844
|
-
const existing = findLeaseBySession(listLeases(readLedger(
|
|
20453
|
+
const existing = findLeaseBySession(listLeases(readLedger()), input.sessionId);
|
|
19845
20454
|
if (existing && input.sessionId !== "") {
|
|
19846
20455
|
const launched = ensureRunning(input.root, existing.slot, existing.pid);
|
|
19847
|
-
if (launched.ok)
|
|
19848
|
-
|
|
19849
|
-
|
|
19850
|
-
cur
|
|
19851
|
-
|
|
19852
|
-
|
|
19853
|
-
|
|
19854
|
-
|
|
19855
|
-
|
|
19856
|
-
|
|
19857
|
-
|
|
20456
|
+
if (launched.ok) {
|
|
20457
|
+
withLedger((lg) => {
|
|
20458
|
+
const cur = lg.leases[String(existing.slot)];
|
|
20459
|
+
if (cur) {
|
|
20460
|
+
cur.pid = launched.pid || cur.pid;
|
|
20461
|
+
cur.lastActionAt = now;
|
|
20462
|
+
if (!cur.cccRoot) cur.cccRoot = input.root;
|
|
20463
|
+
}
|
|
20464
|
+
return {
|
|
20465
|
+
ledger: lg,
|
|
20466
|
+
result: null
|
|
20467
|
+
};
|
|
20468
|
+
});
|
|
20469
|
+
stampIdentity(input.root, existing.slot, existing.sessionId, existing.trajectory, existing.leasedAt);
|
|
20470
|
+
}
|
|
19858
20471
|
return {
|
|
19859
20472
|
ok: launched.ok,
|
|
19860
20473
|
slot: existing.slot,
|
|
@@ -19863,7 +20476,7 @@ async function acquireSlot(input) {
|
|
|
19863
20476
|
detail: `你在槽位 ${slotLabel(existing.slot)}(端口 ${slotPort(existing.slot)})上已有占用,已复用。\n ⛔ 不要再租第二个 —— 一次会话占两个槽位是本次事故的形状(租了忘记退)。\n` + launched.detail
|
|
19864
20477
|
};
|
|
19865
20478
|
}
|
|
19866
|
-
const picked = withLedger(
|
|
20479
|
+
const picked = withLedger((lg) => {
|
|
19867
20480
|
const leases = listLeases(lg);
|
|
19868
20481
|
const free = input.want && input.want > 0 ? input.want : pickFreeSlot(leases);
|
|
19869
20482
|
if (free === 0) return {
|
|
@@ -19876,6 +20489,7 @@ async function acquireSlot(input) {
|
|
|
19876
20489
|
};
|
|
19877
20490
|
lg.leases[String(free)] = {
|
|
19878
20491
|
slot: free,
|
|
20492
|
+
cccRoot: input.root,
|
|
19879
20493
|
sessionId: input.sessionId,
|
|
19880
20494
|
trajectory: input.trajectory,
|
|
19881
20495
|
leasedAt: now,
|
|
@@ -19905,7 +20519,7 @@ async function acquireSlot(input) {
|
|
|
19905
20519
|
};
|
|
19906
20520
|
const n = picked;
|
|
19907
20521
|
const launched = ensureRunning(input.root, n, 0);
|
|
19908
|
-
withLedger(
|
|
20522
|
+
withLedger((lg) => {
|
|
19909
20523
|
const cur = lg.leases[String(n)];
|
|
19910
20524
|
if (cur) cur.pid = launched.pid || 0;
|
|
19911
20525
|
return {
|
|
@@ -19915,13 +20529,14 @@ async function acquireSlot(input) {
|
|
|
19915
20529
|
});
|
|
19916
20530
|
const r = SLOT_RESOLUTION(n);
|
|
19917
20531
|
if (!launched.ok) {
|
|
19918
|
-
withLedger(
|
|
20532
|
+
withLedger((lg) => {
|
|
19919
20533
|
delete lg.leases[String(n)];
|
|
19920
20534
|
return {
|
|
19921
20535
|
ledger: lg,
|
|
19922
20536
|
result: null
|
|
19923
20537
|
};
|
|
19924
20538
|
});
|
|
20539
|
+
clearSlotIdentity(n);
|
|
19925
20540
|
return {
|
|
19926
20541
|
ok: false,
|
|
19927
20542
|
slot: n,
|
|
@@ -19930,6 +20545,7 @@ async function acquireSlot(input) {
|
|
|
19930
20545
|
detail: launched.detail
|
|
19931
20546
|
};
|
|
19932
20547
|
}
|
|
20548
|
+
stampIdentity(input.root, n, input.sessionId, input.trajectory, now);
|
|
19933
20549
|
return {
|
|
19934
20550
|
ok: true,
|
|
19935
20551
|
slot: n,
|
|
@@ -19940,13 +20556,13 @@ async function acquireSlot(input) {
|
|
|
19940
20556
|
}
|
|
19941
20557
|
/** 启动退避:连续失败按指数推迟(G9)。返回 0 = 可以尝试,>0 = 还需等待的毫秒 */
|
|
19942
20558
|
function backoffWaitMs(root, n, now) {
|
|
19943
|
-
const b = readLedger(
|
|
20559
|
+
const b = readLedger().backoff[String(n)];
|
|
19944
20560
|
if (!b || b.failures === 0) return 0;
|
|
19945
20561
|
return Math.max(0, b.nextAt - now);
|
|
19946
20562
|
}
|
|
19947
20563
|
/** 记一次启动失败(推下次允许时刻) */
|
|
19948
20564
|
function noteLaunchFailure(root, n) {
|
|
19949
|
-
return withLedger(
|
|
20565
|
+
return withLedger((lg) => {
|
|
19950
20566
|
const failures = (lg.backoff[String(n)] ?? {
|
|
19951
20567
|
failures: 0,
|
|
19952
20568
|
nextAt: 0
|
|
@@ -19964,7 +20580,7 @@ function noteLaunchFailure(root, n) {
|
|
|
19964
20580
|
}
|
|
19965
20581
|
/** 启动成功 ⇒ 清零退避 */
|
|
19966
20582
|
function clearLaunchFailure(root, n) {
|
|
19967
|
-
withLedger(
|
|
20583
|
+
withLedger((lg) => {
|
|
19968
20584
|
delete lg.backoff[String(n)];
|
|
19969
20585
|
return {
|
|
19970
20586
|
ledger: lg,
|
|
@@ -19974,7 +20590,7 @@ function clearLaunchFailure(root, n) {
|
|
|
19974
20590
|
}
|
|
19975
20591
|
/** 确保槽位进程在跑(内部):不在则起 + 等就绪 */
|
|
19976
20592
|
function ensureRunning(root, n, pidHint) {
|
|
19977
|
-
const live = findPidsByProfile(slotPaths(
|
|
20593
|
+
const live = findPidsByProfile(slotPaths(n).profile);
|
|
19978
20594
|
if (live.length > 0) return {
|
|
19979
20595
|
ok: true,
|
|
19980
20596
|
pid: live[0],
|
|
@@ -19991,7 +20607,7 @@ function ensureRunning(root, n, pidHint) {
|
|
|
19991
20607
|
pid: 0,
|
|
19992
20608
|
detail: `槽位 ${slotLabel(n)} 处于**启动退避**中(还需 ${Math.ceil(wait / 1e3)} 秒)。\n 🔴 起因:该槽位连续启动失败。⇒ 反复重试会白付一次完整复检(数秒),且**读数上分不出来**。\n ⇒ 先查根因:\`browser_slot doctor\` 看 pidDrift 与日志路径;或换一个槽位。`
|
|
19993
20609
|
};
|
|
19994
|
-
const launched = launchSlot(
|
|
20610
|
+
const launched = launchSlot(n);
|
|
19995
20611
|
if (!launched.ok) {
|
|
19996
20612
|
const w = noteLaunchFailure(root, n);
|
|
19997
20613
|
return {
|
|
@@ -20011,9 +20627,33 @@ function ensureRunning(root, n, pidHint) {
|
|
|
20011
20627
|
async function waitSlotReady(root, n) {
|
|
20012
20628
|
return await waitCdp(root, n);
|
|
20013
20629
|
}
|
|
20630
|
+
/**
|
|
20631
|
+
* 把归属**同时**写进两处:台账(权威)+ `identity.json`(profile 侧冗余)。
|
|
20632
|
+
*
|
|
20633
|
+
* 🔴 owner 2026-11-10 令:「每个槽位的浏览器 profile 里加点标识」。
|
|
20634
|
+
* 判据:**资源的归属必须在"资源自己身上"也能被读出来** —— 只靠台账回答归属,
|
|
20635
|
+
* 会让"台账坏了/读了一半"与"槽位无主"在读数上完全同形(D253 同族)。
|
|
20636
|
+
* ⚠️ 两处不一致时**以台账为准**;identity 是抓手,不是第二个真相源。
|
|
20637
|
+
*/
|
|
20638
|
+
function stampIdentity(root, n, sessionId, trajectory, leasedAt) {
|
|
20639
|
+
try {
|
|
20640
|
+
writeSlotIdentity({
|
|
20641
|
+
slot: n,
|
|
20642
|
+
label: slotLabel(n),
|
|
20643
|
+
port: slotPort(n),
|
|
20644
|
+
cccRoot: root,
|
|
20645
|
+
sessionId,
|
|
20646
|
+
trajectory,
|
|
20647
|
+
leasedAt,
|
|
20648
|
+
writtenAt: 0
|
|
20649
|
+
});
|
|
20650
|
+
} catch (err) {
|
|
20651
|
+
console.warn(`[serenity-hooks] ⚠️ 槽位 ${slotLabel(n)} 的 identity.json 写入失败:${String(err?.message ?? err)}`);
|
|
20652
|
+
}
|
|
20653
|
+
}
|
|
20014
20654
|
/** release:交还槽位(**杀进程** + 删记录,⛔ 保留 profile 目录) */
|
|
20015
20655
|
function releaseSlot(root, sessionId, target) {
|
|
20016
|
-
const lease = readLedger(
|
|
20656
|
+
const lease = readLedger().leases[String(target)];
|
|
20017
20657
|
if (!lease) return {
|
|
20018
20658
|
ok: true,
|
|
20019
20659
|
detail: `槽位 ${slotLabel(target)} 本就无人占用(无需释放)。`
|
|
@@ -20022,14 +20662,15 @@ function releaseSlot(root, sessionId, target) {
|
|
|
20022
20662
|
ok: false,
|
|
20023
20663
|
detail: `槽位 ${slotLabel(target)} 不属于你(占用者:${lease.trajectory || lease.sessionId || "未知"})。\n ⛔ 不代别人释放 —— 它可能正在用。若确信它已废弃,用 \`browser_slot reap <槽>\`(看守动作,会记录原因)。`
|
|
20024
20664
|
};
|
|
20025
|
-
const destroyed = destroySlot(
|
|
20026
|
-
withLedger(
|
|
20665
|
+
const destroyed = destroySlot(target, lease.pid);
|
|
20666
|
+
withLedger((lg) => {
|
|
20027
20667
|
delete lg.leases[String(target)];
|
|
20028
20668
|
return {
|
|
20029
20669
|
ledger: lg,
|
|
20030
20670
|
result: null
|
|
20031
20671
|
};
|
|
20032
20672
|
});
|
|
20673
|
+
clearSlotIdentity(target);
|
|
20033
20674
|
sampleCache.delete(target);
|
|
20034
20675
|
return {
|
|
20035
20676
|
ok: true,
|
|
@@ -20038,7 +20679,7 @@ function releaseSlot(root, sessionId, target) {
|
|
|
20038
20679
|
}
|
|
20039
20680
|
/** list:全部槽位一览(含空槽) */
|
|
20040
20681
|
function listSlots(root, policy = policyFromEnv()) {
|
|
20041
|
-
const ledger = readLedger(
|
|
20682
|
+
const ledger = readLedger();
|
|
20042
20683
|
const now = Date.now();
|
|
20043
20684
|
const views = [];
|
|
20044
20685
|
for (let n = 1; n <= 20; n++) {
|
|
@@ -20059,7 +20700,7 @@ function listSlots(root, policy = policyFromEnv()) {
|
|
|
20059
20700
|
/** status:单槽位详情 */
|
|
20060
20701
|
function slotStatus(root, target, policy = policyFromEnv()) {
|
|
20061
20702
|
if (target < 1 || target > 20) return null;
|
|
20062
|
-
const lease = readLedger(
|
|
20703
|
+
const lease = readLedger().leases[String(target)] ?? null;
|
|
20063
20704
|
const now = Date.now();
|
|
20064
20705
|
return toView(root, target, lease, lease ? readProcFor(root, target, now, lease.pid) : {
|
|
20065
20706
|
alive: false,
|
|
@@ -20073,15 +20714,16 @@ function slotStatus(root, target, policy = policyFromEnv()) {
|
|
|
20073
20714
|
* ⛔ 与 release 的区别:release 是**占用者的自觉**,reap 是**兜底**,故必须记录原因。
|
|
20074
20715
|
*/
|
|
20075
20716
|
function reapSlot(root, target, reason) {
|
|
20076
|
-
const lease = readLedger(
|
|
20077
|
-
const destroyed = destroySlot(
|
|
20078
|
-
withLedger(
|
|
20717
|
+
const lease = readLedger().leases[String(target)];
|
|
20718
|
+
const destroyed = destroySlot(target, lease?.pid ?? 0);
|
|
20719
|
+
withLedger((lg) => {
|
|
20079
20720
|
delete lg.leases[String(target)];
|
|
20080
20721
|
return {
|
|
20081
20722
|
ledger: lg,
|
|
20082
20723
|
result: null
|
|
20083
20724
|
};
|
|
20084
20725
|
});
|
|
20726
|
+
clearSlotIdentity(target);
|
|
20085
20727
|
sampleCache.delete(target);
|
|
20086
20728
|
return {
|
|
20087
20729
|
ok: true,
|
|
@@ -20089,7 +20731,7 @@ function reapSlot(root, target, reason) {
|
|
|
20089
20731
|
};
|
|
20090
20732
|
}
|
|
20091
20733
|
async function nudgeStaleSlots(root, inject, policy = policyFromEnv()) {
|
|
20092
|
-
const ledger = readLedger(
|
|
20734
|
+
const ledger = readLedger();
|
|
20093
20735
|
const now = Date.now();
|
|
20094
20736
|
const out = [];
|
|
20095
20737
|
let scanned = 0;
|
|
@@ -20109,7 +20751,7 @@ async function nudgeStaleSlots(root, inject, policy = policyFromEnv()) {
|
|
|
20109
20751
|
continue;
|
|
20110
20752
|
}
|
|
20111
20753
|
const res = await inject(root, target, nudgeText(lease.slot, state, reasons, policy));
|
|
20112
|
-
withLedger(
|
|
20754
|
+
withLedger((lg) => {
|
|
20113
20755
|
const cur = lg.leases[String(lease.slot)];
|
|
20114
20756
|
if (cur) {
|
|
20115
20757
|
cur.nudges += 1;
|
|
@@ -20133,29 +20775,165 @@ async function nudgeStaleSlots(root, inject, policy = policyFromEnv()) {
|
|
|
20133
20775
|
scanned
|
|
20134
20776
|
};
|
|
20135
20777
|
}
|
|
20778
|
+
/** 推进 lastActionAt(由"成功的浏览器操作"调用;这就是"是否长期不动作"的判据来源) */
|
|
20779
|
+
function touchSlot(root, target) {
|
|
20780
|
+
withLedger((lg) => {
|
|
20781
|
+
const cur = lg.leases[String(target)];
|
|
20782
|
+
if (cur) cur.lastActionAt = Date.now();
|
|
20783
|
+
return {
|
|
20784
|
+
ledger: lg,
|
|
20785
|
+
result: null
|
|
20786
|
+
};
|
|
20787
|
+
});
|
|
20788
|
+
}
|
|
20136
20789
|
/** doctor:自检(⛔ 不修改任何东西) */
|
|
20137
20790
|
function doctorSlots(root, policy = policyFromEnv()) {
|
|
20138
|
-
const ledger = readLedger(
|
|
20791
|
+
const ledger = readLedger();
|
|
20139
20792
|
const now = Date.now();
|
|
20140
20793
|
const drift = [];
|
|
20141
20794
|
for (const lease of listLeases(ledger)) {
|
|
20142
|
-
const live = findPidsByProfile(slotPaths(
|
|
20795
|
+
const live = findPidsByProfile(slotPaths(lease.slot).profile);
|
|
20143
20796
|
if (lease.pid > 0 && live.length > 0 && !live.includes(lease.pid)) drift.push(`槽位 ${slotLabel(lease.slot)}:台账 pid=${lease.pid},实际=${live.join(",")}`);
|
|
20144
20797
|
if (lease.pid === 0 && live.length > 0) drift.push(`槽位 ${slotLabel(lease.slot)}:台账无 pid,实际在跑 ${live.join(",")}`);
|
|
20145
20798
|
}
|
|
20146
20799
|
const views = listSlots(root, policy).views.filter((v) => v.state !== "free");
|
|
20800
|
+
const identityDrift = [];
|
|
20801
|
+
for (const lease of listLeases(ledger)) {
|
|
20802
|
+
const ident = readSlotIdentity(lease.slot);
|
|
20803
|
+
if (!ident) {
|
|
20804
|
+
identityDrift.push(`槽位 ${slotLabel(lease.slot)}:台账有租约但 identity.json 缺失`);
|
|
20805
|
+
continue;
|
|
20806
|
+
}
|
|
20807
|
+
if (ident.sessionId !== lease.sessionId) identityDrift.push(`槽位 ${slotLabel(lease.slot)}:identity.sessionId=${ident.sessionId || "(空)"} ≠ 台账=${lease.sessionId || "(空)"}`);
|
|
20808
|
+
if ((ident.cccRoot || "") !== (lease.cccRoot || "")) identityDrift.push(`槽位 ${slotLabel(lease.slot)}:identity.cccRoot 与台账不一致(⛔ 以台账为准)`);
|
|
20809
|
+
}
|
|
20147
20810
|
return {
|
|
20148
20811
|
ledger: {
|
|
20149
|
-
path:
|
|
20812
|
+
path: ledgerPath(),
|
|
20150
20813
|
leases: listLeases(ledger).length,
|
|
20151
20814
|
ageMin: ledger.updatedAt ? Math.round((now - ledger.updatedAt) / 6e4) : 0
|
|
20152
20815
|
},
|
|
20153
20816
|
policy,
|
|
20154
20817
|
occupied: views,
|
|
20155
20818
|
pidDrift: drift,
|
|
20156
|
-
|
|
20819
|
+
identityDrift,
|
|
20820
|
+
verdict: drift.length === 0 && identityDrift.length === 0 ? "clean" : "drift"
|
|
20157
20821
|
};
|
|
20158
20822
|
}
|
|
20823
|
+
/**
|
|
20824
|
+
* 页面操作的前置守卫:**这个槽位必须是你租的**。
|
|
20825
|
+
*
|
|
20826
|
+
* 🔴🔴 判据(这条比任何单个动作都值钱):
|
|
20827
|
+
* 搬进来的动作以前是「给一个端口就能操作」,而端口与归属在**两处**各记一份
|
|
20828
|
+
* ⇒ 谁都能操作任何人的浏览器,而**没有任何读数会显示这件事**。
|
|
20829
|
+
* ⇒ 现在页面动作必须先过归属检查:`sessionId` 必须是该槽位的占用者。
|
|
20830
|
+
*
|
|
20831
|
+
* ⚠️ 豁免:`sessionId === ''`(无归属调用,例如 CLI 探针)**一律拒绝**,⛔ 不做"信任本地"的放宽
|
|
20832
|
+
* —— 一旦放宽,归属就从"机制"退回成"习惯"。
|
|
20833
|
+
*/
|
|
20834
|
+
function assertSlotOwned(root, slot, sessionId) {
|
|
20835
|
+
const lease = readLedger().leases[String(slot)];
|
|
20836
|
+
if (!lease) throw new Error(`槽位 ${slotLabel(slot)} 当前无人占用 ⇒ 先 \`browser_slot acquire\` 租一个再用。\n ⛔ 不自动替你租:租了不还就是 2026-11-09 那次 36 小时功耗事故的形状。`);
|
|
20837
|
+
if (sessionId === "" || lease.sessionId !== sessionId) throw new Error(`槽位 ${slotLabel(slot)} 不是你租的(占用者 ${lease.sessionId || "(无)"})⇒ 拒绝操作。\n ⇒ 自己的槽位用 \`browser_slot list\` 查;要新开一个用 \`browser_slot acquire\`。\n ⚠️ 硬拒绝是刻意的:放行会让"谁在动谁的浏览器"变成没有读数可查的事。`);
|
|
20838
|
+
}
|
|
20839
|
+
/** 把页面上一次成功的操作推进 lastActionAt(这就是"长期不动作"判据的来源) */
|
|
20840
|
+
function pageTouched(root, slot) {
|
|
20841
|
+
touchSlot(root, slot);
|
|
20842
|
+
}
|
|
20843
|
+
/** 列当前槽位上的 targets */
|
|
20844
|
+
async function slotTargets(root, slot, sessionId) {
|
|
20845
|
+
assertSlotOwned(root, slot, sessionId);
|
|
20846
|
+
const list = await listTargets(slot);
|
|
20847
|
+
pageTouched(root, slot);
|
|
20848
|
+
return list;
|
|
20849
|
+
}
|
|
20850
|
+
/** 新开标签页 */
|
|
20851
|
+
async function slotOpen(root, slot, sessionId, url) {
|
|
20852
|
+
assertSlotOwned(root, slot, sessionId);
|
|
20853
|
+
const id = await openTab(slot, url);
|
|
20854
|
+
pageTouched(root, slot);
|
|
20855
|
+
return id;
|
|
20856
|
+
}
|
|
20857
|
+
/** 导航 */
|
|
20858
|
+
async function slotGoto(root, slot, sessionId, targetId, url) {
|
|
20859
|
+
assertSlotOwned(root, slot, sessionId);
|
|
20860
|
+
await navigate(slot, targetId, url);
|
|
20861
|
+
pageTouched(root, slot);
|
|
20862
|
+
}
|
|
20863
|
+
/** 页面内求值 */
|
|
20864
|
+
async function slotEval(root, slot, sessionId, targetId, expression, timeoutMs) {
|
|
20865
|
+
assertSlotOwned(root, slot, sessionId);
|
|
20866
|
+
const v = await evalInPage(slot, targetId, expression, timeoutMs);
|
|
20867
|
+
pageTouched(root, slot);
|
|
20868
|
+
return v;
|
|
20869
|
+
}
|
|
20870
|
+
/** 正文 */
|
|
20871
|
+
async function slotText(root, slot, sessionId, targetId) {
|
|
20872
|
+
assertSlotOwned(root, slot, sessionId);
|
|
20873
|
+
const v = await pageText(slot, targetId);
|
|
20874
|
+
pageTouched(root, slot);
|
|
20875
|
+
return v;
|
|
20876
|
+
}
|
|
20877
|
+
/** HTML */
|
|
20878
|
+
async function slotHtml(root, slot, sessionId, targetId, max) {
|
|
20879
|
+
assertSlotOwned(root, slot, sessionId);
|
|
20880
|
+
const v = await pageHtml(slot, targetId, max);
|
|
20881
|
+
pageTouched(root, slot);
|
|
20882
|
+
return v;
|
|
20883
|
+
}
|
|
20884
|
+
/** 截图(落点必须在 CCC 根内) */
|
|
20885
|
+
async function slotShot(root, slot, sessionId, targetId, outRel) {
|
|
20886
|
+
assertSlotOwned(root, slot, sessionId);
|
|
20887
|
+
await screenshot(slot, targetId, resolveShotPath(root, outRel));
|
|
20888
|
+
pageTouched(root, slot);
|
|
20889
|
+
return outRel;
|
|
20890
|
+
}
|
|
20891
|
+
/** 重载(可先装探针脚本) */
|
|
20892
|
+
async function slotReload(root, slot, sessionId, targetId, script) {
|
|
20893
|
+
assertSlotOwned(root, slot, sessionId);
|
|
20894
|
+
const state = await reloadPage(slot, targetId, script);
|
|
20895
|
+
pageTouched(root, slot);
|
|
20896
|
+
return state;
|
|
20897
|
+
}
|
|
20898
|
+
/** 关标签页 */
|
|
20899
|
+
async function slotClose(root, slot, sessionId, targetId, all = false) {
|
|
20900
|
+
assertSlotOwned(root, slot, sessionId);
|
|
20901
|
+
const closed = await closeTab(slot, targetId, all);
|
|
20902
|
+
pageTouched(root, slot);
|
|
20903
|
+
return closed;
|
|
20904
|
+
}
|
|
20905
|
+
/** 列本 CCC 的扩展 */
|
|
20906
|
+
function slotExtList(root) {
|
|
20907
|
+
return listExtensions(root);
|
|
20908
|
+
}
|
|
20909
|
+
/**
|
|
20910
|
+
* 跑一个扩展。
|
|
20911
|
+
*
|
|
20912
|
+
* 🔴 归属检查与页面层同一条:扩展能驱动槽位里的浏览器 ⇒ 它跑的必须是你租的那个槽。
|
|
20913
|
+
* ⚠️ 扩展**不受 SLOT_ACTIONS 约束** —— 那正是扩展的意义(ACC 不预知它要做什么)。
|
|
20914
|
+
* 它拿到的只有 slot/port/cccRoot/args,⛔ 拿不到别人的台账。
|
|
20915
|
+
*/
|
|
20916
|
+
async function slotExt(root, slot, sessionId, name, args) {
|
|
20917
|
+
assertSlotOwned(root, slot, sessionId);
|
|
20918
|
+
const entry = findExtension(root, name);
|
|
20919
|
+
if (!entry) {
|
|
20920
|
+
const known = listExtensions(root).map((e) => e.name);
|
|
20921
|
+
return {
|
|
20922
|
+
ok: false,
|
|
20923
|
+
code: "ext-not-found",
|
|
20924
|
+
error: `没有名为「${name}」的扩展。\n` + (known.length > 0 ? ` ⇒ 本 CCC 现有的扩展:${known.join(", ")}` : ` ⇒ 本 CCC 还没有任何扩展(<CCC 根>/${EXT_DIR_REL}/ 下没有 .ts 文件)。\n 写一个:stdin 收 {slot,port,cccRoot,args},stdout 最后一行给 {"ok":true,"result":…}`)
|
|
20925
|
+
};
|
|
20926
|
+
}
|
|
20927
|
+
const res = await runExtension(entry, buildExtPayload({
|
|
20928
|
+
name,
|
|
20929
|
+
slot,
|
|
20930
|
+
port: slotPort(slot),
|
|
20931
|
+
cccRoot: root,
|
|
20932
|
+
args
|
|
20933
|
+
}));
|
|
20934
|
+
pageTouched(root, slot);
|
|
20935
|
+
return res;
|
|
20936
|
+
}
|
|
20159
20937
|
//#endregion
|
|
20160
20938
|
//#region src/tools/browser-slot/index.ts
|
|
20161
20939
|
/**
|
|
@@ -20205,6 +20983,45 @@ function row(v) {
|
|
|
20205
20983
|
const why = v.reasons.length > 0 ? `\n ↳ ${v.reasons.join(";")}` : "";
|
|
20206
20984
|
return ` ${g} ${v.label.padEnd(3)} :${v.port} ${v.resolution.padEnd(9)} ${v.state.padEnd(8)}${who}${extra}${why}`;
|
|
20207
20985
|
}
|
|
20986
|
+
/**
|
|
20987
|
+
* 取 `--slot` 并校验(页面层与扩展层的统一入口)。
|
|
20988
|
+
*
|
|
20989
|
+
* 🔴 页面动作**必须亮明槽位**,⛔ 不接受裸端口:
|
|
20990
|
+
* 槽位号是循环复用的(b1 今天给 A、明天给 B),裸端口会让「这是谁的浏览器」
|
|
20991
|
+
* 变成隐含状态 —— 而那正是 `browser` MSM 与槽位体系断开的那个口子。
|
|
20992
|
+
*/
|
|
20993
|
+
function needSlot(args) {
|
|
20994
|
+
const n = normalizeSlotId(String(args.slot ?? ""));
|
|
20995
|
+
if (n === 0) throw new Error(`⛔ 需要 --slot <b1..b20>(当前收到 ${JSON.stringify(args.slot)})。\n ⇒ 页面操作必须指明槽位:先 \`browser_slot list\` 看你租的是哪个。`);
|
|
20996
|
+
return n;
|
|
20997
|
+
}
|
|
20998
|
+
/** 取字符串参数(空串当没给) */
|
|
20999
|
+
function str(v) {
|
|
21000
|
+
return typeof v === "string" && v !== "" ? v : void 0;
|
|
21001
|
+
}
|
|
21002
|
+
/** 取数字参数(非有限数当没给) */
|
|
21003
|
+
function num(v) {
|
|
21004
|
+
const n = Number(v);
|
|
21005
|
+
return Number.isFinite(n) && n > 0 ? n : void 0;
|
|
21006
|
+
}
|
|
21007
|
+
/**
|
|
21008
|
+
* 组装扩展的 `args`。
|
|
21009
|
+
*
|
|
21010
|
+
* 契约:`--earg key=value` 可重复;`--earg` 之后的值一律当字符串
|
|
21011
|
+
* (⛔ 不做类型猜测 —— 猜错会让扩展收到 `"true"` 而不是 `true`,而那种错在扩展里静默)。
|
|
21012
|
+
*/
|
|
21013
|
+
function extArgs(args) {
|
|
21014
|
+
const raw = args.earg;
|
|
21015
|
+
const list = Array.isArray(raw) ? raw : typeof raw === "string" ? [raw] : [];
|
|
21016
|
+
const out = {};
|
|
21017
|
+
for (const item of list) {
|
|
21018
|
+
if (typeof item !== "string") continue;
|
|
21019
|
+
const i = item.indexOf("=");
|
|
21020
|
+
if (i <= 0) continue;
|
|
21021
|
+
out[item.slice(0, i)] = item.slice(i + 1);
|
|
21022
|
+
}
|
|
21023
|
+
return out;
|
|
21024
|
+
}
|
|
20208
21025
|
/** 动作实现 */
|
|
20209
21026
|
async function run(ctx, root, sessionId, trajectory, action, args) {
|
|
20210
21027
|
switch (action) {
|
|
@@ -20258,6 +21075,78 @@ async function run(ctx, root, sessionId, trajectory, action, args) {
|
|
|
20258
21075
|
return lines.join("\n");
|
|
20259
21076
|
}
|
|
20260
21077
|
case "doctor": return JSON.stringify(doctorSlots(root), null, 2);
|
|
21078
|
+
case "targets": {
|
|
21079
|
+
const n = needSlot(args);
|
|
21080
|
+
const list = await slotTargets(root, n, sessionId);
|
|
21081
|
+
if (list.length === 0) return `槽位 ${slotLabel(n)}(端口 ${slotPort(n)})上没有 target。`;
|
|
21082
|
+
return `[browser_slot] ${list.length} 个 target(槽位 ${slotLabel(n)},端口 ${slotPort(n)})\n` + list.map((t) => ` ${t.type.padEnd(10)} ${t.id} ${t.title.slice(0, 40)} ${t.url.slice(0, 90)}`).join("\n");
|
|
21083
|
+
}
|
|
21084
|
+
case "open": {
|
|
21085
|
+
const n = needSlot(args);
|
|
21086
|
+
const url = str(args.url);
|
|
21087
|
+
if (!url) return "⛔ 需要 --url=<地址>";
|
|
21088
|
+
return `[browser_slot] targetId=${await slotOpen(root, n, sessionId, url)}`;
|
|
21089
|
+
}
|
|
21090
|
+
case "goto": {
|
|
21091
|
+
const n = needSlot(args);
|
|
21092
|
+
const target = str(args.target);
|
|
21093
|
+
const url = str(args.url);
|
|
21094
|
+
if (!target) return "⛔ 需要 --target=<targetId>(先跑 targets)";
|
|
21095
|
+
if (!url) return "⛔ 需要 --url=<地址>";
|
|
21096
|
+
await slotGoto(root, n, sessionId, target, url);
|
|
21097
|
+
return `[browser_slot] navigate ${target} → ${url}`;
|
|
21098
|
+
}
|
|
21099
|
+
case "eval": {
|
|
21100
|
+
const n = needSlot(args);
|
|
21101
|
+
const target = str(args.target);
|
|
21102
|
+
const js = str(args.js);
|
|
21103
|
+
if (!target) return "⛔ 需要 --target=<targetId>(先跑 targets)";
|
|
21104
|
+
if (!js) return "⛔ 需要 --js=<表达式>(例如 document.title)";
|
|
21105
|
+
const v = await slotEval(root, n, sessionId, target, js, num(args.timeout));
|
|
21106
|
+
return typeof v === "string" ? v : JSON.stringify(v, null, 2);
|
|
21107
|
+
}
|
|
21108
|
+
case "text": {
|
|
21109
|
+
const n = needSlot(args);
|
|
21110
|
+
const target = str(args.target);
|
|
21111
|
+
if (!target) return "⛔ 需要 --target=<targetId>(先跑 targets)";
|
|
21112
|
+
return await slotText(root, n, sessionId, target);
|
|
21113
|
+
}
|
|
21114
|
+
case "html": {
|
|
21115
|
+
const n = needSlot(args);
|
|
21116
|
+
const target = str(args.target);
|
|
21117
|
+
if (!target) return "⛔ 需要 --target=<targetId>(先跑 targets)";
|
|
21118
|
+
return await slotHtml(root, n, sessionId, target, num(args.max));
|
|
21119
|
+
}
|
|
21120
|
+
case "shot": {
|
|
21121
|
+
const n = needSlot(args);
|
|
21122
|
+
const target = str(args.target);
|
|
21123
|
+
if (!target) return "⛔ 需要 --target=<targetId>(先跑 targets)";
|
|
21124
|
+
return `[browser_slot] shot → ${await slotShot(root, n, sessionId, target, str(args.out) ?? `_tmp/browser-shots/shot-${target.slice(0, 8)}-${Date.now()}.png`)}`;
|
|
21125
|
+
}
|
|
21126
|
+
case "reload": {
|
|
21127
|
+
const n = needSlot(args);
|
|
21128
|
+
const target = str(args.target);
|
|
21129
|
+
if (!target) return "⛔ 需要 --target=<targetId>(先跑 targets)";
|
|
21130
|
+
return `[browser_slot] reload 完成(readyState=${await slotReload(root, n, sessionId, target, str(args.script)) || "?"})`;
|
|
21131
|
+
}
|
|
21132
|
+
case "close": {
|
|
21133
|
+
const n = needSlot(args);
|
|
21134
|
+
const all = args.all === true;
|
|
21135
|
+
return `[browser_slot] closed ${(await slotClose(root, n, sessionId, str(args.target) ?? "", all)).join(", ")}`;
|
|
21136
|
+
}
|
|
21137
|
+
case "ext-list": {
|
|
21138
|
+
const exts = slotExtList(root);
|
|
21139
|
+
if (exts.length === 0) return `本 CCC 还没有任何扩展。\n 写一个:在 <CCC 根>/${EXT_DIR_REL}/ 下放一个 .ts 文件,文件名即扩展名。\n 契约:stdin 收 {slot,port,cccRoot,args};stdout **最后一个非空行**给 {"ok":true,"result":…}。\n ⚠️ ACC 只 spawn、⛔ 从不 import —— 你的语法错不会放倒宿主。`;
|
|
21140
|
+
return `本 CCC 的浏览器扩展 ${exts.length} 个(<CCC 根>/${EXT_DIR_REL}/):\n` + exts.map((e) => ` · ${e.name}`).join("\n") + `\n\n调用:browser_slot ext --slot b1 --name <名> [--eslot …/--earg key=value]`;
|
|
21141
|
+
}
|
|
21142
|
+
case "ext": {
|
|
21143
|
+
const n = needSlot(args);
|
|
21144
|
+
const name = str(args.name);
|
|
21145
|
+
if (!name) return "⛔ 需要 --name=<扩展名>(先跑 ext-list)";
|
|
21146
|
+
const res = await slotExt(root, n, sessionId, name, extArgs(args));
|
|
21147
|
+
if (!res.ok) return `⛔ 扩展「${name}」失败(${res.code ?? "unknown"}):\n${res.error ?? ""}`;
|
|
21148
|
+
return typeof res.result === "string" ? res.result : JSON.stringify(res.result ?? null, null, 2);
|
|
21149
|
+
}
|
|
20261
21150
|
}
|
|
20262
21151
|
}
|
|
20263
21152
|
function createBrowserSlotTool(ctx) {
|