@trim21/personal-pi-extensions 0.1.454 → 0.1.456

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trim21/personal-pi-extensions",
3
- "version": "0.1.454",
3
+ "version": "0.1.456",
4
4
  "type": "module",
5
5
  "description": "Custom pi coding-agent extensions: bwrap sandbox, workspace guard, opencode edit, and more",
6
6
  "keywords": [
@@ -24,6 +24,7 @@
24
24
  "test": "vitest run",
25
25
  "test:coverage": "vitest run --coverage",
26
26
  "sandbox": "tsx bin/sandbox.ts",
27
+ "aft-search": "tsx bin/aft-search.ts",
27
28
  "build:holder": "esbuild src/bwrap/holder.ts --format=esm --target=node24 --outfile=src/bwrap/holder.js",
28
29
  "prepare": "husky"
29
30
  },
@@ -43,6 +44,7 @@
43
44
  "@types/turndown": "^5.0.6",
44
45
  "@typescript/native": "npm:typescript@^7.0.2",
45
46
  "@vitest/coverage-v8": "^4.1.10",
47
+ "citty": "^0.2.2",
46
48
  "esbuild": "^0.28.2",
47
49
  "eslint": "^10.8.1",
48
50
  "eslint-config-prettier": "10.1.8",
@@ -1,12 +1,11 @@
1
1
  import { spawn } from "node:child_process";
2
- import { readFile } from "node:fs/promises";
3
2
  import { setTimeout as sleep } from "node:timers/promises";
4
3
  const args = process.argv.slice(2);
5
4
  const configBase64 = args[0];
6
5
  const mihomoPath = args[1];
7
- const slirp4netnsPath = args[2];
8
- const tunMtu = Number(args[3]);
9
- if (!configBase64 || !mihomoPath || !slirp4netnsPath || !tunMtu) {
6
+ const tunMtu = Number(args[2]);
7
+ const mihomoHome = args[3];
8
+ if (!configBase64 || !mihomoPath || !tunMtu || !mihomoHome) {
10
9
  process.exit(2);
11
10
  }
12
11
  process.chdir("/");
@@ -27,16 +26,8 @@ async function waitFor(attempts, delayMs, predicate) {
27
26
  async function main() {
28
27
  process.stdin.resume();
29
28
  process.stdin.on("end", () => process.exit(0));
30
- const status = await readFile("/proc/self/status", "utf8");
31
- const hostPid = /^NSpid:\s+(.+)$/m.exec(status)?.[1].split(/\s+/, 1)[0];
32
- if (!hostPid) {
33
- throw new Error("Failed to resolve host pid from NSpid");
34
- }
35
- spawn(slirp4netnsPath, ["-c", `--mtu=${tunMtu}`, "--netns-type=pid", hostPid, "tap0"], {
36
- stdio: ["ignore", "inherit", "inherit"]
37
- });
38
29
  await waitFor(100, 100, tap0Exists);
39
- const mihomo = spawn(mihomoPath, ["-config", configBase64], {
30
+ const mihomo = spawn(mihomoPath, ["-d", mihomoHome, "-config", configBase64], {
40
31
  stdio: ["ignore", "inherit", "inherit"]
41
32
  });
42
33
  const stop = () => {
@@ -1,17 +1,19 @@
1
1
  /* eslint-disable no-console, unicorn/no-process-exit -- 独立 CLI 脚本,由 unshare 直接执行 */
2
2
  import { spawn } from "node:child_process";
3
- import { readFile } from "node:fs/promises";
4
3
  import { setTimeout as sleep } from "node:timers/promises";
5
4
 
6
- // 用法:unshare -Urnp --fork --kill-child node holder.ts <config-base64> <mihomo> <slirp4netns> <mtu>
5
+ // 用法:unshare -Urnp --fork --kill-child node holder.ts <config-base64> <mihomo> <mtu> <mihomo-home-dir>
7
6
  // 本进程是 pid namespace 的 init:无论以何种方式退出(含 SIGKILL),内核都会清理该 pid ns 内的
8
- // slirp4netns / mihomo,userns/netns 引用随之归零。
7
+ // mihomo,userns/netns 引用随之归零。slirp4netns 由宿主侧启动(egress 必须留在宿主 netns,
8
+ // 否则出站流量会绕回 mihomo 的 TUN 被 dns-hijack 自劫持),它通过 exit-fd 绑定本进程的生命周期:
9
+ // fd 3 是 exit-fd 的写端(network-stack 经 unshare 传入),本进程存活期间保持打开,死亡即关闭,
10
+ // slirp4netns 侧收到 HUP 自行退出并释放 tap fd,netns 引用随之归零。
9
11
  const args = process.argv.slice(2);
10
12
  const configBase64 = args[0];
11
13
  const mihomoPath = args[1];
12
- const slirp4netnsPath = args[2];
13
- const tunMtu = Number(args[3]);
14
- if (!configBase64 || !mihomoPath || !slirp4netnsPath || !tunMtu) {
14
+ const tunMtu = Number(args[2]);
15
+ const mihomoHome = args[3];
16
+ if (!configBase64 || !mihomoPath || !tunMtu || !mihomoHome) {
15
17
  process.exit(2);
16
18
  }
17
19
 
@@ -40,28 +42,15 @@ async function waitFor(
40
42
 
41
43
  async function main(): Promise<void> {
42
44
  // 宿主(pi)进程死亡检测:宿主以任何方式退出(含 SIGKILL)都会关闭它持有的 stdin 写端,
43
- // 这里读到 EOF 即自杀(init 退出即触发内核清理整个 pid ns)。
45
+ // 这里读到 EOF 即自杀(init 退出即触发内核清理整个 pid ns,顺带关闭 exit-fd 写端)。
44
46
  process.stdin.resume();
45
47
  process.stdin.on("end", () => process.exit(0));
46
48
 
47
- // 宿主视角 pid(NSpid 第一项):/proc 挂载是宿主的(-Urnp 不含 -m,宿主视角下
48
- // /proc/1 是 systemd 而非本 pid ns 的 init),slirp4netns 的 setns 必须走宿主 /proc
49
- const status = await readFile("/proc/self/status", "utf8");
50
- const hostPid = /^NSpid:\s+(.+)$/m.exec(status)?.[1].split(/\s+/, 1)[0];
51
- if (!hostPid) {
52
- throw new Error("Failed to resolve host pid from NSpid");
53
- }
54
-
55
- // slirp4netns 提供 egress:本进程已在目标 userns/netns 内,setns 到自身 netns(no-op);
56
- // 日志 inherit 到 holder 的 stdout/stderr,宿主侧诊断(--verbose)可见
57
- spawn(slirp4netnsPath, ["-c", `--mtu=${tunMtu}`, "--netns-type=pid", hostPid, "tap0"], {
58
- stdio: ["ignore", "inherit", "inherit"],
59
- });
60
-
61
- // mihomo 日志透传到 holder 的 stdout/stderr,宿主侧监听 "Tun adapter listening" 判定就绪
49
+ // tap0 由宿主侧的 slirp4netns(fork 进本 netns)创建,就绪后再拉起 mihomo。
50
+ // mihomo 日志透传到 holder 的 stdout/stderr,宿主侧监听 "Tun adapter listening" 判定就绪。
62
51
  await waitFor(100, 100, tap0Exists);
63
52
 
64
- const mihomo = spawn(mihomoPath, ["-config", configBase64], {
53
+ const mihomo = spawn(mihomoPath, ["-d", mihomoHome, "-config", configBase64], {
65
54
  stdio: ["ignore", "inherit", "inherit"],
66
55
  });
67
56
 
@@ -20,6 +20,8 @@ export interface MihomoConfig {
20
20
  mode: "rule";
21
21
  "log-level": "info";
22
22
  ipv6: false;
23
+ /** 出站静态绑定 slirp 接口(固定名 tap0)。 */
24
+ "interface-name": string;
23
25
  dns: {
24
26
  enable: true;
25
27
  ipv6: false;
@@ -173,6 +175,11 @@ export function generateMihomoConfig(options: MihomoConfigOptions): MihomoConfig
173
175
  mode: "rule",
174
176
  "log-level": "info",
175
177
  ipv6: false,
178
+ // 静态绑定 tap0:auto-detect-interface 在启动瞬间可能探测到未就绪的接口
179
+ //(tap0 尚由 slirp4netns 创建),monitor 事后纠正但 DNS 拨号已经走错接口,
180
+ // 上游查询进自己的 TUN 被 dns-hijack 自劫持形成回环(allowlist 域名全部
181
+ // SERVFAIL)。slirp 接口名固定是 tap0,直接写死最可靠。
182
+ "interface-name": "tap0",
176
183
  dns: {
177
184
  enable: true,
178
185
  ipv6: false,
@@ -1,7 +1,11 @@
1
1
  import { type ChildProcess, spawn } from "node:child_process";
2
- import { readFile, readlink } from "node:fs/promises";
2
+ import { randomUUID } from "node:crypto";
3
+ import { mkdir, readFile, readlink } from "node:fs/promises";
4
+ import { join } from "node:path";
3
5
  import { fileURLToPath } from "node:url";
4
6
 
7
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
8
+
5
9
  import { forEachLine } from "../lib/proc.js";
6
10
  import { generateMihomoConfig, TUN_MTU } from "./mihomo-config.js";
7
11
 
@@ -178,12 +182,15 @@ export interface NetworkStack {
178
182
 
179
183
  interface NetworkStackState {
180
184
  holderPid: number;
185
+ slirpPid: number;
181
186
  }
182
187
 
183
188
  /** 兜底:调用方忘记 stop() 时,对象被 GC 回收后 kill 残留进程。 */
184
189
  const stackFinalizer = new FinalizationRegistry<NetworkStackState>((state) => {
185
- // SIGTERM 经 unshare --kill-child 转发给 init,内核清理 pid ns 内全部进程
190
+ // SIGTERM 经 unshare --kill-child 转发给 init,内核清理 pid ns 内全部进程;
191
+ // slirp4netns 在宿主侧持有 tap fd,单独终止
186
192
  killProcess(state.holderPid);
193
+ killProcess(state.slirpPid);
187
194
  });
188
195
 
189
196
  /**
@@ -203,10 +210,17 @@ export async function startNetworkStack(options: NetworkStackOptions): Promise<N
203
210
  const config = generateMihomoConfig({ allowlist, dnsServers });
204
211
  const configBase64 = Buffer.from(JSON.stringify(config)).toString("base64");
205
212
 
213
+ // mihomo 工作目录(-d):cache.db 等落在这里,而不是它默认的 ~/.config/mihomo/
214
+ //(后者不存在时 mihomo 每次启动都告警且 fakeip 映射无持久化)。每次启动用独立
215
+ // uuid 目录,避免并发的多个 holder 争抢 bbolt 文件锁。
216
+ const mihomoHome = join(getAgentDir(), "tmp", `mihomo-${randomUUID()}`);
217
+ await mkdir(mihomoHome, { recursive: true });
218
+
206
219
  let holder: ChildProcess | undefined;
220
+ let slirp: ChildProcess | undefined;
207
221
  try {
208
222
  // unshare -p --fork:node 成为 pid namespace 的 init,任何方式退出(含 SIGKILL)
209
- // 内核都会清理 pid ns 内全部进程(slirp4netns/mihomo),ns 引用随之归零;
223
+ // 内核都会清理 pid ns 内全部进程(mihomo),ns 引用随之归零;
210
224
  // --kill-child=SIGTERM:宿主侧 SIGTERM unshare 时转发给 init 走优雅退出
211
225
  holder = spawn(
212
226
  "unshare",
@@ -219,8 +233,8 @@ export async function startNetworkStack(options: NetworkStackOptions): Promise<N
219
233
  HOLDER_PATH,
220
234
  configBase64,
221
235
  mihomoPath,
222
- slirp4netnsPath,
223
236
  String(TUN_MTU),
237
+ mihomoHome,
224
238
  ],
225
239
  {
226
240
  env: {
@@ -228,8 +242,9 @@ export async function startNetworkStack(options: NetworkStackOptions): Promise<N
228
242
  PATH: `${process.env.PATH ?? ""}:${SBIN_PATH_SUFFIX}`,
229
243
  },
230
244
  // stdin 保持 pipe:本进程持有写端,进程退出(含 SIGKILL)时内核关闭 fd,
231
- // holder 读到 EOF 即自杀(init 退出 → 内核清理 pid ns)
232
- stdio: ["pipe", "pipe", "pipe"],
245
+ // holder 读到 EOF 即自杀(init 退出 → 内核清理 pid ns)。
246
+ // fd 3:exit-fd 写端,传给 holder 持有(holder 死亡 → 读端 HUP → slirp4netns 退出)。
247
+ stdio: ["pipe", "pipe", "pipe", "pipe"],
233
248
  },
234
249
  );
235
250
  forwardOutput(holder, holderOutput);
@@ -239,9 +254,45 @@ export async function startNetworkStack(options: NetworkStackOptions): Promise<N
239
254
  const holderPid = holder.pid;
240
255
  await waitForNewUserns(holderPid);
241
256
 
257
+ // slirp4netns 提供 egress,必须在宿主 netns 启动:它的 egress socket 决定出站
258
+ // 视角,留在沙盒 netns 里会被 mihomo 的 TUN 策略路由 + dns-hijack 自劫持成环
259
+ //(上游 DNS 查询自己劫自己,allowlist 域名全部 SERVFAIL)。tap fd 会被它持有
260
+ // 而 pin 住 netns,因此用 exit-fd(holder 的 fd 3 写端的读端)绑定 holder 生命
261
+ // 周期:holder 退出 → 读端 HUP → slirp4netns 退出 → tap fd 释放。
262
+ // --userns-path / --netns-type=pid 都指向 unshare 进程:它创建并持有目标
263
+ // userns/netns(node holder 是它的子进程,同 ns)。
264
+ // exit-fd 的读端 fd:从 holder 的额外 stdio pipe 取父进程侧的原始 fd。
265
+ // Node 没有公开 API 拿它(stdio[3].fd 恒为 undefined,只能读 _handle,且仅在
266
+ // 子进程存活期间有效);pipe 要跨两个子进程共享(holder 持写端、slirp4netns
267
+ // 持读端),所以必须把父进程侧的 fd 重新 dup 给 slirp4netns。
268
+ const exitReadFd = (holder.stdio[3] as unknown as { _handle?: { fd?: number } } | null)?._handle
269
+ ?.fd;
270
+ if (typeof exitReadFd !== "number") {
271
+ throw new TypeError("Failed to resolve exit-fd from holder stdio");
272
+ }
273
+ slirp = spawn(
274
+ slirp4netnsPath,
275
+ [
276
+ "-c",
277
+ `--mtu=${TUN_MTU}`,
278
+ `--userns-path=/proc/${String(holderPid)}/ns/user`,
279
+ "--netns-type=pid",
280
+ String(holderPid),
281
+ "tap0",
282
+ // exit-fd:本子进程的 fd 3(stdio 第 4 项 dup 为 fd 3)
283
+ "-e",
284
+ "3",
285
+ ],
286
+ { stdio: ["ignore", "pipe", "pipe", exitReadFd] },
287
+ );
288
+ forwardOutput(slirp, holderOutput);
289
+ if (slirp.pid === undefined) {
290
+ throw new Error("Failed to start slirp4netns");
291
+ }
292
+
242
293
  await waitForMihomoStarted(holder);
243
294
 
244
- const state: NetworkStackState = { holderPid };
295
+ const state: NetworkStackState = { holderPid, slirpPid: slirp.pid };
245
296
  const stack: NetworkStack = {
246
297
  exec: async (execOptions: NetworkStackExecOptions) => {
247
298
  const child = spawn(
@@ -311,10 +362,14 @@ export async function startNetworkStack(options: NetworkStackOptions): Promise<N
311
362
  },
312
363
  stop: async () => {
313
364
  const children = await readChildPids(state.holderPid);
365
+ // slirp4netns 持有 tap fd(pin 住 netns),必须随 holder 一起显式终止;
366
+ // 先杀它再杀 holder,避免 stop() 与 exit-fd HUP 的收尾时序竞争
367
+ killProcess(state.slirpPid);
314
368
  // SIGTERM unshare → --kill-child 转发 SIGTERM 给 init(pid ns 的 pid 1),
315
369
  // init 优雅停 mihomo 后退出,内核清理 pid ns 内全部进程,ns 引用随之归零
316
370
  killProcess(state.holderPid);
317
371
  await waitForExit(state.holderPid);
372
+ await waitForExit(state.slirpPid);
318
373
  // 兜底:init 未在超时内退出 → SIGKILL init → 内核清 pid ns
319
374
  for (const pid of children) {
320
375
  killProcess(pid, "SIGKILL");
@@ -326,7 +381,11 @@ export async function startNetworkStack(options: NetworkStackOptions): Promise<N
326
381
  return stack;
327
382
  } catch (error) {
328
383
  // 失败清理:holder(unshare)的 SIGTERM 经 --kill-child 转发给 init,
329
- // init 退出时内核清理 pid ns 内全部进程;调用方拿不到 stack,这里只能靠自己
384
+ // init 退出时内核清理 pid ns 内全部进程;slirp4netns 在宿主侧,需单独终止
385
+ //(exit-fd 写端也会随 holder 死亡关闭,这里主动杀只是不等到 HUP 轮询)
386
+ if (slirp?.pid) {
387
+ killProcess(slirp.pid);
388
+ }
330
389
  if (holder?.pid) {
331
390
  const children = await readChildPids(holder.pid);
332
391
  killProcess(holder.pid);
@@ -1,10 +1,10 @@
1
1
  /**
2
- * 诊断报告格式化:报告 ERROR 与 WARN,每个文件最多 20 条。
2
+ * 诊断报告格式化:报告 ERROR 与 WARN,每个文件最多 5 条。
3
3
  */
4
4
 
5
5
  import type { Diagnostic } from "./client.js";
6
6
 
7
- const MAX_PER_FILE = 20;
7
+ const MAX_PER_FILE = 5;
8
8
 
9
9
  const SEVERITY_LABELS: Record<number, string> = {
10
10
  1: "ERROR",