leo-link 0.0.0-stage → 1.3.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.
Files changed (3) hide show
  1. package/README.md +37 -2
  2. package/dist/index.js +4648 -0
  3. package/package.json +42 -4
package/dist/index.js ADDED
@@ -0,0 +1,4648 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/main.ts
4
+ import { spawn as spawn4 } from "child_process";
5
+ import { realpathSync as realpathSync2 } from "fs";
6
+ import { realpath as realpath9 } from "fs/promises";
7
+ import { homedir as homedir8, hostname } from "os";
8
+
9
+ // ../link/src/core/cli.ts
10
+ import { execFile, spawn as spawn2 } from "child_process";
11
+ import { homedir } from "os";
12
+ import { win32 as win322 } from "path";
13
+ import { promisify } from "util";
14
+
15
+ // ../link/src/core/winLaunch.ts
16
+ import { spawn } from "child_process";
17
+ import { existsSync, readFileSync } from "fs";
18
+ import { win32 } from "path";
19
+ function pickWhere(stdout) {
20
+ const lines = stdout.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
21
+ const ext = (l) => l.slice(l.lastIndexOf(".")).toLowerCase();
22
+ return lines.find((l) => ext(l) === ".exe") ?? lines.find((l) => [".cmd", ".bat"].includes(ext(l))) ?? "";
23
+ }
24
+ var SHIM_TARGET = /"%(?:~dp0|dp0%)\\([^"%]+\.[cm]?js)"/i;
25
+ function launchOf(path, args, deps = {}) {
26
+ const platform = deps.platform ?? process.platform;
27
+ if (platform !== "win32" || !/\.(cmd|bat)$/i.test(path)) return { file: path, args };
28
+ const read = deps.readFile ?? ((p) => readFileSync(p, "utf8"));
29
+ const exists2 = deps.exists ?? existsSync;
30
+ let shim;
31
+ try {
32
+ shim = read(path);
33
+ } catch {
34
+ return null;
35
+ }
36
+ const m = shim.match(SHIM_TARGET);
37
+ if (!m) return null;
38
+ const dir = win32.dirname(path);
39
+ const script = win32.join(dir, m[1]);
40
+ const node = [dir, ...(deps.pathEnv ?? process.env.PATH ?? "").split(";")].filter(Boolean).map((d) => win32.join(d, "node.exe")).find((p) => exists2(p));
41
+ return node ? { file: node, args: [script, ...args] } : null;
42
+ }
43
+ function killTree(child, signal, deps = {}) {
44
+ if (child.exitCode !== null || child.signalCode !== null) return;
45
+ if ((deps.platform ?? process.platform) !== "win32" || child.pid === void 0) {
46
+ child.kill(signal);
47
+ return;
48
+ }
49
+ const taskkill = win32.join(deps.systemRoot ?? process.env.SystemRoot ?? "C:\\Windows", "System32", "taskkill.exe");
50
+ try {
51
+ (deps.spawnImpl ?? spawn)(taskkill, ["/PID", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true }).on("error", () => child.kill());
52
+ } catch {
53
+ child.kill();
54
+ }
55
+ }
56
+
57
+ // ../link/src/core/cli.ts
58
+ var execFileP = promisify(execFile);
59
+ var defaultExec = async (file, args) => {
60
+ await shellPath.ready();
61
+ const env = loginPathEnv();
62
+ const launch = launchOf(file, args, { pathEnv: env.PATH });
63
+ if (!launch) throw new Error(`cannot launch ${file}`);
64
+ const { stdout } = await execFileP(launch.file, launch.args, { timeout: 8e3, env, windowsHide: true });
65
+ return { stdout };
66
+ };
67
+ var SHELL_TIMEOUT_MS = 5e3;
68
+ var SHELL_REFRESH_THROTTLE_MS = 3e4;
69
+ var MARK = "__LEO_SHELL_PATH__";
70
+ var MAX_OUTPUT = 1 << 20;
71
+ var runInteractiveShell = (shell, script, timeoutMs, env, done) => new Promise((resolve3, reject) => {
72
+ const child = spawn2(shell, ["-ilc", script], { env, stdio: ["ignore", "pipe", "ignore"], detached: true });
73
+ let out = "";
74
+ const timer = setTimeout(() => {
75
+ try {
76
+ process.kill(-child.pid, "SIGKILL");
77
+ } catch {
78
+ }
79
+ reject(new Error(`${shell} -ilc timed out after ${timeoutMs}ms`));
80
+ }, timeoutMs);
81
+ child.stdout.setEncoding("utf8");
82
+ child.stdout.on("data", (d) => {
83
+ if (out.length < MAX_OUTPUT) out += d;
84
+ if (done?.(out)) {
85
+ clearTimeout(timer);
86
+ child.stdout.destroy();
87
+ resolve3(out);
88
+ }
89
+ });
90
+ child.on("error", (e) => {
91
+ clearTimeout(timer);
92
+ reject(e);
93
+ });
94
+ child.on("close", () => {
95
+ clearTimeout(timer);
96
+ resolve3(out);
97
+ });
98
+ });
99
+ var ShellPath = class {
100
+ entries = [];
101
+ pending = null;
102
+ lastStart = -Infinity;
103
+ deps;
104
+ constructor(deps = {}) {
105
+ this.deps = deps;
106
+ }
107
+ get() {
108
+ return this.entries;
109
+ }
110
+ /** 等正在进行的读取(首次读取)完成;没有在读就立即返回 */
111
+ async ready() {
112
+ await this.pending;
113
+ }
114
+ /**
115
+ * 重新读取。true = PATH 变了,false = 没变,null = 节流中或读取失败(没有新信息)。
116
+ * 「变了」不等于多了有用的东西:fnm 每个 shell 都给一个新的临时目录,每次读都不一样。
117
+ */
118
+ refresh() {
119
+ if (this.pending) return this.pending;
120
+ const now = (this.deps.now ?? Date.now)();
121
+ if (now - this.lastStart < SHELL_REFRESH_THROTTLE_MS) return Promise.resolve(null);
122
+ this.lastStart = now;
123
+ this.pending = this.read().finally(() => {
124
+ this.pending = null;
125
+ });
126
+ return this.pending;
127
+ }
128
+ async read() {
129
+ if ((this.deps.platform ?? process.platform) === "win32") return null;
130
+ const env = this.deps.env ?? process.env;
131
+ const shell = /^\/.*\/(zsh|bash)$/.test(env.SHELL ?? "") ? env.SHELL : "/bin/zsh";
132
+ const clean = {};
133
+ for (const [k, v] of Object.entries(env)) if (!k.startsWith("ELECTRON_")) clean[k] = v;
134
+ let out;
135
+ try {
136
+ out = await (this.deps.run ?? runInteractiveShell)(
137
+ shell,
138
+ `printf '%s%s%s' ${MARK} "$PATH" ${MARK}`,
139
+ SHELL_TIMEOUT_MS,
140
+ clean,
141
+ (o) => o.split(MARK).length >= 3
142
+ );
143
+ } catch {
144
+ return null;
145
+ }
146
+ const m = out.match(new RegExp(`${MARK}([^\\n]*?)${MARK}`));
147
+ if (!m) return null;
148
+ const next = m[1].split(":").filter((p) => p.startsWith("/"));
149
+ const changed = next.join(":") !== this.entries.join(":");
150
+ this.entries = next;
151
+ return changed;
152
+ }
153
+ /** 测试用:换一份依赖、清空状态 */
154
+ reset(deps = {}) {
155
+ this.deps = deps;
156
+ this.entries = [];
157
+ this.pending = null;
158
+ this.lastStart = -Infinity;
159
+ }
160
+ };
161
+ var shellPath = new ShellPath();
162
+ function loginPathEnv(platform = process.platform, base = process.env) {
163
+ const win = platform === "win32";
164
+ const env = {};
165
+ let current = "";
166
+ for (const [k, v] of Object.entries(base)) {
167
+ if (win ? k.toUpperCase() === "PATH" : k === "PATH") current = v ?? "";
168
+ else env[k] = v;
169
+ }
170
+ const home = win ? base.USERPROFILE ?? homedir() : base.HOME ?? "";
171
+ const extra = win ? [
172
+ ...base.APPDATA ? [win322.join(base.APPDATA, "npm")] : [],
173
+ win322.join(home, ".local", "bin"),
174
+ win322.join(home, ".volta", "bin"),
175
+ ...base.ProgramFiles ? [win322.join(base.ProgramFiles, "nodejs")] : []
176
+ ] : [`${home}/.local/bin`, `${home}/.npm-global/bin`, `${home}/.volta/bin`, "/opt/homebrew/bin", "/usr/local/bin"];
177
+ const sep3 = win ? ";" : ":";
178
+ const parts = Array.from(/* @__PURE__ */ new Set([...shellPath.get(), ...current.split(sep3).filter(Boolean), ...extra]));
179
+ return { ...env, PATH: parts.join(sep3) };
180
+ }
181
+ async function detectOne(name, exec, platform) {
182
+ let path;
183
+ try {
184
+ const win = platform === "win32";
185
+ const { stdout } = await exec(win ? "where" : "which", [name]);
186
+ path = win ? pickWhere(stdout) : stdout.split(/\r?\n/).find((l) => l.trim())?.trim() ?? "";
187
+ } catch {
188
+ return { found: false };
189
+ }
190
+ if (!path) return { found: false };
191
+ try {
192
+ const { stdout } = await exec(path, ["--version"]);
193
+ const version = stdout.match(/\d+\.\d+(\.\d+)?/)?.[0];
194
+ return { found: true, path, version };
195
+ } catch {
196
+ return { found: true, path };
197
+ }
198
+ }
199
+ async function detectClis(exec = defaultExec, platform = process.platform) {
200
+ const [claude, codex] = await Promise.all([detectOne("claude", exec, platform), detectOne("codex", exec, platform)]);
201
+ return { claude, codex };
202
+ }
203
+
204
+ // ../link/src/core/config.ts
205
+ import { mkdirSync, readFileSync as readFileSync2, renameSync, writeFileSync } from "fs";
206
+ import { dirname } from "path";
207
+
208
+ // ../link/src/core/serverUrl.ts
209
+ var OCTET = /^(0|[1-9]\d{0,2})$/;
210
+ function isLocalIpv4(host) {
211
+ const parts = host.split(".");
212
+ if (parts.length !== 4 || !parts.every((p) => OCTET.test(p) && Number(p) <= 255)) return false;
213
+ const [a, b] = parts.map(Number);
214
+ return a === 127 || // 回环
215
+ a === 10 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a === 169 && b === 254 || // 链路本地
216
+ a === 100 && b >= 64 && b <= 127;
217
+ }
218
+ function isLocalIpv6(host) {
219
+ return host === "::1" || /^f[cd][0-9a-f]{2}:/.test(host) || /^fe[89ab][0-9a-f]:/.test(host);
220
+ }
221
+ function isLocalHost(hostname2) {
222
+ const host = hostname2.toLowerCase();
223
+ if (host === "localhost" || host.endsWith(".local")) return true;
224
+ if (host.startsWith("[") && host.endsWith("]")) return isLocalIpv6(host.slice(1, -1));
225
+ return isLocalIpv4(host);
226
+ }
227
+ function parseServerUrl(url) {
228
+ const trimmed = url.trim();
229
+ const m = /^(https?):\/\/([^/?#]*)/i.exec(trimmed);
230
+ if (!m || !m[2]) return { error: "\u670D\u52A1\u5668\u5730\u5740\u9700\u8981\u4EE5 http:// \u6216 https:// \u5F00\u5934" };
231
+ if (/[\s@]/.test(m[2]) || /[\\\u0000-\u001f\u007f]/.test(trimmed)) {
232
+ return { error: "\u670D\u52A1\u5668\u5730\u5740\u91CC\u4E0D\u80FD\u6709\u7528\u6237\u540D\u3001\u53CD\u659C\u6760\u6216\u7A7A\u767D\u5B57\u7B26" };
233
+ }
234
+ const authority = /^(\[[^\]]*\]|[^:[\]]+)(:\d*)?$/.exec(m[2]);
235
+ if (!authority) return { error: "\u670D\u52A1\u5668\u5730\u5740\u683C\u5F0F\u4E0D\u6B63\u786E" };
236
+ return { origin: `${m[1].toLowerCase()}://${m[2]}`, host: authority[1] };
237
+ }
238
+ function insecureServerUrlReason(url) {
239
+ const parsed = parseServerUrl(url);
240
+ if ("error" in parsed) return parsed.error;
241
+ if (parsed.origin.startsWith("https:")) return null;
242
+ if (isLocalHost(parsed.host)) return null;
243
+ return `${parsed.host} \u4E0D\u662F\u5C40\u57DF\u7F51\u5730\u5740\uFF0C\u5FC5\u987B\u7528 https:// \u8FDE\u63A5\u2014\u2014\u7528 http \u4F1A\u8BA9\u8BBE\u5907\u51ED\u8BC1\u4E0E\u6307\u4EE4\u660E\u6587\u7ECF\u8FC7\u7F51\u7EDC`;
244
+ }
245
+
246
+ // ../link/src/core/config.ts
247
+ var DEFAULT_TOGGLES = { cli: false, userpc: false };
248
+ function defaultConfig(deviceName) {
249
+ return { serverUrl: null, token: null, deviceId: null, deviceName, toggles: { ...DEFAULT_TOGGLES } };
250
+ }
251
+ function normalizeServerUrl(input) {
252
+ const trimmed = input.trim();
253
+ if (!trimmed) throw new Error("\u670D\u52A1\u5668\u5730\u5740\u4E0D\u80FD\u4E3A\u7A7A");
254
+ const hasScheme = /^https?:\/\//i.test(trimmed);
255
+ let url;
256
+ try {
257
+ url = new URL(hasScheme ? trimmed : `http://${trimmed}`);
258
+ } catch {
259
+ throw new Error("\u670D\u52A1\u5668\u5730\u5740\u683C\u5F0F\u4E0D\u6B63\u786E");
260
+ }
261
+ if (!url.hostname) throw new Error("\u670D\u52A1\u5668\u5730\u5740\u683C\u5F0F\u4E0D\u6B63\u786E");
262
+ if (!hasScheme && !isLocalHost(url.hostname)) url.protocol = "https:";
263
+ const base = `${url.protocol}//${url.host}`;
264
+ const insecure = insecureServerUrlReason(base);
265
+ if (insecure) throw new Error(insecure);
266
+ return base;
267
+ }
268
+ function readConfigFile(path) {
269
+ try {
270
+ const parsed = JSON.parse(readFileSync2(path, "utf8"));
271
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
272
+ } catch {
273
+ return null;
274
+ }
275
+ }
276
+ function parseLinkConfig(raw, deviceName) {
277
+ if (!raw) return defaultConfig(deviceName);
278
+ const toggles = raw.toggles ?? {};
279
+ return {
280
+ serverUrl: typeof raw.serverUrl === "string" ? raw.serverUrl : null,
281
+ token: typeof raw.token === "string" ? raw.token : null,
282
+ deviceId: typeof raw.deviceId === "string" ? raw.deviceId : null,
283
+ deviceName: typeof raw.deviceName === "string" && raw.deviceName ? raw.deviceName : deviceName,
284
+ toggles: { cli: toggles.cli === true, userpc: toggles.userpc === true }
285
+ };
286
+ }
287
+ function saveConfig(path, config) {
288
+ mkdirSync(dirname(path), { recursive: true });
289
+ const tmp = `${path}.tmp`;
290
+ writeFileSync(tmp, JSON.stringify(config, null, 2), { encoding: "utf8", mode: 384 });
291
+ renameSync(tmp, path);
292
+ }
293
+ function linkConfigStore(path, deviceName) {
294
+ return {
295
+ load: () => parseLinkConfig(readConfigFile(path), deviceName),
296
+ save: (config) => saveConfig(path, config)
297
+ };
298
+ }
299
+ function isPaired(config) {
300
+ return Boolean(config.serverUrl && config.token && config.deviceId);
301
+ }
302
+
303
+ // ../link/src/core/link.ts
304
+ var RpcFailure = class extends Error {
305
+ code;
306
+ data;
307
+ constructor(code, message, data) {
308
+ super(message);
309
+ this.code = code;
310
+ this.data = data;
311
+ }
312
+ };
313
+ var RECONNECT_BACKOFF_MS = [1e3, 2e3, 4e3, 8e3, 16e3, 3e4];
314
+ var LIVENESS_TIMEOUT_MS = 6e4;
315
+ var HANDSHAKE_TIMEOUT_MS = 2e4;
316
+ var METHOD_NOT_FOUND = -32601;
317
+ var INVALID_REQUEST = -32600;
318
+ var INTERNAL_ERROR = -32603;
319
+ var CAPABILITY_DISABLED = -32001;
320
+ var REQUEST_CANCELLED = -32002;
321
+ var defaultDelay = (ms) => new Promise((r) => setTimeout(r, ms));
322
+ var defaultSchedule = (fn, ms) => {
323
+ const handle = setTimeout(fn, ms);
324
+ return () => clearTimeout(handle);
325
+ };
326
+ var Generation = class {
327
+ inflight = /* @__PURE__ */ new Map();
328
+ ws;
329
+ closed = false;
330
+ constructor(ws) {
331
+ this.ws = ws;
332
+ }
333
+ send(frame) {
334
+ if (this.closed) return;
335
+ try {
336
+ this.ws.send(JSON.stringify(frame));
337
+ } catch {
338
+ }
339
+ }
340
+ close() {
341
+ this.closed = true;
342
+ for (const f of this.inflight.values()) f.controller.abort();
343
+ this.inflight.clear();
344
+ }
345
+ };
346
+ var LinkClient = class {
347
+ stopped = true;
348
+ gen = null;
349
+ attempt = 0;
350
+ status = "disconnected";
351
+ loopPromise = null;
352
+ wakeReconnect = null;
353
+ /** 当前连接的强制断开入口(连接期间才有);断开原因随之进入状态 */
354
+ drop = null;
355
+ /** 下一次断开后不退避(手动重连) */
356
+ skipBackoff = false;
357
+ deps;
358
+ constructor(deps) {
359
+ this.deps = deps;
360
+ }
361
+ get currentStatus() {
362
+ return this.status;
363
+ }
364
+ /** 在飞请求数(测试/诊断) */
365
+ get inflightCount() {
366
+ return this.gen?.inflight.size ?? 0;
367
+ }
368
+ start() {
369
+ if (!this.stopped) return;
370
+ this.stopped = false;
371
+ this.attempt = 0;
372
+ this.loopPromise = this.runLoop();
373
+ }
374
+ async stop() {
375
+ if (this.stopped) return;
376
+ this.stopped = true;
377
+ this.gen?.ws.close();
378
+ this.wakeReconnect?.();
379
+ await this.loopPromise;
380
+ this.setStatus("disconnected", null);
381
+ }
382
+ /** 声明变化:在线则立刻重发 hello;离线则下次连上自然带最新声明。 */
383
+ sendHello() {
384
+ if (this.status === "online") this.gen?.send({ jsonrpc: "2.0", method: "hello", params: this.deps.hello() });
385
+ }
386
+ /** 能力被关闭:取消该命名空间(如 "process.")下所有在飞请求。 */
387
+ abortNamespace(prefix) {
388
+ let n = 0;
389
+ for (const f of this.gen?.inflight.values() ?? []) {
390
+ if (f.method.startsWith(prefix)) {
391
+ f.controller.abort();
392
+ n += 1;
393
+ }
394
+ }
395
+ return n;
396
+ }
397
+ /** 立刻重试(用户点了「重新连接」):退避中则跳过剩余等待;在线/连接中则强制
398
+ * 断开当前 socket 重连——本地显示在线不代表服务端也这么认为(半开连接)。 */
399
+ reconnectNow() {
400
+ this.attempt = 0;
401
+ if (this.drop) {
402
+ this.skipBackoff = true;
403
+ this.drop("\u624B\u52A8\u91CD\u65B0\u8FDE\u63A5");
404
+ } else {
405
+ this.wakeReconnect?.();
406
+ }
407
+ }
408
+ setStatus(status2, error) {
409
+ this.status = status2;
410
+ this.deps.onStatus?.(status2, error);
411
+ }
412
+ async runLoop() {
413
+ while (!this.stopped) {
414
+ this.setStatus("connecting", null);
415
+ await this.connectOnce();
416
+ if (this.stopped) break;
417
+ if (this.skipBackoff) {
418
+ this.skipBackoff = false;
419
+ continue;
420
+ }
421
+ const backoff = RECONNECT_BACKOFF_MS[Math.min(this.attempt, RECONNECT_BACKOFF_MS.length - 1)];
422
+ this.attempt += 1;
423
+ await Promise.race([
424
+ (this.deps.delay ?? defaultDelay)(backoff),
425
+ new Promise((r) => {
426
+ this.wakeReconnect = r;
427
+ })
428
+ ]);
429
+ this.wakeReconnect = null;
430
+ }
431
+ }
432
+ /** 一次连接的生命周期;resolve 值是断开原因(人话)。 */
433
+ connectOnce() {
434
+ return new Promise((resolve3) => {
435
+ let ws;
436
+ try {
437
+ ws = this.deps.connect();
438
+ } catch (e) {
439
+ const reason = e instanceof Error ? e.message : "\u65E0\u6CD5\u5EFA\u7ACB\u8FDE\u63A5";
440
+ if (!this.stopped) this.setStatus("disconnected", reason);
441
+ resolve3(reason);
442
+ return;
443
+ }
444
+ const gen = new Generation(ws);
445
+ this.gen = gen;
446
+ let opened = false;
447
+ let failed = false;
448
+ let settled = false;
449
+ let cancelWatchdog = null;
450
+ const finish = (reason) => {
451
+ if (settled) return;
452
+ settled = true;
453
+ cancelWatchdog?.();
454
+ cancelWatchdog = null;
455
+ if (this.drop === drop) this.drop = null;
456
+ gen.close();
457
+ if (this.gen === gen) this.gen = null;
458
+ if (!this.stopped) this.setStatus("disconnected", reason);
459
+ resolve3(reason);
460
+ };
461
+ const drop = (reason) => {
462
+ if (settled) return;
463
+ finish(reason);
464
+ try {
465
+ ws.terminate();
466
+ } catch {
467
+ }
468
+ };
469
+ const armWatchdog = (reason, ms) => {
470
+ if (settled) return;
471
+ cancelWatchdog?.();
472
+ cancelWatchdog = (this.deps.schedule ?? defaultSchedule)(() => drop(reason), ms);
473
+ };
474
+ const armLiveness = () => armWatchdog("\u8FDE\u63A5\u65E0\u54CD\u5E94\uFF08\u5FC3\u8DF3\u8D85\u65F6\uFF09", this.deps.livenessTimeoutMs ?? LIVENESS_TIMEOUT_MS);
475
+ this.drop = drop;
476
+ armWatchdog("\u8FDE\u63A5\u8D85\u65F6\uFF08\u63E1\u624B\u65E0\u54CD\u5E94\uFF09", HANDSHAKE_TIMEOUT_MS);
477
+ ws.onopen = () => {
478
+ opened = true;
479
+ this.attempt = 0;
480
+ gen.send({ jsonrpc: "2.0", method: "hello", params: this.deps.hello() });
481
+ armLiveness();
482
+ this.setStatus("online", null);
483
+ };
484
+ ws.onmessage = (ev) => {
485
+ if (gen.closed) return;
486
+ armLiveness();
487
+ void this.handleFrame(gen, String(ev.data));
488
+ };
489
+ ws.onerror = () => {
490
+ failed = true;
491
+ };
492
+ ws.onclose = (ev) => {
493
+ if (!opened) {
494
+ finish(failed ? "\u8FDE\u63A5\u88AB\u62D2\u7EDD\u6216\u670D\u52A1\u5668\u4E0D\u53EF\u8FBE" : "\u8FDE\u63A5\u5728\u5EFA\u7ACB\u524D\u88AB\u5173\u95ED");
495
+ } else {
496
+ finish(ev?.reason ? `\u8FDE\u63A5\u5DF2\u65AD\u5F00\uFF1A${ev.reason}` : "\u8FDE\u63A5\u5DF2\u65AD\u5F00");
497
+ }
498
+ };
499
+ });
500
+ }
501
+ async handleFrame(gen, text) {
502
+ let frame;
503
+ try {
504
+ frame = JSON.parse(text);
505
+ } catch {
506
+ gen.send({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } });
507
+ return;
508
+ }
509
+ if (!frame || typeof frame !== "object") return;
510
+ const f = frame;
511
+ if (typeof f.method !== "string") return;
512
+ const params = f.params && typeof f.params === "object" && !Array.isArray(f.params) ? f.params : null;
513
+ const isRequest = f.id !== void 0 && f.id !== null;
514
+ if (params === null) {
515
+ if (isRequest) gen.send({ jsonrpc: "2.0", id: f.id, error: { code: INVALID_REQUEST, message: "params must be an object" } });
516
+ return;
517
+ }
518
+ if (!isRequest) {
519
+ if (f.method.endsWith(".cancel")) {
520
+ const target = params.id;
521
+ if (typeof target === "number" || typeof target === "string") gen.inflight.get(target)?.controller.abort();
522
+ }
523
+ return;
524
+ }
525
+ const id = f.id;
526
+ if (!(this.deps.authorize?.(f.method) ?? false)) {
527
+ gen.send({ jsonrpc: "2.0", id, error: { code: CAPABILITY_DISABLED, message: `Capability disabled: ${f.method}` } });
528
+ return;
529
+ }
530
+ const handler = this.deps.handlers?.[f.method];
531
+ if (!handler) {
532
+ gen.send({ jsonrpc: "2.0", id, error: { code: METHOD_NOT_FOUND, message: `Method not found: ${f.method}` } });
533
+ return;
534
+ }
535
+ const controller = new AbortController();
536
+ gen.inflight.set(id, { method: f.method, controller });
537
+ const ctx = {
538
+ id,
539
+ method: f.method,
540
+ notify: (method, p) => gen.send({ jsonrpc: "2.0", method, params: { ...p ?? {}, id } }),
541
+ signal: controller.signal
542
+ };
543
+ try {
544
+ const result = await handler(params, ctx);
545
+ if (controller.signal.aborted) {
546
+ gen.send({ jsonrpc: "2.0", id, error: { code: REQUEST_CANCELLED, message: "Request cancelled" } });
547
+ } else {
548
+ gen.send({ jsonrpc: "2.0", id, result: result ?? null });
549
+ }
550
+ } catch (e) {
551
+ if (controller.signal.aborted) {
552
+ gen.send({ jsonrpc: "2.0", id, error: { code: REQUEST_CANCELLED, message: "Request cancelled" } });
553
+ } else if (e instanceof RpcFailure) {
554
+ gen.send({ jsonrpc: "2.0", id, error: { code: e.code, message: e.message, ...e.data !== void 0 ? { data: e.data } : {} } });
555
+ } else {
556
+ gen.send({ jsonrpc: "2.0", id, error: { code: INTERNAL_ERROR, message: e instanceof Error ? e.message : String(e) } });
557
+ }
558
+ } finally {
559
+ gen.inflight.delete(id);
560
+ }
561
+ }
562
+ };
563
+
564
+ // ../link/src/core/pairing.ts
565
+ async function redeemPairingCode(baseUrl, code, deviceName, fetchImpl = fetch) {
566
+ const trimmed = code.trim();
567
+ if (!trimmed) throw new Error("\u8BF7\u8F93\u5165\u914D\u5BF9\u7801");
568
+ let res;
569
+ try {
570
+ res = await fetchImpl(`${baseUrl}/api/auth/pair/redeem`, {
571
+ method: "POST",
572
+ headers: { "Content-Type": "application/json" },
573
+ body: JSON.stringify({ code: trimmed, device_name: deviceName, platform: "desktop" })
574
+ });
575
+ } catch {
576
+ throw new Error("\u65E0\u6CD5\u8FDE\u63A5\u5230\u670D\u52A1\u5668\uFF0C\u8BF7\u68C0\u67E5\u5730\u5740\u4E0E\u7F51\u7EDC");
577
+ }
578
+ if (res.status === 401) throw new Error("\u914D\u5BF9\u7801\u65E0\u6548\u6216\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u5728\u914D\u7F6E\u9875\u91CD\u65B0\u751F\u6210");
579
+ if (res.status === 429) throw new Error("\u5C1D\u8BD5\u6B21\u6570\u8FC7\u591A\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5");
580
+ if (res.status === 503) throw new Error("\u670D\u52A1\u6B63\u5728\u542F\u52A8\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5");
581
+ if (!res.ok) throw new Error(`\u914D\u5BF9\u5931\u8D25\uFF08HTTP ${res.status}\uFF09`);
582
+ const body = await res.json();
583
+ if (!body.token || !body.device_id) throw new Error("\u670D\u52A1\u7AEF\u7248\u672C\u8FC7\u65E7\uFF0C\u4E0D\u652F\u6301\u684C\u9762\u7AEF\u914D\u5BF9");
584
+ return { token: body.token, deviceId: body.device_id, userName: body.user_name, serverVersion: body.version };
585
+ }
586
+
587
+ // ../link/src/core/app.ts
588
+ var NAMESPACE_TOGGLE = {
589
+ "process.": "cli",
590
+ "pc.": "userpc"
591
+ };
592
+ var TOGGLE_LABELS = {
593
+ cli: "\u501F\u51FA\u672C\u673A Claude Code / Codex \u7ED9 Leo \u670D\u52A1\u7AEF\u4F5C\u4E3A\u6A21\u578B\u6765\u6E90",
594
+ userpc: "\u5141\u8BB8 Leo \u670D\u52A1\u7AEF\u64CD\u4F5C\u8FD9\u53F0\u7535\u8111"
595
+ };
596
+ var UserDeclined = class extends Error {
597
+ constructor() {
598
+ super("\u7528\u6237\u53D6\u6D88\u4E86\u64CD\u4F5C");
599
+ }
600
+ };
601
+ var LinkApp = class {
602
+ config;
603
+ cli = { claude: { found: false }, codex: { found: false } };
604
+ link = null;
605
+ linkStatus = "disconnected";
606
+ linkError = null;
607
+ lastNotice = null;
608
+ deps;
609
+ constructor(deps) {
610
+ this.deps = deps;
611
+ this.config = deps.config.load();
612
+ this.dropInsecurePairing();
613
+ }
614
+ /**
615
+ * 早于这条规则配对的公网 http 地址:bearer 与指令一直在明文传。只在本机忘掉凭证,不去服务端
616
+ * 吊销——吊销请求本身会把 bearer 再明文送一次;请用户在配置页删掉旧设备、用 https 重新配对。
617
+ */
618
+ dropInsecurePairing() {
619
+ const url = this.config.serverUrl;
620
+ const insecure = url ? insecureServerUrlReason(url) : null;
621
+ if (!insecure) return;
622
+ this.config = this.clearSession({ ...this.config, serverUrl: null, token: null, deviceId: null });
623
+ this.persist();
624
+ this.lastNotice = `\u5DF2\u89E3\u9664\u4E0E ${url} \u7684\u914D\u5BF9\uFF1A${insecure}\u3002\u8BF7\u7528 https \u5730\u5740\u91CD\u65B0\u914D\u5BF9\uFF0C\u5E76\u5230\u914D\u7F6E\u9875\u300C\u5BA2\u6237\u7AEF\u300D\u91CC\u5220\u9664\u8FD9\u53F0\u7535\u8111\u7684\u65E7\u8BB0\u5F55`;
625
+ }
626
+ async start() {
627
+ await this.redetectCli();
628
+ if (isPaired(this.config)) this.startLink();
629
+ this.emit();
630
+ }
631
+ async stop() {
632
+ await this.link?.stop();
633
+ this.link = null;
634
+ }
635
+ getState() {
636
+ return {
637
+ paired: isPaired(this.config),
638
+ serverUrl: this.config.serverUrl,
639
+ deviceId: this.config.deviceId,
640
+ deviceName: this.config.deviceName,
641
+ toggles: { ...this.config.toggles },
642
+ cli: this.cli,
643
+ link: this.linkStatus,
644
+ linkError: this.linkError,
645
+ lastNotice: this.lastNotice,
646
+ appVersion: this.deps.appVersion,
647
+ platform: this.deps.platform
648
+ };
649
+ }
650
+ /** 主进程内部用(反代加头、握手注入);绝不经 IPC 暴露给渲染进程 */
651
+ getServer() {
652
+ if (!isPaired(this.config)) return null;
653
+ return { baseUrl: this.config.serverUrl, token: this.config.token };
654
+ }
655
+ getServerUrl() {
656
+ return this.getServer()?.baseUrl ?? null;
657
+ }
658
+ /** 实时授权:方法所属命名空间的开关此刻是否打开(未知命名空间一律拒绝) */
659
+ authorize(method) {
660
+ for (const [prefix, toggle] of Object.entries(NAMESPACE_TOGGLE)) {
661
+ if (method.startsWith(prefix)) return this.config.toggles[toggle];
662
+ }
663
+ return false;
664
+ }
665
+ async pair(args) {
666
+ const baseUrl = normalizeServerUrl(args.serverUrl);
667
+ if (isPaired(this.config) && !await this.confirm(`\u8FD9\u53F0\u7535\u8111\u5DF2\u914D\u5BF9\u5230 ${this.config.serverUrl}\u3002\u8981\u6539\u4E3A\u914D\u5BF9\u5230 ${baseUrl} \u5417\uFF1F`)) {
668
+ throw new UserDeclined();
669
+ }
670
+ const name = args.deviceName?.trim() || this.config.deviceName;
671
+ const previous = this.getServer();
672
+ const result = await redeemPairingCode(baseUrl, args.code, name, this.deps.fetchImpl);
673
+ await this.link?.stop();
674
+ this.link = null;
675
+ const oldRevoked = previous ? await this.revokeRemote(previous) : true;
676
+ const sameServer = this.config.serverUrl === baseUrl;
677
+ this.config = this.clearSession({
678
+ ...this.config,
679
+ serverUrl: baseUrl,
680
+ token: result.token,
681
+ deviceId: result.deviceId,
682
+ deviceName: name,
683
+ toggles: sameServer ? this.config.toggles : { ...DEFAULT_TOGGLES }
684
+ });
685
+ const notes = [
686
+ ...sameServer ? [] : ["\u5DF2\u914D\u5BF9\u5230\u65B0\u7684\u670D\u52A1\u5668\uFF0C\u80FD\u529B\u5F00\u5173\u5DF2\u5168\u90E8\u91CD\u7F6E\u4E3A\u5173\u95ED"],
687
+ ...oldRevoked ? [] : [`\u65E7\u51ED\u8BC1\u672A\u80FD\u5728 ${previous.baseUrl} \u4E0A\u540A\u9500\uFF0C\u8BF7\u5230\u5176\u914D\u7F6E\u9875\u300C\u684C\u9762\u7AEF\u300D\u624B\u52A8\u65AD\u5F00`]
688
+ ];
689
+ this.lastNotice = notes.length ? notes.join("\uFF1B") : null;
690
+ this.persist();
691
+ this.startLink();
692
+ this.emit();
693
+ return this.getState();
694
+ }
695
+ /** 请服务端吊销一枚 bearer:有界(超时/网络失败都算未吊销),永不抛。 */
696
+ async revokeRemote(server) {
697
+ const timeoutMs = this.deps.revokeTimeoutMs ?? 5e3;
698
+ const controller = new AbortController();
699
+ let timer = null;
700
+ const timeout = new Promise((resolve3) => {
701
+ timer = setTimeout(() => {
702
+ controller.abort();
703
+ resolve3(null);
704
+ }, timeoutMs);
705
+ });
706
+ try {
707
+ const res = await Promise.race([
708
+ (this.deps.fetchImpl ?? fetch)(`${server.baseUrl}/api/auth/device/self`, {
709
+ method: "DELETE",
710
+ headers: { Authorization: `Bearer ${server.token}` },
711
+ signal: controller.signal
712
+ }),
713
+ timeout
714
+ ]);
715
+ return res !== null && (res.status === 204 || res.status === 401);
716
+ } catch {
717
+ return false;
718
+ } finally {
719
+ if (timer !== null) clearTimeout(timer);
720
+ }
721
+ }
722
+ /** 解除配对:先请服务端吊销这枚 bearer(有界 best-effort),本地凭证无论如何都清掉。 */
723
+ async unpair() {
724
+ const server = this.getServer();
725
+ await this.link?.stop();
726
+ this.link = null;
727
+ this.linkStatus = "disconnected";
728
+ this.linkError = null;
729
+ let revoked = false;
730
+ try {
731
+ revoked = server ? await this.revokeRemote(server) : true;
732
+ } finally {
733
+ this.config = this.clearSession({ ...this.config, serverUrl: null, token: null, deviceId: null });
734
+ this.persist();
735
+ }
736
+ this.lastNotice = revoked ? "\u5DF2\u89E3\u9664\u914D\u5BF9\uFF0C\u670D\u52A1\u7AEF\u4E0A\u7684\u8BBE\u5907\u51ED\u8BC1\u5DF2\u540A\u9500" : "\u5DF2\u5728\u672C\u673A\u89E3\u9664\u914D\u5BF9\uFF0C\u4F46\u670D\u52A1\u7AEF\u672A\u786E\u8BA4\u540A\u9500\u2014\u2014\u8BF7\u5230\u914D\u7F6E\u9875\u300C\u684C\u9762\u7AEF\u300D\u624B\u52A8\u65AD\u5F00\u8BE5\u8BBE\u5907";
737
+ this.emit();
738
+ return this.getState();
739
+ }
740
+ async setToggle(name, enabled) {
741
+ if (enabled && !this.config.toggles[name]) {
742
+ if (!await this.confirm(`\u786E\u8BA4\u5F00\u542F\u300C${TOGGLE_LABELS[name]}\u300D\uFF1F`)) throw new UserDeclined();
743
+ }
744
+ this.config = { ...this.config, toggles: { ...this.config.toggles, [name]: enabled } };
745
+ this.persist();
746
+ if (!enabled) {
747
+ const prefix = Object.entries(NAMESPACE_TOGGLE).find(([, t]) => t === name)?.[0];
748
+ if (prefix) this.link?.abortNamespace(prefix);
749
+ }
750
+ this.link?.sendHello();
751
+ this.emit();
752
+ return this.getState();
753
+ }
754
+ confirm(message) {
755
+ return this.deps.confirm ? this.deps.confirm(message) : Promise.resolve(true);
756
+ }
757
+ async redetectCli() {
758
+ this.cli = await detectClis(this.deps.exec);
759
+ this.link?.sendHello();
760
+ this.emit();
761
+ return this.getState();
762
+ }
763
+ /** 手动重连:本地显示在线也照样断开重连(半开连接时服务端那头早已不认这条连接)。 */
764
+ reconnectNow() {
765
+ this.link?.reconnectNow();
766
+ return this.getState();
767
+ }
768
+ /** 本机 CLI 的可执行路径(探测结果);未安装返回 null。process.* 处理器用它解析 program。 */
769
+ cliPath(program) {
770
+ const det = program === "claude" ? this.cli.claude : this.cli.codex;
771
+ return det.found && det.path ? det.path : null;
772
+ }
773
+ /** 服务端认可的能力声明:开关 ∧ 检测结果。 */
774
+ hello() {
775
+ const { cli, userpc } = this.config.toggles;
776
+ return {
777
+ platform: "desktop",
778
+ client: this.deps.client ?? "desktop",
779
+ os: this.deps.platform,
780
+ arch: this.deps.arch,
781
+ app_version: this.deps.appVersion,
782
+ base_url: this.config.serverUrl ?? "",
783
+ capabilities: {
784
+ claude_code: {
785
+ enabled: cli && this.cli.claude.found,
786
+ // 插入消息:stream-json 输入 + process.write / process.close_stdin
787
+ steer: true,
788
+ // 原生打断:process.write 放行 control_request interrupt(1.0 起);服务端据此才走协作式停止
789
+ interrupt: true,
790
+ ...this.cli.claude.version ? { version: this.cli.claude.version } : {},
791
+ ...this.deps.stageRoot ? { stage_root: this.deps.stageRoot } : {}
792
+ },
793
+ codex: {
794
+ enabled: cli && this.cli.codex.found,
795
+ transport: "app-server-stdio-v1",
796
+ // 插入消息:turn/steer 放行(只收文字)
797
+ steer: true,
798
+ // process.stage_files 接受 asset:从服务端公开路由暂存 persona 参考图(0.98)
799
+ stage_assets: true,
800
+ ...this.cli.codex.version ? { version: this.cli.codex.version } : {},
801
+ ...this.deps.stageRoot ? { stage_root: this.deps.stageRoot } : {}
802
+ },
803
+ // 操作这台电脑(pc.*):服务端按 enabled、version、fs、rg 判断这台电脑能不能被选作
804
+ // 工作空间(leo/plugin/userpc/link.py 的 eligible)
805
+ userpc: this.userpcCapability(userpc)
806
+ }
807
+ };
808
+ }
809
+ /** Leo 文件夹只在开着「允许 Leo 操作这台电脑」时声明:取它会建这个文件夹,没开过这个功能的用户
810
+ * 不该在主目录里多出一个文件夹 */
811
+ userpcCapability(enabled) {
812
+ const defaultRoot = enabled ? this.deps.pcDefaultRoot?.() : null;
813
+ const commands = this.deps.pcCommands?.();
814
+ return {
815
+ // version 5 = 读写 + 命令(pc.exec,没有 sandbox 声明时服务端不提供 pc_bash)+ 目录浏览
816
+ // (pc.fs.browse,三端都在它里面选文件夹)+ 项目说明文件(pc.fs.instructions);服务端要求 ≥ 5。
817
+ // unsandboxed:pc.exec 认 sandbox: "unsandboxed"(服务端的 no-sandbox 越权)
818
+ enabled,
819
+ version: 5,
820
+ fs: true,
821
+ rg: this.deps.rgAvailable?.() ?? false,
822
+ ...defaultRoot ? { default_root: defaultRoot } : {},
823
+ // sandbox:命令跑在沙箱里;shell:没有沙箱(Windows),命令一律在沙箱外跑,老服务端不认它,只是不提供 pc_bash
824
+ ...commands ? { ...commands, unsandboxed: true } : {}
825
+ };
826
+ }
827
+ startLink() {
828
+ const server = this.getServer();
829
+ if (!server) return;
830
+ const url = `${server.baseUrl.replace(/^http/, "ws")}/api/v2/link`;
831
+ this.link = new LinkClient({
832
+ connect: () => this.deps.connectWs(url, server.token),
833
+ hello: () => this.hello(),
834
+ handlers: this.deps.handlers,
835
+ authorize: (method) => this.authorize(method),
836
+ onStatus: (status2, error) => {
837
+ this.linkStatus = status2;
838
+ this.linkError = error;
839
+ this.emit();
840
+ }
841
+ });
842
+ this.link.start();
843
+ }
844
+ clearSession(config) {
845
+ return this.deps.config.clearSession ? this.deps.config.clearSession(config) : config;
846
+ }
847
+ persist() {
848
+ this.deps.config.save(this.config);
849
+ }
850
+ emit() {
851
+ this.deps.onState?.(this.getState());
852
+ }
853
+ };
854
+
855
+ // ../link/src/core/runtime.ts
856
+ import { mkdirSync as mkdirSync3 } from "fs";
857
+ import { realpath as realpath6 } from "fs/promises";
858
+ import { homedir as homedir5 } from "os";
859
+ import { join as join12, sep as sep2 } from "path";
860
+
861
+ // ../link/src/core/codex.ts
862
+ import { execFile as execFile2, spawn as spawn3 } from "child_process";
863
+ import { randomUUID as randomUUID2 } from "crypto";
864
+ import { realpath as realpath2, stat as stat2 } from "fs/promises";
865
+ import { homedir as homedir2, tmpdir as tmpdir2 } from "os";
866
+ import { isAbsolute as isAbsolute2, join as join3, relative as relative2, resolve } from "path";
867
+ import { StringDecoder } from "string_decoder";
868
+
869
+ // ../link/src/core/process.ts
870
+ import { spawn as nodeSpawn } from "child_process";
871
+ import { randomUUID } from "crypto";
872
+ import { tmpdir } from "os";
873
+
874
+ // ../link/src/protocol/cli-env.json
875
+ var cli_env_default = {
876
+ $about: "\u501F\u51FA\u7684 CLI \u5B50\u8FDB\u7A0B\u73AF\u5883\u53D8\u91CF\u767D\u540D\u5355\uFF08fail-closed\uFF1A\u4E0D\u5728\u5355\u91CC\u7684\u4E00\u5F8B\u4E0D\u7EE7\u627F\uFF0CAPI/gateway/\u7B2C\u4E09\u65B9\u4E91\u8DEF\u7531\u53D8\u91CF\u56E0\u6B64\u8FDB\u4E0D\u6765\uFF09\u3002\u684C\u9762\u7AEF process.ts \u76F4\u63A5\u8BFB\u5B83\uFF0Cclaude \u4E0E codex \u5171\u7528\u4E00\u4EFD\u5B50\u8FDB\u7A0B\u73AF\u5883\uFF0C\u6240\u4EE5\u4E09\u7EC4\u90FD\u653E\u884C\uFF1B\u670D\u52A1\u7AEF leo/app/llm/claude_code.py \u7684 _ENV_ALLOWLIST \u53EA\u8DD1 claude\uFF0C\u5FC5\u987B\u7B49\u4E8E base + claude\uFF08test/unit/app/llm/test_cli_env.py \u65AD\u8A00\uFF09\u3002windows \u7EC4\u53EA\u5728 Windows \u684C\u9762\u7AEF\u653E\u884C\uFF08\u6309\u540D\u5B57\u4E0D\u5206\u5927\u5C0F\u5199\u5339\u914D\uFF09\uFF1A\u6CA1\u6709\u5B83\u4EEC node\u3001claude\u3001codex \u90FD\u8D77\u4E0D\u6765\uFF0C\u4E5F\u627E\u4E0D\u5230\u7528\u6237\u76EE\u5F55\u4E0B\u7684\u767B\u5F55\u4E0E\u914D\u7F6E\u3002",
877
+ base: [
878
+ "PATH",
879
+ "HOME",
880
+ "USER",
881
+ "LOGNAME",
882
+ "SHELL",
883
+ "TMPDIR",
884
+ "TERM",
885
+ "TZ",
886
+ "LANG",
887
+ "LC_ALL",
888
+ "LC_CTYPE",
889
+ "HTTP_PROXY",
890
+ "HTTPS_PROXY",
891
+ "ALL_PROXY",
892
+ "NO_PROXY",
893
+ "http_proxy",
894
+ "https_proxy",
895
+ "all_proxy",
896
+ "no_proxy",
897
+ "NODE_EXTRA_CA_CERTS",
898
+ "SSL_CERT_FILE"
899
+ ],
900
+ claude: ["CLAUDE_CONFIG_DIR", "CLAUDE_CODE_OAUTH_TOKEN"],
901
+ codex: ["CODEX_HOME"],
902
+ windows: [
903
+ "SystemRoot",
904
+ "SystemDrive",
905
+ "windir",
906
+ "ComSpec",
907
+ "PATHEXT",
908
+ "TEMP",
909
+ "TMP",
910
+ "USERPROFILE",
911
+ "HOMEDRIVE",
912
+ "HOMEPATH",
913
+ "USERNAME",
914
+ "USERDOMAIN",
915
+ "APPDATA",
916
+ "LOCALAPPDATA",
917
+ "ProgramData",
918
+ "ProgramFiles",
919
+ "ProgramFiles(x86)",
920
+ "ProgramW6432",
921
+ "CommonProgramFiles",
922
+ "CommonProgramFiles(x86)",
923
+ "CommonProgramW6432",
924
+ "NUMBER_OF_PROCESSORS",
925
+ "PROCESSOR_ARCHITECTURE",
926
+ "OS"
927
+ ]
928
+ };
929
+
930
+ // ../link/src/core/fileCache.ts
931
+ import { createWriteStream } from "fs";
932
+ import { mkdir, readdir, readFile, rename, rm, stat, utimes, writeFile } from "fs/promises";
933
+ import { basename, join } from "path";
934
+ import { Readable } from "stream";
935
+ import { pipeline } from "stream/promises";
936
+ var ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
937
+ var UNSAFE_RE = /[\x00-\x1f\x7f/\\:*?"<>|]/g;
938
+ function safeFileName(name) {
939
+ const base = basename(name || "").replace(UNSAFE_RE, "_").trim();
940
+ return base && base !== "." && base !== ".." && base !== "meta.json" ? base.slice(0, 200) : "file";
941
+ }
942
+ function isValidFileId(id) {
943
+ return typeof id === "string" && ID_RE.test(id);
944
+ }
945
+ var FileCache = class {
946
+ root;
947
+ maxBytes;
948
+ constructor(root, maxBytes = 500 * 1024 * 1024) {
949
+ this.root = root;
950
+ this.maxBytes = maxBytes;
951
+ }
952
+ dir(id) {
953
+ return join(this.root, id);
954
+ }
955
+ async get(id) {
956
+ if (!isValidFileId(id)) return null;
957
+ try {
958
+ const meta = JSON.parse(await readFile(join(this.dir(id), "meta.json"), "utf8"));
959
+ const path = join(this.dir(id), safeFileName(meta.name));
960
+ const st = await stat(path);
961
+ if (!st.isFile()) return null;
962
+ const now = /* @__PURE__ */ new Date();
963
+ utimes(path, now, now).catch(() => {
964
+ });
965
+ return { id, path, name: meta.name, mimetype: meta.mimetype, size: st.size };
966
+ } catch {
967
+ return null;
968
+ }
969
+ }
970
+ /** 写入(已存在则覆盖)。source 可为 Buffer 或可读流;写完才 rename 到位,半截文件不会被命中。 */
971
+ async put(id, meta, source) {
972
+ if (!isValidFileId(id)) throw new Error(`invalid file id: ${String(id)}`);
973
+ const dir = this.dir(id);
974
+ await mkdir(dir, { recursive: true });
975
+ const name = safeFileName(meta.name);
976
+ const final = join(dir, name);
977
+ const tmp = join(dir, `.${name}.part`);
978
+ if (Buffer.isBuffer(source)) {
979
+ await writeFile(tmp, source);
980
+ } else {
981
+ const readable = source instanceof Readable ? source : Readable.fromWeb(source);
982
+ await pipeline(readable, createWriteStream(tmp));
983
+ }
984
+ await rename(tmp, final);
985
+ const size = (await stat(final)).size;
986
+ await writeFile(join(dir, "meta.json"), JSON.stringify({ name: meta.name, mimetype: meta.mimetype, size }));
987
+ void this.evict().catch(() => {
988
+ });
989
+ return { id, path: final, name: meta.name, mimetype: meta.mimetype, size };
990
+ }
991
+ /** 按最近访问时间淘汰到上限以内(整目录为单位)。 */
992
+ async evict() {
993
+ let entries = [];
994
+ let dirs;
995
+ try {
996
+ dirs = await readdir(this.root);
997
+ } catch {
998
+ return 0;
999
+ }
1000
+ for (const id of dirs) {
1001
+ if (!isValidFileId(id)) continue;
1002
+ try {
1003
+ const files = await readdir(this.dir(id));
1004
+ let size = 0;
1005
+ let atime = 0;
1006
+ for (const f of files) {
1007
+ const st = await stat(join(this.dir(id), f));
1008
+ size += st.size;
1009
+ if (f !== "meta.json") atime = Math.max(atime, st.mtimeMs);
1010
+ }
1011
+ entries.push({ id, size, atime });
1012
+ } catch {
1013
+ }
1014
+ }
1015
+ let total = entries.reduce((a, e) => a + e.size, 0);
1016
+ entries = entries.sort((a, b) => a.atime - b.atime);
1017
+ let removed = 0;
1018
+ for (const e of entries) {
1019
+ if (total <= this.maxBytes) break;
1020
+ await rm(this.dir(e.id), { recursive: true, force: true });
1021
+ total -= e.size;
1022
+ removed += 1;
1023
+ }
1024
+ return removed;
1025
+ }
1026
+ };
1027
+
1028
+ // ../link/src/core/process.ts
1029
+ var INVALID_PARAMS = -32602;
1030
+ var PROGRAMS = ["claude", "codex"];
1031
+ var ENV_ALLOWLIST = [...cli_env_default.base, ...cli_env_default.claude, ...cli_env_default.codex];
1032
+ var WINDOWS_ENV = new Set([...ENV_ALLOWLIST, ...cli_env_default.windows].map((k) => k.toUpperCase()));
1033
+ var ENV_EXTRA_ALLOWLIST = /* @__PURE__ */ new Set(["LEO_MCP_TOKEN"]);
1034
+ var RUN_ALLOWLIST = {
1035
+ claude: [["--setting-sources", "", "auth", "status", "--json"], ["--version"]],
1036
+ codex: [["--version"], ["login", "status"]]
1037
+ };
1038
+ var BUILTIN_TOOLS_ALLOWED = /* @__PURE__ */ new Set(["Read", "ToolSearch"]);
1039
+ var PUBLIC_ASSET_RE = /^\/assets\/persona-[A-Za-z0-9._-]+$/;
1040
+ function assetStageKey(path) {
1041
+ return `asset_${path.slice("/assets/".length).replace(/[^A-Za-z0-9_-]/g, "_")}`.slice(0, 128);
1042
+ }
1043
+ function buildChildEnv(base, extra, platform = process.platform) {
1044
+ const env = {};
1045
+ const withPath = loginPathEnv(platform, base);
1046
+ if (platform === "win32") {
1047
+ for (const [k, v] of Object.entries(withPath)) if (v !== void 0 && WINDOWS_ENV.has(k.toUpperCase())) env[k] = v;
1048
+ } else {
1049
+ for (const k of ENV_ALLOWLIST) if (withPath[k] !== void 0) env[k] = withPath[k];
1050
+ }
1051
+ env.DISABLE_AUTOUPDATER = "1";
1052
+ env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC = "1";
1053
+ env.CLAUDE_CODE_DISABLE_AUTO_MEMORY = "1";
1054
+ env.CLAUDE_CODE_DISABLE_CLAUDE_MDS = "1";
1055
+ for (const [k, v] of Object.entries(extra ?? {})) {
1056
+ if (!ENV_EXTRA_ALLOWLIST.has(k)) throw new RpcFailure(INVALID_PARAMS, `env_extra.${k} is not allowed`);
1057
+ if (typeof v !== "string") throw new RpcFailure(INVALID_PARAMS, `env_extra.${k} must be a string`);
1058
+ env[k] = v;
1059
+ }
1060
+ return env;
1061
+ }
1062
+ function argValue(args, flag) {
1063
+ const i = args.indexOf(flag);
1064
+ return i >= 0 ? args[i + 1] : void 0;
1065
+ }
1066
+ function validateClaudeArgs(args) {
1067
+ const bad = (m) => new RpcFailure(INVALID_PARAMS, `claude args rejected: ${m}`);
1068
+ if (!args.includes("-p") && !args.includes("--print")) throw bad("must be a print (-p) turn");
1069
+ if (args.includes("--dangerously-skip-permissions")) throw bad("--dangerously-skip-permissions is forbidden");
1070
+ if (argValue(args, "--permission-mode") !== "dontAsk") throw bad("--permission-mode must be dontAsk");
1071
+ if (argValue(args, "--setting-sources") !== "") throw bad('--setting-sources must be ""');
1072
+ const tools = argValue(args, "--tools");
1073
+ if (tools === void 0) throw bad("--tools whitelist is required");
1074
+ for (const t of tools.split(",").map((s) => s.trim()).filter(Boolean)) {
1075
+ if (!BUILTIN_TOOLS_ALLOWED.has(t)) throw bad(`built-in tool ${t} is not allowed`);
1076
+ }
1077
+ const allowed = argValue(args, "--allowedTools");
1078
+ if (allowed !== void 0) {
1079
+ const i = args.indexOf("--allowedTools");
1080
+ for (let j = i + 1; j < args.length && !args[j].startsWith("--"); j++) {
1081
+ const v = args[j];
1082
+ if (!(v === "mcp__leo" || v.startsWith("Read("))) throw bad(`allowedTools entry ${v} is not allowed`);
1083
+ }
1084
+ }
1085
+ for (const flag of ["--mcp-config", "--mcp-server", "--add-dir"]) {
1086
+ if (flag !== "--mcp-config" && args.includes(flag)) throw bad(`${flag} is forbidden`);
1087
+ }
1088
+ if (args.includes("--input-format") && argValue(args, "--input-format") !== "stream-json") {
1089
+ throw bad("--input-format must be stream-json");
1090
+ }
1091
+ }
1092
+ function isInterrupt(msg) {
1093
+ const request = msg.request;
1094
+ return msg.type === "control_request" && typeof msg.request_id === "string" && Object.keys(msg).length === 3 && typeof request === "object" && request !== null && Object.keys(request).length === 1 && request.subtype === "interrupt";
1095
+ }
1096
+ function validateStdinLine(line) {
1097
+ const bad = (m) => new RpcFailure(INVALID_PARAMS, `stdin line rejected: ${m}`);
1098
+ if (typeof line !== "string" || line.includes("\n")) throw bad("must be a single line");
1099
+ let msg;
1100
+ try {
1101
+ msg = JSON.parse(line);
1102
+ } catch {
1103
+ throw bad("must be JSON");
1104
+ }
1105
+ if (msg && typeof msg === "object" && isInterrupt(msg)) return line;
1106
+ if (msg?.type !== "user" || msg.message?.role !== "user" || typeof msg.message.content !== "string") {
1107
+ throw bad("must be a user text message or an interrupt");
1108
+ }
1109
+ return line;
1110
+ }
1111
+ function validateSpawnParams(params) {
1112
+ const program = params.program;
1113
+ if (typeof program !== "string" || !PROGRAMS.includes(program)) {
1114
+ throw new RpcFailure(INVALID_PARAMS, `program must be one of ${PROGRAMS.join(", ")}`);
1115
+ }
1116
+ if (program === "codex") throw new RpcFailure(INVALID_PARAMS, "Codex requires process.codex_open");
1117
+ const args = params.args;
1118
+ if (!Array.isArray(args) || !args.every((a) => typeof a === "string")) throw new RpcFailure(INVALID_PARAMS, "args must be a string array");
1119
+ const stdin = params.stdin ?? "";
1120
+ if (typeof stdin !== "string") throw new RpcFailure(INVALID_PARAMS, "stdin must be a string");
1121
+ if (program === "claude") validateClaudeArgs(args);
1122
+ const keepStdinOpen = params.keep_stdin_open === true;
1123
+ if (keepStdinOpen && argValue(args, "--input-format") !== "stream-json") {
1124
+ throw new RpcFailure(INVALID_PARAMS, "keep_stdin_open requires --input-format stream-json");
1125
+ }
1126
+ return { program, args, stdin, keepStdinOpen };
1127
+ }
1128
+ function lineSplitter(onLine, maxLineBytes) {
1129
+ let buf = "";
1130
+ return {
1131
+ push(chunk) {
1132
+ buf += chunk.toString("utf8");
1133
+ let idx;
1134
+ while ((idx = buf.indexOf("\n")) >= 0) {
1135
+ const line = buf.slice(0, idx).replace(/\r$/, "");
1136
+ buf = buf.slice(idx + 1);
1137
+ onLine(line.length > maxLineBytes ? line.slice(0, maxLineBytes) : line);
1138
+ }
1139
+ if (buf.length > maxLineBytes * 2) {
1140
+ buf = buf.slice(-maxLineBytes);
1141
+ }
1142
+ },
1143
+ flush() {
1144
+ if (buf) onLine(buf.length > maxLineBytes ? buf.slice(0, maxLineBytes) : buf);
1145
+ buf = "";
1146
+ }
1147
+ };
1148
+ }
1149
+ function createProcessHandlers(deps) {
1150
+ const spawnImpl = deps.spawnImpl ?? nodeSpawn;
1151
+ const grace = deps.killGraceMs ?? 3e3;
1152
+ const maxLine = deps.maxLineBytes ?? 4 * 1024 * 1024;
1153
+ const resolve3 = (program, args, env) => {
1154
+ const path = deps.resolveProgram(program);
1155
+ if (!path) throw new RpcFailure(INVALID_PARAMS, `${program} is not installed on this computer`);
1156
+ const launch = launchOf(path, args, { pathEnv: env.PATH });
1157
+ if (!launch) throw new RpcFailure(INVALID_PARAMS, `${program} at ${path} cannot be launched without a shell`);
1158
+ return launch;
1159
+ };
1160
+ const terminate = (child) => {
1161
+ if (child.exitCode !== null || child.signalCode !== null) return;
1162
+ killTree(child, "SIGTERM");
1163
+ const t = setTimeout(() => killTree(child, "SIGKILL"), grace);
1164
+ child.once("exit", () => clearTimeout(t));
1165
+ };
1166
+ const openStdin = /* @__PURE__ */ new Map();
1167
+ const spawnHandler = async (params, ctx) => {
1168
+ const { program, args, stdin, keepStdinOpen } = validateSpawnParams(params);
1169
+ const env = buildChildEnv(deps.env ?? process.env, params.env_extra);
1170
+ const launch = resolve3(program, args, env);
1171
+ if (ctx.signal.aborted) throw new RpcFailure(-32002, "Request cancelled");
1172
+ return await new Promise((resolvePromise, reject) => {
1173
+ let child;
1174
+ try {
1175
+ child = spawnImpl(launch.file, launch.args, { env, cwd: deps.cwd ?? tmpdir(), stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
1176
+ } catch (e) {
1177
+ reject(new RpcFailure(-32603, `spawn failed: ${e instanceof Error ? e.message : String(e)}`));
1178
+ return;
1179
+ }
1180
+ const stderrTail = [];
1181
+ let stderrBytes = 0;
1182
+ const out = lineSplitter((line) => ctx.notify("process.stdout", { line }), maxLine);
1183
+ const err = lineSplitter((line) => {
1184
+ ctx.notify("process.stderr", { line });
1185
+ stderrTail.push(line);
1186
+ stderrBytes += line.length;
1187
+ while (stderrBytes > 8192 && stderrTail.length > 1) stderrBytes -= stderrTail.shift().length;
1188
+ }, maxLine);
1189
+ child.stdout?.on("data", (c) => out.push(c));
1190
+ child.stderr?.on("data", (c) => err.push(c));
1191
+ child.on("error", (e) => reject(new RpcFailure(-32603, `spawn failed: ${e.message}`)));
1192
+ child.on("close", (code, signal) => {
1193
+ out.flush();
1194
+ err.flush();
1195
+ resolvePromise({ exit_code: code ?? (signal ? 128 : -1), signal: signal ?? null, stderr_tail: stderrTail.join("\n") });
1196
+ });
1197
+ ctx.signal.addEventListener("abort", () => terminate(child));
1198
+ child.stdin?.on("error", () => {
1199
+ });
1200
+ if (keepStdinOpen) {
1201
+ child.stdin?.write(stdin);
1202
+ const processId = randomUUID();
1203
+ openStdin.set(processId, child);
1204
+ child.on("close", () => openStdin.delete(processId));
1205
+ ctx.notify("process.stdin_ready", { process_id: processId });
1206
+ } else {
1207
+ child.stdin?.end(stdin);
1208
+ }
1209
+ });
1210
+ };
1211
+ const runHandler = async (params, ctx) => {
1212
+ const program = params.program;
1213
+ if (typeof program !== "string" || !PROGRAMS.includes(program)) {
1214
+ throw new RpcFailure(INVALID_PARAMS, `program must be one of ${PROGRAMS.join(", ")}`);
1215
+ }
1216
+ const args = Array.isArray(params.args) ? params.args : [];
1217
+ const allowed = RUN_ALLOWLIST[program].some((a) => a.length === args.length && a.every((x, i) => x === args[i]));
1218
+ if (!allowed) throw new RpcFailure(INVALID_PARAMS, `process.run only allows read-only probes, got: ${args.join(" ")}`);
1219
+ const timeoutMs = typeof params.timeout_ms === "number" ? Math.min(Math.max(params.timeout_ms, 1e3), 12e4) : 3e4;
1220
+ const env = buildChildEnv(deps.env ?? process.env, void 0);
1221
+ const launch = resolve3(program, args, env);
1222
+ return await new Promise((resolvePromise, reject) => {
1223
+ const child = spawnImpl(launch.file, launch.args, { env, cwd: deps.cwd ?? tmpdir(), stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
1224
+ const outChunks = [];
1225
+ const errChunks = [];
1226
+ let timedOut = false;
1227
+ const timer = setTimeout(() => {
1228
+ timedOut = true;
1229
+ terminate(child);
1230
+ }, timeoutMs);
1231
+ child.stdout?.on("data", (c) => outChunks.push(c));
1232
+ child.stderr?.on("data", (c) => errChunks.push(c));
1233
+ child.on("error", (e) => {
1234
+ clearTimeout(timer);
1235
+ reject(new RpcFailure(-32603, `spawn failed: ${e.message}`));
1236
+ });
1237
+ child.on("close", (code) => {
1238
+ clearTimeout(timer);
1239
+ if (timedOut) {
1240
+ reject(new RpcFailure(-32603, `${program} ${args.join(" ")} timed out after ${timeoutMs}ms`));
1241
+ return;
1242
+ }
1243
+ resolvePromise({
1244
+ exit_code: code ?? -1,
1245
+ stdout: Buffer.concat(outChunks).toString("utf8").slice(0, 64 * 1024),
1246
+ stderr: Buffer.concat(errChunks).toString("utf8").slice(0, 16 * 1024)
1247
+ });
1248
+ });
1249
+ ctx.signal.addEventListener("abort", () => terminate(child));
1250
+ });
1251
+ };
1252
+ const stageAsset = async (cache, asset) => {
1253
+ const key = assetStageKey(asset);
1254
+ const hit = await cache.get(key);
1255
+ if (hit) return hit.path;
1256
+ if (!deps.fetchAsset) return null;
1257
+ try {
1258
+ const res = await deps.fetchAsset(asset);
1259
+ if (!res.ok || !res.body) return null;
1260
+ const name = asset.slice(asset.lastIndexOf("/") + 1);
1261
+ const mimetype = res.headers.get("content-type") ?? "application/octet-stream";
1262
+ return (await cache.put(key, { name, mimetype, size: 0 }, res.body)).path;
1263
+ } catch {
1264
+ return null;
1265
+ }
1266
+ };
1267
+ const stageHandler = async (params) => {
1268
+ const cache = deps.cache;
1269
+ if (!cache) throw new RpcFailure(-32601, "file staging is not available on this desktop");
1270
+ const files = Array.isArray(params.files) ? params.files : null;
1271
+ if (!files) throw new RpcFailure(INVALID_PARAMS, "files must be an array");
1272
+ const paths = {};
1273
+ for (const raw of files) {
1274
+ const f = raw ?? {};
1275
+ if (!isValidFileId(f.id)) continue;
1276
+ if (f.asset !== void 0) {
1277
+ if (typeof f.asset !== "string" || !PUBLIC_ASSET_RE.test(f.asset)) continue;
1278
+ const path = await stageAsset(cache, f.asset);
1279
+ if (path) paths[f.id] = path;
1280
+ continue;
1281
+ }
1282
+ const hit = await cache.get(f.id);
1283
+ if (hit) {
1284
+ paths[f.id] = hit.path;
1285
+ continue;
1286
+ }
1287
+ if (!deps.fetchFile) continue;
1288
+ try {
1289
+ const res = await deps.fetchFile(f.id);
1290
+ if (!res.ok || !res.body) continue;
1291
+ const name = typeof f.name === "string" && f.name ? f.name : f.id;
1292
+ const mimetype = typeof f.mimetype === "string" && f.mimetype ? f.mimetype : res.headers.get("content-type") ?? "application/octet-stream";
1293
+ const put = await cache.put(f.id, { name, mimetype, size: 0 }, res.body);
1294
+ paths[f.id] = put.path;
1295
+ } catch {
1296
+ }
1297
+ }
1298
+ return { root: cache.root, paths };
1299
+ };
1300
+ const openChild = (params) => {
1301
+ const child = typeof params.process_id === "string" ? openStdin.get(params.process_id) : void 0;
1302
+ if (!child) throw new RpcFailure(INVALID_PARAMS, "process closed or unknown");
1303
+ return child;
1304
+ };
1305
+ const writeHandler = async (params) => {
1306
+ const child = openChild(params);
1307
+ const line = validateStdinLine(params.line);
1308
+ await new Promise((resolve4, reject) => child.stdin.write(`${line}
1309
+ `, (err) => err ? reject(err) : resolve4()));
1310
+ return {};
1311
+ };
1312
+ const closeStdinHandler = async (params) => {
1313
+ const child = openChild(params);
1314
+ openStdin.delete(params.process_id);
1315
+ child.stdin?.end();
1316
+ return {};
1317
+ };
1318
+ return {
1319
+ "process.spawn": spawnHandler,
1320
+ "process.run": runHandler,
1321
+ "process.stage_files": stageHandler,
1322
+ "process.write": writeHandler,
1323
+ "process.close_stdin": closeStdinHandler
1324
+ };
1325
+ }
1326
+
1327
+ // ../link/src/core/codexImages.ts
1328
+ import { realpath, rm as rm2 } from "fs/promises";
1329
+ import { extname as extname2, isAbsolute, join as join2, relative } from "path";
1330
+
1331
+ // ../link/src/core/pc/upload.ts
1332
+ import { basename as basename2 } from "path";
1333
+
1334
+ // ../link/src/core/pc/fs.ts
1335
+ import { constants } from "fs";
1336
+ import { lstat, open, stat as fsStat } from "fs/promises";
1337
+ import { extname } from "path";
1338
+
1339
+ // ../link/src/core/pc/errors.ts
1340
+ var PATH_SENSITIVE = -32010;
1341
+ var PATH_OUTSIDE = -32011;
1342
+ var NOT_FOUND = -32012;
1343
+ var NOT_A_TEXT_FILE = -32013;
1344
+ var TOO_LARGE = -32014;
1345
+ var STALE_VERSION = -32015;
1346
+ var EXISTS = -32016;
1347
+ var EDIT_NOT_FOUND = -32017;
1348
+ var EDIT_AMBIGUOUS = -32018;
1349
+ var PATH_PROTECTED = -32019;
1350
+ var OPEN_EXECUTABLE = -32020;
1351
+ function invalid(message) {
1352
+ return new RpcFailure(INVALID_PARAMS, message);
1353
+ }
1354
+
1355
+ // ../link/src/core/pc/fs.ts
1356
+ var MIME_BY_EXT = {
1357
+ ".png": "image/png",
1358
+ ".jpg": "image/jpeg",
1359
+ ".jpeg": "image/jpeg",
1360
+ ".gif": "image/gif",
1361
+ ".webp": "image/webp",
1362
+ ".svg": "image/svg+xml",
1363
+ ".heic": "image/heic",
1364
+ ".ico": "image/x-icon",
1365
+ ".bmp": "image/bmp",
1366
+ ".tif": "image/tiff",
1367
+ ".tiff": "image/tiff",
1368
+ ".pdf": "application/pdf",
1369
+ ".epub": "application/epub+zip",
1370
+ ".zip": "application/zip",
1371
+ ".gz": "application/gzip",
1372
+ ".tar": "application/x-tar",
1373
+ ".dmg": "application/x-apple-diskimage",
1374
+ ".txt": "text/plain",
1375
+ ".md": "text/markdown",
1376
+ ".markdown": "text/markdown",
1377
+ ".csv": "text/csv",
1378
+ ".tsv": "text/tab-separated-values",
1379
+ ".html": "text/html",
1380
+ ".htm": "text/html",
1381
+ ".css": "text/css",
1382
+ ".xml": "application/xml",
1383
+ ".json": "application/json",
1384
+ ".yaml": "application/yaml",
1385
+ ".yml": "application/yaml",
1386
+ ".toml": "application/toml",
1387
+ ".js": "text/javascript",
1388
+ ".mjs": "text/javascript",
1389
+ ".cjs": "text/javascript",
1390
+ ".ts": "text/x-typescript",
1391
+ ".tsx": "text/x-typescript",
1392
+ ".py": "text/x-python",
1393
+ ".sh": "application/x-sh",
1394
+ ".go": "text/x-go",
1395
+ ".rs": "text/x-rust",
1396
+ ".java": "text/x-java",
1397
+ ".c": "text/x-c",
1398
+ ".h": "text/x-c",
1399
+ ".cpp": "text/x-c++",
1400
+ ".swift": "text/x-swift",
1401
+ ".rb": "text/x-ruby",
1402
+ ".sql": "application/sql",
1403
+ ".mp3": "audio/mpeg",
1404
+ ".wav": "audio/wav",
1405
+ ".mp4": "video/mp4",
1406
+ ".mov": "video/quicktime",
1407
+ ".doc": "application/msword",
1408
+ ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
1409
+ ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
1410
+ ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation"
1411
+ };
1412
+ function mimeByExt(path) {
1413
+ return MIME_BY_EXT[extname(path).toLowerCase()];
1414
+ }
1415
+ function sniff(head) {
1416
+ const at = (sig, offset = 0) => sig.every((b, i) => head[offset + i] === b);
1417
+ if (at([137, 80, 78, 71, 13, 10, 26, 10])) return { mimetype: "image/png", image: true };
1418
+ if (at([255, 216, 255])) return { mimetype: "image/jpeg", image: true };
1419
+ if (at([71, 73, 70, 56]) && (head[4] === 55 || head[4] === 57) && head[5] === 97) return { mimetype: "image/gif", image: true };
1420
+ if (at([82, 73, 70, 70]) && at([87, 69, 66, 80], 8)) return { mimetype: "image/webp", image: true };
1421
+ if (at([37, 80, 68, 70, 45])) return { mimetype: "application/pdf", image: false };
1422
+ if (at([80, 75, 3, 4])) return { mimetype: "application/zip", image: false };
1423
+ if (at([31, 139])) return { mimetype: "application/gzip", image: false };
1424
+ return null;
1425
+ }
1426
+ async function statInfo(path) {
1427
+ const st = await fsStat(path);
1428
+ const kind = st.isFile() ? "file" : st.isDirectory() ? "dir" : "other";
1429
+ const mimetype = kind === "file" ? mimeByExt(path) : void 0;
1430
+ return { kind, size: st.size, mtime_ms: Math.floor(st.mtimeMs), ...mimetype ? { mimetype } : {} };
1431
+ }
1432
+ async function openNoFollow(path) {
1433
+ const handle = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
1434
+ const [opened, named] = await Promise.all([handle.stat({ bigint: true }), lstat(path, { bigint: true }).catch(() => null)]);
1435
+ if (!named || named.isSymbolicLink() || named.dev !== opened.dev || named.ino !== opened.ino) {
1436
+ await handle.close();
1437
+ throw Object.assign(new Error(`ELOOP: ${path} is a link or changed while opening`), { code: "ELOOP" });
1438
+ }
1439
+ return handle;
1440
+ }
1441
+ async function openRegularFile(path) {
1442
+ const pre = await fsStat(path);
1443
+ if (pre.isDirectory()) throw invalid("\u662F\u76EE\u5F55\uFF0C\u8BF7\u7528 pc_glob \u5217\u51FA\u5176\u4E2D\u7684\u6587\u4EF6");
1444
+ if (!pre.isFile()) throw invalid("\u4E0D\u662F\u666E\u901A\u6587\u4EF6\uFF08\u8BBE\u5907\u3001FIFO\u3001socket \u7B49\u4E0D\u53EF\u8BFB\u53D6\uFF09");
1445
+ let handle;
1446
+ try {
1447
+ handle = await openNoFollow(path);
1448
+ } catch (e) {
1449
+ if (e.code === "ELOOP") throw invalid("\u8DEF\u5F84\u662F\u7B26\u53F7\u94FE\u63A5");
1450
+ throw e;
1451
+ }
1452
+ const st = await handle.stat();
1453
+ if (!st.isFile()) {
1454
+ await handle.close();
1455
+ throw invalid("\u4E0D\u662F\u666E\u901A\u6587\u4EF6\uFF08\u8BBE\u5907\u3001FIFO\u3001socket \u7B49\u4E0D\u53EF\u8BFB\u53D6\uFF09");
1456
+ }
1457
+ return { handle, size: st.size };
1458
+ }
1459
+ var SNIFF_BYTES = 8192;
1460
+ var CHUNK = 64 * 1024;
1461
+ function decodeLine(buf, maxChars, lineNo) {
1462
+ let text = buf.toString("utf8");
1463
+ if (lineNo === 1 && text.charCodeAt(0) === 65279) text = text.slice(1);
1464
+ if (text.endsWith("\r")) text = text.slice(0, -1);
1465
+ if (text.length <= maxChars) return { text, truncated: false };
1466
+ let cut = text.slice(0, maxChars);
1467
+ const last = cut.charCodeAt(cut.length - 1);
1468
+ if (last >= 55296 && last <= 56319) cut = cut.slice(0, -1);
1469
+ return { text: cut, truncated: true };
1470
+ }
1471
+ function clipBytes(text, maxBytes) {
1472
+ if (Buffer.byteLength(text) <= maxBytes) return text;
1473
+ let out = Buffer.from(text).subarray(0, maxBytes).toString("utf8");
1474
+ if (out.endsWith("\uFFFD")) out = out.slice(0, -1);
1475
+ return out;
1476
+ }
1477
+ async function readFile2(path, opts) {
1478
+ const { handle, size } = await openRegularFile(path);
1479
+ try {
1480
+ const head = Buffer.alloc(Math.min(SNIFF_BYTES, size));
1481
+ const { bytesRead } = head.length ? await handle.read(head, 0, head.length, 0) : { bytesRead: 0 };
1482
+ const sniffed = sniff(head.subarray(0, bytesRead));
1483
+ if (sniffed?.image) return { kind: "image", mimetype: sniffed.mimetype, size };
1484
+ if (sniffed || head.subarray(0, bytesRead).includes(0)) {
1485
+ const mimetype = sniffed?.mimetype ?? mimeByExt(path) ?? "application/octet-stream";
1486
+ throw new RpcFailure(NOT_A_TEXT_FILE, `\u4E0D\u662F\u6587\u672C\u6587\u4EF6\uFF08${mimetype}\uFF09`, { mimetype });
1487
+ }
1488
+ return await readLines(handle, opts);
1489
+ } finally {
1490
+ await handle.close();
1491
+ }
1492
+ }
1493
+ async function readLines(handle, opts) {
1494
+ const keepBytes = opts.maxLineChars * 4 + 4;
1495
+ const lines = [];
1496
+ const truncated = [];
1497
+ let bytes = 0;
1498
+ let lineNo = 0;
1499
+ let parts = [];
1500
+ let partLen = 0;
1501
+ let lineOverflow = false;
1502
+ let started = false;
1503
+ const finishLine = () => {
1504
+ lineNo++;
1505
+ const raw = Buffer.concat(parts, partLen);
1506
+ parts = [];
1507
+ partLen = 0;
1508
+ started = false;
1509
+ const overflow = lineOverflow;
1510
+ lineOverflow = false;
1511
+ if (lineNo < opts.offset) return true;
1512
+ if (lines.length >= opts.limit) return false;
1513
+ let { text, truncated: cut } = decodeLine(raw, opts.maxLineChars, lineNo);
1514
+ cut ||= overflow;
1515
+ const cost = Buffer.byteLength(text) + 1;
1516
+ if (bytes + cost > opts.maxBytes) {
1517
+ if (lines.length) return false;
1518
+ text = clipBytes(text, opts.maxBytes - 1);
1519
+ cut = true;
1520
+ }
1521
+ lines.push(text);
1522
+ if (cut) truncated.push(lineNo);
1523
+ bytes += Buffer.byteLength(text) + 1;
1524
+ return true;
1525
+ };
1526
+ const buf = Buffer.alloc(CHUNK);
1527
+ let position = 0;
1528
+ let hasMore = false;
1529
+ read: for (; ; ) {
1530
+ const { bytesRead } = await handle.read(buf, 0, CHUNK, position);
1531
+ if (!bytesRead) break;
1532
+ position += bytesRead;
1533
+ const chunk = buf.subarray(0, bytesRead);
1534
+ let start2 = 0;
1535
+ while (start2 < chunk.length) {
1536
+ const nl = chunk.indexOf(10, start2);
1537
+ const end = nl === -1 ? chunk.length : nl;
1538
+ if (end > start2) {
1539
+ started = true;
1540
+ if (lineNo + 1 >= opts.offset && !lineOverflow) {
1541
+ const take = Math.min(end - start2, keepBytes - partLen);
1542
+ if (take > 0) {
1543
+ parts.push(Buffer.from(chunk.subarray(start2, start2 + take)));
1544
+ partLen += take;
1545
+ }
1546
+ if (take < end - start2) lineOverflow = true;
1547
+ }
1548
+ }
1549
+ if (nl === -1) break;
1550
+ if (!finishLine()) {
1551
+ hasMore = true;
1552
+ break read;
1553
+ }
1554
+ start2 = nl + 1;
1555
+ }
1556
+ }
1557
+ if (!hasMore && started && !finishLine()) hasMore = true;
1558
+ return {
1559
+ kind: "text",
1560
+ lines,
1561
+ start_line: opts.offset,
1562
+ has_more: hasMore,
1563
+ ...hasMore ? {} : { total_lines: lineNo },
1564
+ truncated_lines: truncated
1565
+ };
1566
+ }
1567
+
1568
+ // ../link/src/core/pc/upload.ts
1569
+ var MAX_UPLOAD_BYTES = 20 * 1024 * 1024;
1570
+ var UploadTooLarge = class extends Error {
1571
+ size;
1572
+ limit;
1573
+ constructor(size, limit) {
1574
+ super(`\u6587\u4EF6\u8D85\u8FC7 ${Math.round(limit / 1024 / 1024)} MB \u4E0A\u9650`);
1575
+ this.size = size;
1576
+ this.limit = limit;
1577
+ }
1578
+ };
1579
+ var UploadHttpError = class extends Error {
1580
+ status;
1581
+ constructor(status2) {
1582
+ super(`Upload failed (HTTP ${status2})`);
1583
+ this.status = status2;
1584
+ }
1585
+ };
1586
+ async function uploadLocalFile(opts) {
1587
+ opts.signal.throwIfAborted();
1588
+ const handle = await openNoFollow(opts.path);
1589
+ let data;
1590
+ try {
1591
+ const info = await handle.stat();
1592
+ if (!info.isFile()) throw new Error("Not a regular file");
1593
+ if (info.size > MAX_UPLOAD_BYTES) throw new UploadTooLarge(info.size, MAX_UPLOAD_BYTES);
1594
+ if (info.size === 0 && opts.allowEmpty === false) throw new Error("File is empty");
1595
+ data = await handle.readFile();
1596
+ if (data.length > MAX_UPLOAD_BYTES) throw new UploadTooLarge(data.length, MAX_UPLOAD_BYTES);
1597
+ if (!data.length && opts.allowEmpty === false) throw new Error("File is empty");
1598
+ } finally {
1599
+ await handle.close();
1600
+ }
1601
+ opts.signal.throwIfAborted();
1602
+ const declared = opts.mimetype ?? "application/octet-stream";
1603
+ const body = new FormData();
1604
+ body.append("file", new Blob([data], { type: declared }), basename2(opts.path));
1605
+ const response = await (opts.fetchImpl ?? fetch)(`${opts.server.baseUrl.replace(/\/$/, "")}/api/v2/chat/upload`, {
1606
+ method: "POST",
1607
+ headers: { Authorization: `Bearer ${opts.server.token}` },
1608
+ body,
1609
+ signal: AbortSignal.any([opts.signal, AbortSignal.timeout(12e4)]),
1610
+ redirect: "error"
1611
+ });
1612
+ if (response.status !== 201) throw new UploadHttpError(response.status);
1613
+ const file = await response.json();
1614
+ if (!isValidFileId(file.id) || typeof file.name !== "string" || typeof file.mimetype !== "string") throw new Error("Invalid upload response");
1615
+ if (opts.expectMimetype !== void 0 && file.mimetype !== opts.expectMimetype) throw new Error("Invalid upload response");
1616
+ opts.signal.throwIfAborted();
1617
+ const uploaded = { id: file.id, name: file.name, mimetype: file.mimetype, size: data.length };
1618
+ await opts.cache?.put(uploaded.id, { name: uploaded.name, mimetype: uploaded.mimetype, size: uploaded.size }, data).catch(() => {
1619
+ });
1620
+ return uploaded;
1621
+ }
1622
+
1623
+ // ../link/src/core/codexImages.ts
1624
+ var IMAGE_TYPES = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp", ".gif": "image/gif" };
1625
+ var CodexImageJob = class {
1626
+ paths = /* @__PURE__ */ new Map();
1627
+ threads = /* @__PURE__ */ new Set();
1628
+ uploaded = /* @__PURE__ */ new Map();
1629
+ collecting;
1630
+ cache;
1631
+ server;
1632
+ fetchImpl;
1633
+ generatedRoot;
1634
+ constructor(codexHome, cache, server, fetchImpl = fetch) {
1635
+ this.generatedRoot = join2(codexHome, "generated_images");
1636
+ this.cache = cache;
1637
+ this.server = { ...server };
1638
+ this.fetchImpl = fetchImpl;
1639
+ }
1640
+ startedThread(id) {
1641
+ if (/^[A-Za-z0-9_-]{1,128}$/.test(id)) this.threads.add(id);
1642
+ }
1643
+ record(path, threadId) {
1644
+ this.paths.set(path, threadId && this.threads.has(threadId) ? threadId : void 0);
1645
+ }
1646
+ async threadDirectory(threadId) {
1647
+ const root = await realpath(this.generatedRoot);
1648
+ const dir = await realpath(join2(root, threadId));
1649
+ if (relative(root, dir) !== threadId) throw new Error("Codex image thread directory escaped its output root");
1650
+ return dir;
1651
+ }
1652
+ async collect(signal) {
1653
+ signal.throwIfAborted();
1654
+ this.collecting ??= this.upload(signal).finally(() => {
1655
+ this.collecting = void 0;
1656
+ });
1657
+ return this.collecting;
1658
+ }
1659
+ async upload(signal) {
1660
+ if (!this.paths.size) throw new Error("Codex did not produce an image");
1661
+ for (const [path, threadId] of this.paths) {
1662
+ signal.throwIfAborted();
1663
+ if (this.uploaded.has(path)) continue;
1664
+ const canonical = await realpath(path);
1665
+ if (!threadId) throw new Error("Generated image is not from this Codex thread");
1666
+ const rel = relative(await this.threadDirectory(threadId), canonical);
1667
+ if (!rel || rel.startsWith("..") || isAbsolute(rel)) throw new Error("Generated image is outside this Codex thread");
1668
+ const mimetype = IMAGE_TYPES[extname2(canonical).toLowerCase()];
1669
+ if (!mimetype) throw new Error("Codex output is not a supported image");
1670
+ const file = await uploadLocalFile({
1671
+ path: canonical,
1672
+ server: this.server,
1673
+ signal,
1674
+ fetchImpl: this.fetchImpl,
1675
+ cache: this.cache,
1676
+ mimetype,
1677
+ expectMimetype: mimetype,
1678
+ allowEmpty: false
1679
+ });
1680
+ this.uploaded.set(path, { id: file.id, name: file.name, mimetype });
1681
+ }
1682
+ return [...this.uploaded.values()];
1683
+ }
1684
+ async close() {
1685
+ await this.collecting?.catch(() => {
1686
+ });
1687
+ for (const thread of this.threads) {
1688
+ try {
1689
+ await rm2(await this.threadDirectory(thread), { recursive: true, force: true });
1690
+ } catch {
1691
+ }
1692
+ }
1693
+ }
1694
+ };
1695
+
1696
+ // ../link/src/protocol/codex-isolation.json
1697
+ var codex_isolation_default = {
1698
+ $about: "codex \u5185\u7F6E\u5DE5\u5177\u5173\u95ED\u6E05\u5355\uFF08Issue #113\uFF09\u3002\u684C\u9762\u7AEF codex.ts \u76F4\u63A5\u8BFB\u5B83\u62FC argv\uFF1B\u670D\u52A1\u7AEF leo/app/llm/codex.py \u7684 DISABLED_FEATURES \u5FC5\u987B\u4E0E\u5B83\u4E00\u81F4\uFF08test/unit/app/llm/test_codex_isolation.py \u65AD\u8A00\uFF09\u3002\u952E\u540D\u6309 `codex features list` \u6838\u5BF9\uFF080.162.1\uFF09\uFF1B\u6539\u540D\u6216\u5E9F\u5F03\u65F6 codex \u53EA\u53D1\u4E00\u6761 configWarning\uFF0CLeo \u628A\u5B83\u5F53\u4F5C\u672C\u8F6E\u5931\u8D25\u3002\u51FA\u56FE\u4EFB\u52A1\u4FDD\u7559 image_generation\uFF0C\u5176\u4F59\u7167\u5173\u3002",
1699
+ disabled_features: [
1700
+ "shell_tool",
1701
+ "unified_exec",
1702
+ "apps",
1703
+ "plugins",
1704
+ "browser_use",
1705
+ "computer_use",
1706
+ "view_image",
1707
+ "image_generation",
1708
+ "tool_suggest"
1709
+ ],
1710
+ image_feature: "image_generation"
1711
+ };
1712
+
1713
+ // ../link/src/core/codex.ts
1714
+ function isolationOverrides(image) {
1715
+ return [
1716
+ ...codex_isolation_default.disabled_features.filter((f) => !(image && f === codex_isolation_default.image_feature)).map((f) => `features.${f}=false`),
1717
+ 'web_search="disabled"'
1718
+ ];
1719
+ }
1720
+ var MCP_NAME = /^[A-Za-z0-9_-]+$/;
1721
+ function listMcpServers(path, env, cwd) {
1722
+ const launch = launchOf(path, ["--disable", "plugins", "mcp", "list", "--json"], { pathEnv: env.PATH });
1723
+ if (!launch) return Promise.reject(new Error(`${path} cannot be launched without a shell`));
1724
+ return new Promise((resolve3, reject) => {
1725
+ execFile2(launch.file, launch.args, { cwd, env, timeout: 3e4, maxBuffer: 4 * 1024 * 1024, windowsHide: true }, (error, stdout) => {
1726
+ if (error) return reject(error);
1727
+ try {
1728
+ const servers = JSON.parse(stdout);
1729
+ resolve3(servers.map((s) => String(s.name)));
1730
+ } catch (e) {
1731
+ reject(e);
1732
+ }
1733
+ });
1734
+ });
1735
+ }
1736
+ var FIELDS = {
1737
+ initialize: ["clientInfo", "capabilities"],
1738
+ initialized: [],
1739
+ "model/list": ["cursor", "limit", "includeHidden"],
1740
+ "thread/start": ["model", "cwd", "sandbox", "approvalPolicy", "approvalsReviewer", "developerInstructions", "ephemeral"],
1741
+ "thread/resume": ["threadId", "model", "cwd", "sandbox", "approvalPolicy", "approvalsReviewer", "developerInstructions"],
1742
+ "turn/start": ["threadId", "input", "effort", "outputSchema"],
1743
+ "turn/interrupt": ["threadId", "turnId"],
1744
+ // 生成中插入的消息:只收文字(见下方 input 校验)
1745
+ "turn/steer": ["threadId", "expectedTurnId", "input", "clientUserMessageId"]
1746
+ };
1747
+ function object(value) {
1748
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new RpcFailure(INVALID_PARAMS, "expected object");
1749
+ return value;
1750
+ }
1751
+ function createCodexHandlers(deps) {
1752
+ const running = /* @__PURE__ */ new Map();
1753
+ const cwd = deps.cwd ?? tmpdir2();
1754
+ let mcpCache;
1755
+ async function inheritedMcpServers(path, home) {
1756
+ const info = await stat2(join3(home, "config.toml")).catch(() => null);
1757
+ const key = `${path}:${info ? `${info.mtimeMs}:${info.size}` : "none"}`;
1758
+ if (mcpCache?.key !== key) {
1759
+ const names = await (deps.listMcpServers ?? listMcpServers)(path, buildChildEnv(deps.env ?? process.env, {}), cwd).catch((e) => {
1760
+ throw new RpcFailure(INVALID_PARAMS, `Cannot list Codex MCP servers: ${e.message}`);
1761
+ });
1762
+ const bad = names.find((n) => !MCP_NAME.test(n));
1763
+ if (bad !== void 0) throw new RpcFailure(INVALID_PARAMS, `Cannot disable Codex MCP server ${JSON.stringify(bad)}`);
1764
+ mcpCache = { key, names };
1765
+ }
1766
+ return mcpCache.names;
1767
+ }
1768
+ const open5 = async (params, ctx) => {
1769
+ if (Object.keys(params).some((k) => k !== "ticket" && k !== "image_generation")) throw new RpcFailure(INVALID_PARAMS, "only ticket and image_generation are accepted");
1770
+ if (params.image_generation !== void 0 && typeof params.image_generation !== "boolean") throw new RpcFailure(INVALID_PARAMS, "image_generation must be boolean");
1771
+ const path = deps.resolveProgram("codex");
1772
+ if (!path) throw new RpcFailure(INVALID_PARAMS, "Codex is not installed on this computer");
1773
+ const ticket = params.ticket ?? "";
1774
+ if (typeof ticket !== "string") throw new RpcFailure(INVALID_PARAMS, "ticket must be a string");
1775
+ if (ctx.signal.aborted) throw new RpcFailure(REQUEST_CANCELLED, "Request cancelled");
1776
+ const env = deps.env ?? process.env;
1777
+ const home = env.CODEX_HOME ? resolve(cwd, env.CODEX_HOME) : join3(process.platform === "win32" ? homedir2() : env.HOME ?? homedir2(), ".codex");
1778
+ const inherited = await inheritedMcpServers(path, home);
1779
+ if (ctx.signal.aborted) throw new RpcFailure(REQUEST_CANCELLED, "Request cancelled");
1780
+ let image;
1781
+ if (params.image_generation) {
1782
+ const server = deps.getServer?.();
1783
+ if (!deps.cache || !server) throw new RpcFailure(INVALID_PARAMS, "Image generation needs a paired server and file cache");
1784
+ if (ticket) throw new RpcFailure(INVALID_PARAMS, "Image generation does not use MCP tickets");
1785
+ image = new CodexImageJob(home, deps.cache, server, deps.fetchImpl);
1786
+ }
1787
+ try {
1788
+ const overrides = [
1789
+ 'approval_policy="never"',
1790
+ 'sandbox_mode="read-only"',
1791
+ ...isolationOverrides(!!image),
1792
+ // Only this turn's Leo endpoint; every inherited server is switched off.
1793
+ ...inherited.filter((n) => !(ticket && n === "leo")).map((n) => `mcp_servers.${n}.enabled=false`),
1794
+ ...ticket ? [
1795
+ `mcp_servers.leo.url=${JSON.stringify(deps.getMcpUrl())}`,
1796
+ 'mcp_servers.leo.bearer_token_env_var="LEO_MCP_TOKEN"',
1797
+ 'mcp_servers.leo.default_tools_approval_mode="approve"',
1798
+ // Hard limit; codex ignores MCP progress heartbeats, and artifact_task can run for many minutes.
1799
+ "mcp_servers.leo.tool_timeout_sec=3600"
1800
+ ] : []
1801
+ ];
1802
+ const args = [...overrides.flatMap((v) => ["--config", v]), "app-server", "--listen", "stdio://"];
1803
+ const childEnv = buildChildEnv(deps.env ?? process.env, { LEO_MCP_TOKEN: ticket });
1804
+ const launch = launchOf(path, args, { pathEnv: childEnv.PATH });
1805
+ if (!launch) throw new RpcFailure(INVALID_PARAMS, `Codex at ${path} cannot be launched without a shell`);
1806
+ const child = (deps.spawnImpl ?? spawn3)(launch.file, launch.args, { cwd, env: childEnv, stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
1807
+ const processId = randomUUID2();
1808
+ const lifetime = new AbortController();
1809
+ running.set(processId, { child, signal: AbortSignal.any([ctx.signal, lifetime.signal]), image });
1810
+ return await new Promise((resolve3, reject) => {
1811
+ let timer;
1812
+ let failure;
1813
+ const stop2 = () => {
1814
+ lifetime.abort();
1815
+ running.delete(processId);
1816
+ if (child.exitCode !== null || child.signalCode !== null) return;
1817
+ killTree(child, "SIGTERM");
1818
+ timer ??= setTimeout(() => killTree(child, "SIGKILL"), deps.killGraceMs ?? 3e3);
1819
+ };
1820
+ const decoder = new StringDecoder("utf8");
1821
+ let buffer = "";
1822
+ child.stdout?.on("data", (chunk) => {
1823
+ buffer += decoder.write(chunk);
1824
+ let newline;
1825
+ while ((newline = buffer.indexOf("\n")) >= 0) {
1826
+ const line = buffer.slice(0, newline);
1827
+ buffer = buffer.slice(newline + 1);
1828
+ if (Buffer.byteLength(line) > (deps.maxLineBytes ?? 16 * 1024 * 1024)) {
1829
+ failure = new Error("Codex output exceeded limit");
1830
+ stop2();
1831
+ return;
1832
+ }
1833
+ try {
1834
+ const frame = JSON.parse(line);
1835
+ if (image && frame.method === "thread/started" && typeof frame.params?.thread?.id === "string") image.startedThread(frame.params.thread.id);
1836
+ const item = frame.params?.item;
1837
+ if (image && frame.method === "item/completed" && item?.type === "imageGeneration" && typeof item.savedPath === "string") image.record(item.savedPath, frame.params?.threadId);
1838
+ if (frame.id !== void 0 && typeof frame.method === "string") {
1839
+ const response = frame.method === "item/commandExecution/requestApproval" || frame.method === "item/fileChange/requestApproval" ? { id: frame.id, result: { decision: "decline" } } : { id: frame.id, error: { code: -32601, message: "Interactive requests are disabled for Leo lending" } };
1840
+ child.stdin?.write(`${JSON.stringify(response)}
1841
+ `);
1842
+ continue;
1843
+ }
1844
+ } catch {
1845
+ failure = new Error("Invalid Codex JSON output");
1846
+ stop2();
1847
+ return;
1848
+ }
1849
+ ctx.notify("process.stdout", { line });
1850
+ }
1851
+ if (Buffer.byteLength(buffer) > (deps.maxLineBytes ?? 16 * 1024 * 1024)) {
1852
+ failure = new Error("Codex output exceeded limit");
1853
+ stop2();
1854
+ }
1855
+ });
1856
+ child.stderr?.resume();
1857
+ child.stdin?.on("error", () => stop2());
1858
+ child.once("spawn", () => ctx.notify("process.codex_ready", { process_id: processId, ...image ? { cwd } : {} }));
1859
+ child.once("error", (error) => {
1860
+ failure = error;
1861
+ });
1862
+ child.once("close", (code, signal) => {
1863
+ lifetime.abort();
1864
+ clearTimeout(timer);
1865
+ running.delete(processId);
1866
+ ctx.signal.removeEventListener("abort", stop2);
1867
+ if (failure) reject(failure);
1868
+ else resolve3({ exit_code: code ?? -1, signal });
1869
+ });
1870
+ ctx.signal.addEventListener("abort", stop2, { once: true });
1871
+ if (ctx.signal.aborted) stop2();
1872
+ });
1873
+ } finally {
1874
+ await image?.close();
1875
+ }
1876
+ };
1877
+ const write = async (params, ctx) => {
1878
+ const proc = typeof params.process_id === "string" ? running.get(params.process_id) : void 0;
1879
+ if (!proc || proc.signal.aborted || ctx.signal.aborted) throw new RpcFailure(INVALID_PARAMS, "Codex process closed or unknown");
1880
+ const message = object(params.message);
1881
+ const method = message.method;
1882
+ if (typeof method !== "string" || !Object.hasOwn(FIELDS, method)) throw new RpcFailure(INVALID_PARAMS, "Codex method is not allowed");
1883
+ const p = message.params == null ? {} : { ...object(message.params) };
1884
+ if (Object.keys(p).some((k) => !FIELDS[method].includes(k))) throw new RpcFailure(INVALID_PARAMS, "Codex params are not allowed");
1885
+ if (method === "thread/start" || method === "thread/resume") {
1886
+ const sandbox = "read-only";
1887
+ if (proc.image && method === "thread/resume") throw new RpcFailure(INVALID_PARAMS, "Image generation requires a new thread");
1888
+ if (p.sandbox !== void 0 && p.sandbox !== sandbox) throw new RpcFailure(INVALID_PARAMS, `Codex sandbox must be ${sandbox}`);
1889
+ if (p.approvalPolicy !== void 0 && p.approvalPolicy !== "never") throw new RpcFailure(INVALID_PARAMS, "Codex approvalPolicy must be never");
1890
+ p.cwd = cwd;
1891
+ p.sandbox = sandbox;
1892
+ p.approvalPolicy = "never";
1893
+ if (proc.image) p.ephemeral = true;
1894
+ }
1895
+ if (method === "turn/steer") {
1896
+ if (!Array.isArray(p.input) || !p.input.every((raw) => object(raw).type === "text")) {
1897
+ throw new RpcFailure(INVALID_PARAMS, "turn/steer accepts text input only");
1898
+ }
1899
+ }
1900
+ if (method === "turn/start") {
1901
+ if (!Array.isArray(p.input)) throw new RpcFailure(INVALID_PARAMS, "Codex input must be an array");
1902
+ for (const raw of p.input) {
1903
+ const input = object(raw);
1904
+ if (input.type === "text") continue;
1905
+ if (input.type !== "localImage" || typeof input.path !== "string" || !deps.cache) throw new RpcFailure(INVALID_PARAMS, "only text and staged images are allowed");
1906
+ const [root, path] = await Promise.all([realpath2(deps.cache.root), realpath2(input.path)]);
1907
+ const rel = relative2(root, path);
1908
+ if (!rel || rel.startsWith("..") || isAbsolute2(rel)) throw new RpcFailure(INVALID_PARAMS, "image is outside the desktop cache");
1909
+ }
1910
+ }
1911
+ if (proc.signal.aborted || ctx.signal.aborted) throw new RpcFailure(REQUEST_CANCELLED, "Request cancelled");
1912
+ const frame = { ...message.id !== void 0 ? { id: message.id } : {}, method, params: p };
1913
+ await new Promise((resolve3, reject) => proc.child.stdin.write(`${JSON.stringify(frame)}
1914
+ `, (err) => err ? reject(err) : resolve3()));
1915
+ return {};
1916
+ };
1917
+ const collect = async (params, ctx) => {
1918
+ const proc = typeof params.process_id === "string" ? running.get(params.process_id) : void 0;
1919
+ if (!proc?.image || proc.signal.aborted) throw new RpcFailure(INVALID_PARAMS, "Image process closed or unknown");
1920
+ if (Object.keys(params).some((k) => k !== "process_id")) throw new RpcFailure(INVALID_PARAMS, "only process_id is accepted");
1921
+ return { files: await proc.image.collect(AbortSignal.any([proc.signal, ctx.signal])) };
1922
+ };
1923
+ return { "process.codex_open": open5, "process.codex_write": write, "process.codex_collect": collect };
1924
+ }
1925
+
1926
+ // ../link/src/core/pc/index.ts
1927
+ import "child_process";
1928
+ import { stat as stat7 } from "fs/promises";
1929
+ import { homedir as homedir4 } from "os";
1930
+ import { basename as basename5, dirname as dirname5, join as join10, posix as posix3, win32 as win325 } from "path";
1931
+
1932
+ // ../link/src/core/pc/boundary.ts
1933
+ import { realpath as realpath3, stat as stat3 } from "fs/promises";
1934
+ import { homedir as homedir3 } from "os";
1935
+ import { basename as basename3, dirname as dirname2, join as join5, posix as posix2, relative as relative3, resolve as resolve2, win32 as win324 } from "path";
1936
+
1937
+ // ../link/src/core/pc/rules.ts
1938
+ import { isAbsolute as isAbsolute3, join as join4, posix, sep, win32 as win323 } from "path";
1939
+ var SENSITIVE_HOME_PATHS = [
1940
+ // 桌面端托管的系统内容(以后放借出 CLI 的会话等,见 #117)
1941
+ ".leo",
1942
+ "Library/Keychains",
1943
+ ".ssh",
1944
+ ".gnupg",
1945
+ ".aws/credentials",
1946
+ ".aws/config",
1947
+ ".docker/config.json",
1948
+ ".netrc",
1949
+ ".git-credentials",
1950
+ ".npmrc",
1951
+ ".pypirc",
1952
+ // 各类 CLI 存登录凭据的位置(gh / hub、cargo、gem、kubectl、gcloud、az、terraform、vault、psql、mysql、op)。
1953
+ // 读不到时这些 CLI 在沙箱里用不了,这正是要的:发布、改远端资源都是对外的动作
1954
+ ".config/gh/hosts.yml",
1955
+ ".config/hub",
1956
+ ".cargo/credentials.toml",
1957
+ ".cargo/credentials",
1958
+ ".gem/credentials",
1959
+ ".kube/config",
1960
+ ".config/gcloud",
1961
+ ".azure",
1962
+ ".terraform.d/credentials.tfrc.json",
1963
+ ".vault-token",
1964
+ ".pgpass",
1965
+ ".my.cnf",
1966
+ ".config/op",
1967
+ // agent CLI 的登录凭据(Codex 的 ChatGPT 登录、Claude Code 在没有钥匙串时的文件、Gemini 的 OAuth)。
1968
+ // 改过配置目录的另见 envCredentialPaths
1969
+ ".codex/auth.json",
1970
+ ".claude/.credentials.json",
1971
+ ".gemini/oauth_creds.json",
1972
+ "Library/Application Support/Google/Chrome",
1973
+ "Library/Application Support/Microsoft Edge",
1974
+ "Library/Application Support/BraveSoftware",
1975
+ "Library/Application Support/Arc",
1976
+ "Library/Application Support/Firefox",
1977
+ "Library/Safari",
1978
+ "Library/Cookies",
1979
+ "Library/Messages",
1980
+ "Library/Mail",
1981
+ "Library/Application Support/1Password",
1982
+ "Library/Group Containers/2BUA8C4S2C.com.1password",
1983
+ "Library/Application Support/Bitwarden"
1984
+ ];
1985
+ var SENSITIVE_HOME_PATHS_WIN32 = [
1986
+ ...SENSITIVE_HOME_PATHS.filter((rel) => !rel.startsWith("Library/")),
1987
+ // 凭据管理器与 DPAPI 主密钥、证书(钥匙串的对应物)
1988
+ "AppData/Roaming/Microsoft/Credentials",
1989
+ "AppData/Local/Microsoft/Credentials",
1990
+ "AppData/Roaming/Microsoft/Protect",
1991
+ "AppData/Roaming/Microsoft/Crypto",
1992
+ "AppData/Roaming/Microsoft/SystemCertificates",
1993
+ "AppData/Roaming/Microsoft/Vault",
1994
+ "AppData/Local/Microsoft/Vault",
1995
+ // 浏览器与密码管理器的数据
1996
+ "AppData/Local/Google/Chrome/User Data",
1997
+ "AppData/Local/Microsoft/Edge/User Data",
1998
+ "AppData/Local/BraveSoftware",
1999
+ "AppData/Roaming/Mozilla/Firefox",
2000
+ "AppData/Local/1Password",
2001
+ "AppData/Roaming/Bitwarden",
2002
+ "AppData/Local/Microsoft/Outlook",
2003
+ // CLI 在 Windows 上存登录凭据的位置(gh、gcloud、psql)
2004
+ "AppData/Roaming/GitHub CLI",
2005
+ "AppData/Roaming/gcloud",
2006
+ "AppData/Roaming/postgresql",
2007
+ // 用户注册表
2008
+ "NTUSER.DAT"
2009
+ ];
2010
+ function sensitiveHomePaths(platform = process.platform) {
2011
+ return platform === "win32" ? SENSITIVE_HOME_PATHS_WIN32 : SENSITIVE_HOME_PATHS;
2012
+ }
2013
+ function envCredentialPaths(env) {
2014
+ const out = [];
2015
+ if (env.CODEX_HOME && isAbsolute3(env.CODEX_HOME)) out.push(join4(env.CODEX_HOME, "auth.json"));
2016
+ if (env.CLAUDE_CONFIG_DIR && isAbsolute3(env.CLAUDE_CONFIG_DIR)) out.push(join4(env.CLAUDE_CONFIG_DIR, ".credentials.json"));
2017
+ return out;
2018
+ }
2019
+ var SHELL_DIRS_DARWIN = ["leo-desktop", "leo-desktop-dev", "leo-link", "leo-link-dev"];
2020
+ var SHELL_DIRS_WIN32 = ["leo-desktop", "leo-desktop-dev"];
2021
+ function otherShellDataDirs(own, home, platform = process.platform, env = process.env) {
2022
+ const dirs = platform === "darwin" ? SHELL_DIRS_DARWIN.map((name) => posix.join(home, "Library", "Application Support", name)) : platform === "win32" ? SHELL_DIRS_WIN32.map((name) => win323.join(env.APPDATA ?? win323.join(home, "AppData", "Roaming"), name)) : [];
2023
+ const same = (a, b) => platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;
2024
+ return dirs.filter((dir) => !same(dir, own));
2025
+ }
2026
+ var SSH_READABLE_NAMES = ["known_hosts", "known_hosts.old", "config"];
2027
+ function sshReadable(rel) {
2028
+ return rel !== "" && !rel.includes(sep) && (rel.endsWith(".pub") || SSH_READABLE_NAMES.includes(rel));
2029
+ }
2030
+ var SANDBOX_SENSITIVE_HOME = [".docker/run", ".colima", ".orbstack", ".rd"];
2031
+ var SANDBOX_SENSITIVE_ABS = ["/var/run/docker.sock"];
2032
+ var PROTECTED_NAMES = [
2033
+ ".gitmodules",
2034
+ ".gitconfig",
2035
+ ".bashrc",
2036
+ ".bash_profile",
2037
+ ".zshrc",
2038
+ ".zprofile",
2039
+ ".zshenv",
2040
+ ".zlogin",
2041
+ ".profile",
2042
+ ".ripgreprc",
2043
+ ".mcp.json",
2044
+ ".envrc",
2045
+ // Claude Code 的用户配置(含 MCP 服务器,写进去等于下次启动时执行命令;CC 自己的 DANGEROUS_FILES 也有它)
2046
+ ".claude.json"
2047
+ ];
2048
+ var PROTECTED_NAMES_WIN32 = [
2049
+ ...PROTECTED_NAMES,
2050
+ "microsoft.powershell_profile.ps1",
2051
+ "microsoft.vscode_profile.ps1",
2052
+ "profile.ps1"
2053
+ ];
2054
+ var PROTECTED_DIRS = [".vscode", ".idea", ".aws", ".claude", ".codex", ".agents", ".gemini"];
2055
+ var PROTECTED_HOME_DIRS = ["Library/LaunchAgents"];
2056
+ var PROTECTED_HOME_DIRS_WIN32 = [
2057
+ "AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup",
2058
+ "Documents/WindowsPowerShell",
2059
+ "Documents/PowerShell"
2060
+ ];
2061
+ function protectedRules(platform = process.platform) {
2062
+ return platform === "win32" ? { names: PROTECTED_NAMES_WIN32, homeDirs: PROTECTED_HOME_DIRS_WIN32 } : { names: PROTECTED_NAMES, homeDirs: PROTECTED_HOME_DIRS };
2063
+ }
2064
+ var GIT_PROTECTED_SUFFIXES = [
2065
+ "/(modules/.+/)?hooks(/.*)?",
2066
+ "/(modules/.+/)?config",
2067
+ "/(.*/)?(commondir|gitdir|config\\.worktree)"
2068
+ ];
2069
+ var ESCALATED_RELEASED_NAMES = [".gitmodules", ".mcp.json"];
2070
+ var ESCALATED_RELEASED_DIRS = [".vscode", ".idea", ".claude", ".codex", ".agents", ".gemini"];
2071
+ var WRITABLE_HOME_CACHES = [
2072
+ ".npm",
2073
+ ".cache",
2074
+ ".node-gyp",
2075
+ ".pnpm-store",
2076
+ ".yarn/cache",
2077
+ "Library/Caches",
2078
+ ".cargo/registry",
2079
+ ".cargo/git",
2080
+ "go/pkg/mod",
2081
+ ".gradle/caches",
2082
+ ".m2/repository"
2083
+ ];
2084
+ var EXEC_DENY = ["/usr/bin/open", "/usr/bin/osascript", "/bin/launchctl"];
2085
+ var SECRET_ENV_WORDS = ["KEY", "PASSWORD", "SECRET", "TOKEN"];
2086
+ var SECRET_ENV_NAME = new RegExp(SECRET_ENV_WORDS.join("|"), "i");
2087
+ var OPEN_EXECUTABLE_EXTS = /* @__PURE__ */ new Set([
2088
+ ".app",
2089
+ ".command",
2090
+ ".tool",
2091
+ ".sh",
2092
+ ".terminal",
2093
+ ".workflow",
2094
+ ".pkg",
2095
+ ".mpkg",
2096
+ ".scpt",
2097
+ ".scptd",
2098
+ ".applescript",
2099
+ ".jar",
2100
+ ".webloc",
2101
+ ".inetloc",
2102
+ ".fileloc",
2103
+ ".prefpane",
2104
+ ".kext",
2105
+ ".bundle",
2106
+ ".plugin"
2107
+ ]);
2108
+ var OPEN_EXECUTABLE_EXTS_WIN32 = /* @__PURE__ */ new Set([
2109
+ ".exe",
2110
+ ".com",
2111
+ ".bat",
2112
+ ".cmd",
2113
+ ".ps1",
2114
+ ".psm1",
2115
+ ".psd1",
2116
+ ".vbs",
2117
+ ".vbe",
2118
+ ".js",
2119
+ ".jse",
2120
+ ".wsf",
2121
+ ".wsh",
2122
+ ".hta",
2123
+ ".msi",
2124
+ ".msp",
2125
+ ".mst",
2126
+ ".msix",
2127
+ ".msixbundle",
2128
+ ".appx",
2129
+ ".appxbundle",
2130
+ ".appinstaller",
2131
+ ".scr",
2132
+ ".pif",
2133
+ ".cpl",
2134
+ ".lnk",
2135
+ ".url",
2136
+ ".reg",
2137
+ ".inf",
2138
+ ".scf",
2139
+ ".chm",
2140
+ ".msc",
2141
+ ".application",
2142
+ ".appref-ms",
2143
+ ".gadget",
2144
+ ".settingcontent-ms",
2145
+ ".library-ms",
2146
+ ".search-ms",
2147
+ ".searchconnector-ms",
2148
+ ".diagcab",
2149
+ ".jar",
2150
+ ".jnlp",
2151
+ ".ws",
2152
+ ".xbap",
2153
+ ".vb",
2154
+ ".sys",
2155
+ ".dll",
2156
+ ".ocx",
2157
+ // 装了 Git for Windows 时双击即用 Git Bash 运行
2158
+ ".sh",
2159
+ ".bash"
2160
+ ]);
2161
+ function openExecutableExts(platform = process.platform, pathExt = "") {
2162
+ if (platform !== "win32") return OPEN_EXECUTABLE_EXTS;
2163
+ const fromEnv = pathExt.split(";").map((e) => e.trim().toLowerCase()).filter((e) => /^\.[a-z0-9-]+$/.test(e));
2164
+ return /* @__PURE__ */ new Set([...OPEN_EXECUTABLE_EXTS_WIN32, ...fromEnv]);
2165
+ }
2166
+
2167
+ // ../link/src/core/pc/boundary.ts
2168
+ var nodeBoundaryFs = { realpath: realpath3, stat: stat3 };
2169
+ var idOf = (s) => `${s.dev}:${s.ino}`;
2170
+ var pathOf = (platform) => platform === "win32" ? win324 : posix2;
2171
+ function within(p, base, platform = process.platform) {
2172
+ const fold = platform === "win32" ? (s) => s.toLowerCase() : (s) => s;
2173
+ const [fp, fb] = [fold(p), fold(base)];
2174
+ if (fp === fb) return "";
2175
+ const { sep: sep3 } = pathOf(platform);
2176
+ const prefix = fb.endsWith(sep3) ? fb : fb + sep3;
2177
+ if (!fp.startsWith(prefix)) return null;
2178
+ const depth = prefix.slice(0, -1).split(sep3).length;
2179
+ return p.split(sep3).slice(depth).join(sep3);
2180
+ }
2181
+ var WIN_RESERVED = /^(con|prn|aux|nul|conin\$|conout\$|com[0-9\u00b9\u00b2\u00b3]|lpt[0-9\u00b9\u00b2\u00b3])(\..*)?$/i;
2182
+ function windowsPathProblem(raw) {
2183
+ if (/^[\\/]{2}[?.][\\/]/.test(raw)) return "\u4E0D\u652F\u6301\u8BBE\u5907\u8DEF\u5F84\uFF08\\\\?\\\u3001\\\\.\\\uFF09";
2184
+ if (/^[A-Za-z]:(?![\\/])/.test(raw)) return "\u76D8\u7B26\u540E\u9762\u8981\u8DDF \\\uFF1A\u8BF7\u7ED9\u51FA\u5B8C\u6574\u7684\u7EDD\u5BF9\u8DEF\u5F84\uFF08\u5982 C:\\Users\\\u2026\uFF09";
2185
+ if (/^[\\/](?![\\/])/.test(raw)) return "\u8BF7\u7ED9\u51FA\u5E26\u76D8\u7B26\u7684\u7EDD\u5BF9\u8DEF\u5F84\uFF08\u5982 C:\\Users\\\u2026\uFF09";
2186
+ if (raw.replace(/^[A-Za-z]:/, "").includes(":")) return "\u8DEF\u5F84\u91CC\u4E0D\u80FD\u6709\u5192\u53F7\uFF08\u5907\u7528\u6570\u636E\u6D41\uFF09";
2187
+ if (/[<>"|?*\x00-\x1f]/.test(raw)) return "\u8DEF\u5F84\u91CC\u6709 Windows \u4E0D\u5141\u8BB8\u7684\u5B57\u7B26";
2188
+ for (const seg of raw.split(/[\\/]/)) {
2189
+ if (seg === "" || seg === "." || seg === ".." || seg === "~") continue;
2190
+ if (/[. ]$/.test(seg)) return `\u8DEF\u5F84\u7684\u4E00\u6BB5\u4E0D\u80FD\u4EE5\u70B9\u6216\u7A7A\u683C\u7ED3\u5C3E\uFF1A${seg}`;
2191
+ if (WIN_RESERVED.test(seg)) return `${seg} \u662F Windows \u7684\u8BBE\u5907\u540D\uFF0C\u4E0D\u662F\u6587\u4EF6`;
2192
+ }
2193
+ return null;
2194
+ }
2195
+ var extraPath = (e) => typeof e === "string" ? e : e.path;
2196
+ function isRootPath(p, platform = process.platform) {
2197
+ if (platform !== "win32") return p.startsWith("/");
2198
+ return /^([A-Za-z]:[\\/]|[\\/]{2}[^\\/])/.test(p) && windowsPathProblem(p) === null;
2199
+ }
2200
+ async function loadSensitive(home, extra, fs = nodeBoundaryFs) {
2201
+ const canonicalHome = await fs.realpath(home).catch(() => resolve2(home));
2202
+ const items = [
2203
+ ...sensitiveHomePaths().map((rel) => ({ path: join5(canonicalHome, rel), allow: rel === ".ssh" ? sshReadable : void 0 })),
2204
+ ...extra.map((e) => ({ path: resolve2(extraPath(e)), allow: typeof e === "string" ? void 0 : e.allow }))
2205
+ ];
2206
+ return Promise.all(
2207
+ items.map(async ({ path, allow }) => {
2208
+ try {
2209
+ const canonical = await fs.realpath(path);
2210
+ return { path: canonical, id: idOf(await fs.stat(canonical, { bigint: true })), allow };
2211
+ } catch {
2212
+ return { path, allow };
2213
+ }
2214
+ })
2215
+ );
2216
+ }
2217
+ function containsSensitive(target, sensitive) {
2218
+ return sensitive.some((s) => within(s.path, target) !== null);
2219
+ }
2220
+ function primaryRoot(roots) {
2221
+ return roots[0];
2222
+ }
2223
+ function resolveInput(raw, roots, home = homedir3(), platform = process.platform) {
2224
+ if (typeof raw !== "string" || raw === "") throw invalid("path must be a non-empty string");
2225
+ if (raw.includes("\0")) throw invalid("path must not contain NUL");
2226
+ const P = pathOf(platform);
2227
+ if (platform === "win32") {
2228
+ const problem = windowsPathProblem(raw);
2229
+ if (problem) throw invalid(problem);
2230
+ }
2231
+ if (raw === "~") return P.resolve(home);
2232
+ if (raw.startsWith("~/") || platform === "win32" && raw.startsWith("~\\")) return P.resolve(home, raw.slice(2));
2233
+ if (P.isAbsolute(raw)) return P.resolve(raw);
2234
+ const base = primaryRoot(roots);
2235
+ if (!base) throw invalid("\u76F8\u5BF9\u8DEF\u5F84\u9700\u8981\u5DE5\u4F5C\u7A7A\u95F4\uFF1A\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u5DE5\u4F5C\u7A7A\u95F4\uFF0C\u8BF7\u7ED9\u51FA\u7EDD\u5BF9\u8DEF\u5F84");
2236
+ return P.resolve(baseOfRoot(base, platform), raw);
2237
+ }
2238
+ function baseOfRoot(root, platform = process.platform) {
2239
+ return root.kind === "file" ? pathOf(platform).dirname(root.path) : root.path;
2240
+ }
2241
+ async function canonicalize(path, fs = nodeBoundaryFs) {
2242
+ try {
2243
+ return await fs.realpath(path);
2244
+ } catch (e) {
2245
+ const code = e.code;
2246
+ if (code === "ENOENT" || code === "ENOTDIR" || code === "ELOOP") throw new RpcFailure(NOT_FOUND, `\u8DEF\u5F84\u4E0D\u5B58\u5728\uFF1A${path}`);
2247
+ throw e;
2248
+ }
2249
+ }
2250
+ async function classify(p, roots, sensitive, fs = nodeBoundaryFs) {
2251
+ for (const s of sensitive) {
2252
+ const rel = within(p, s.path);
2253
+ if (rel !== null && !s.allow?.(rel)) return "sensitive";
2254
+ }
2255
+ const ancestors = [];
2256
+ for (let cur = p; ; cur = dirname2(cur)) {
2257
+ const st = await fs.stat(cur, { bigint: true }).catch(() => null);
2258
+ if (st) ancestors.push({ path: cur, id: idOf(st) });
2259
+ if (dirname2(cur) === cur) break;
2260
+ }
2261
+ for (const s of sensitive) {
2262
+ if (!s.id) continue;
2263
+ const hit = ancestors.find((a) => a.id === s.id);
2264
+ if (hit && !s.allow?.(relative3(hit.path, p))) return "sensitive";
2265
+ }
2266
+ for (const root of roots) {
2267
+ if (root.kind === "file" ? p === root.path : within(p, root.path) !== null) return "inside";
2268
+ }
2269
+ for (const root of roots) {
2270
+ const st = await fs.stat(root.path, { bigint: true }).catch(() => null);
2271
+ if (!st) continue;
2272
+ const id = idOf(st);
2273
+ if (root.kind === "file" ? ancestors[0]?.path === p && ancestors[0].id === id : ancestors.some((a) => a.id === id)) return "inside";
2274
+ }
2275
+ return "outside";
2276
+ }
2277
+ var GIT_PROTECTED_RE = new RegExp(`/\\.git(${GIT_PROTECTED_SUFFIXES.join("|")})?$`);
2278
+ function isProtected(p, home, platform = process.platform) {
2279
+ const { names, homeDirs } = protectedRules(platform);
2280
+ const lower = (platform === "win32" ? p.replaceAll("\\", "/") : p).toLowerCase();
2281
+ const parts = lower.split("/").filter(Boolean);
2282
+ if (parts.some((name) => PROTECTED_DIRS.includes(name))) return true;
2283
+ if (parts.length && names.includes(parts[parts.length - 1])) return true;
2284
+ if (GIT_PROTECTED_RE.test(lower)) return true;
2285
+ const P = pathOf(platform);
2286
+ return homeDirs.some((rel) => within(p.toLowerCase(), P.join(home, rel).toLowerCase(), platform) !== null);
2287
+ }
2288
+ async function classifyWrite(p, roots, sensitive, home, fs = nodeBoundaryFs) {
2289
+ const cls = await classify(p, roots, sensitive, fs);
2290
+ if (cls === "sensitive") return cls;
2291
+ return isProtected(p, home) ? "protected" : cls;
2292
+ }
2293
+ async function resolveForCreate(path, fs = nodeBoundaryFs) {
2294
+ const rest = [];
2295
+ for (let cur = path; ; cur = dirname2(cur)) {
2296
+ try {
2297
+ return join5(await fs.realpath(cur), ...rest.reverse());
2298
+ } catch (e) {
2299
+ const code = e.code;
2300
+ if (code !== "ENOENT" && code !== "ENOTDIR") throw e;
2301
+ if (dirname2(cur) === cur) throw e;
2302
+ rest.push(basename3(cur));
2303
+ }
2304
+ }
2305
+ }
2306
+
2307
+ // ../link/src/core/pc/instructions.ts
2308
+ import { lstat as lstat3, open as open3, realpath as realpath5, stat as stat5 } from "fs/promises";
2309
+ import { dirname as dirname4, join as join7 } from "path";
2310
+
2311
+ // ../link/src/core/pc/write.ts
2312
+ import { randomBytes } from "crypto";
2313
+ import { constants as constants2, createWriteStream as createWriteStream2 } from "fs";
2314
+ import { chmod, copyFile, link, lstat as lstat2, mkdir as mkdir2, open as open2, readFile as readBytes, realpath as realpath4, rename as rename2, stat as stat4, unlink } from "fs/promises";
2315
+ import { basename as basename4, dirname as dirname3, join as join6 } from "path";
2316
+ import { Readable as Readable2 } from "stream";
2317
+ import { pipeline as pipeline2 } from "stream/promises";
2318
+ var MAX_TEXT_BYTES = 10 * 1024 * 1024;
2319
+ var MAX_DOWNLOAD_BYTES = 200 * 1024 * 1024;
2320
+ function versionOf(st) {
2321
+ return `${st.dev}:${st.ino}:${st.size}:${st.mtimeNs}:${st.ctimeNs}`;
2322
+ }
2323
+ async function currentVersion(path) {
2324
+ try {
2325
+ const st = await lstat2(path, { bigint: true });
2326
+ return { version: versionOf(st), isFile: st.isFile(), isDir: st.isDirectory(), mode: Number(st.mode & 0o7777n) };
2327
+ } catch (e) {
2328
+ if (e.code === "ENOENT") return null;
2329
+ throw e;
2330
+ }
2331
+ }
2332
+ function parseExpect(v) {
2333
+ const e = v ?? null;
2334
+ if (e && typeof e.version === "string" && e.version) return { version: e.version };
2335
+ if (e && e.absent === true) return { absent: true };
2336
+ throw invalid("expect must be {version} or {absent: true}");
2337
+ }
2338
+ var lockKey = (path, platform = process.platform) => platform === "win32" ? path.toLowerCase() : path;
2339
+ var PathLocks = class {
2340
+ tails = /* @__PURE__ */ new Map();
2341
+ run(keys, op) {
2342
+ const sorted = [...new Set(keys.map((k) => lockKey(k)))].sort();
2343
+ const acquire = (i) => {
2344
+ if (i === sorted.length) return op();
2345
+ const key = sorted[i];
2346
+ const prior = this.tails.get(key) ?? Promise.resolve();
2347
+ const result = prior.catch(() => {
2348
+ }).then(() => acquire(i + 1));
2349
+ const tail = result.catch(() => {
2350
+ });
2351
+ this.tails.set(key, tail);
2352
+ void tail.then(() => {
2353
+ if (this.tails.get(key) === tail) this.tails.delete(key);
2354
+ });
2355
+ return result;
2356
+ };
2357
+ return acquire(0);
2358
+ }
2359
+ };
2360
+ var stale = (path, why) => new RpcFailure(STALE_VERSION, `${path} ${why}`);
2361
+ async function checkExpect(path, expect) {
2362
+ const cur = await currentVersion(path);
2363
+ if ("absent" in expect) {
2364
+ if (cur) throw new RpcFailure(EXISTS, `${path} \u5DF2\u5B58\u5728`);
2365
+ return null;
2366
+ }
2367
+ if (!cur) throw stale(path, "\u5728\u8BFB\u53D6\u4E4B\u540E\u88AB\u5220\u9664\u4E86");
2368
+ if (!cur.isFile) throw invalid(`${path} \u4E0D\u662F\u666E\u901A\u6587\u4EF6`);
2369
+ if (cur.version !== expect.version) throw stale(path, "\u5728\u8BFB\u53D6\u4E4B\u540E\u88AB\u6539\u8FC7");
2370
+ return cur.mode;
2371
+ }
2372
+ async function ensureParent(path) {
2373
+ const parent = dirname3(path);
2374
+ await mkdir2(parent, { recursive: true });
2375
+ if (within(await realpath4(parent), parent) !== "") throw invalid(`${parent} \u7684\u4F4D\u7F6E\u53D8\u4E86\uFF08\u53EF\u80FD\u88AB\u6362\u6210\u4E86\u7B26\u53F7\u94FE\u63A5\uFF09`);
2376
+ }
2377
+ var NO_HARDLINK = /* @__PURE__ */ new Set(["EPERM", "ENOTSUP", "ENOSYS", "EXDEV", "EINVAL"]);
2378
+ var BUSY = /* @__PURE__ */ new Set(["EPERM", "EBUSY", "EACCES"]);
2379
+ async function createExclusive(temp, path, fs = { link, copyFile }) {
2380
+ try {
2381
+ await fs.link(temp, path);
2382
+ } catch (e) {
2383
+ const code = e.code ?? "";
2384
+ if (code === "EEXIST") throw new RpcFailure(EXISTS, `${path} \u5DF2\u5B58\u5728`);
2385
+ if (!NO_HARDLINK.has(code)) throw e;
2386
+ try {
2387
+ await fs.copyFile(temp, path, constants2.COPYFILE_EXCL);
2388
+ } catch (e2) {
2389
+ if (e2.code === "EEXIST") throw new RpcFailure(EXISTS, `${path} \u5DF2\u5B58\u5728`);
2390
+ throw e2;
2391
+ }
2392
+ }
2393
+ }
2394
+ async function replaceWith(temp, path, deps = {}) {
2395
+ const doRename = deps.rename ?? rename2;
2396
+ const retry = (deps.platform ?? process.platform) === "win32";
2397
+ for (const wait of [...retry ? deps.delays ?? [100, 300, 900] : [], -1]) {
2398
+ try {
2399
+ return await doRename(temp, path);
2400
+ } catch (e) {
2401
+ if (!retry || !BUSY.has(e.code ?? "")) throw e;
2402
+ if (wait < 0) throw invalid(`${path} \u88AB\u5176\u4ED6\u7A0B\u5E8F\u5360\u7528\u6216\u662F\u53EA\u8BFB\u6587\u4EF6\uFF0C\u5199\u4E0D\u8FDB\u53BB\uFF1A\u5173\u6389\u5360\u7528\u5B83\u7684\u7A0B\u5E8F\u540E\u518D\u8BD5`);
2403
+ await new Promise((r) => setTimeout(r, wait));
2404
+ }
2405
+ }
2406
+ }
2407
+ var tempPath = (path) => join6(dirname3(path), `.${basename4(path)}.leo-${randomBytes(6).toString("hex")}`);
2408
+ async function commit(temp, path, mode) {
2409
+ try {
2410
+ if (mode === null) {
2411
+ await createExclusive(temp, path);
2412
+ await unlink(temp);
2413
+ } else {
2414
+ await chmod(temp, mode);
2415
+ await replaceWith(temp, path);
2416
+ }
2417
+ } catch (e) {
2418
+ await unlink(temp).catch(() => {
2419
+ });
2420
+ throw e;
2421
+ }
2422
+ }
2423
+ async function writeTemp(path, data) {
2424
+ const temp = tempPath(path);
2425
+ const handle = await open2(temp, constants2.O_WRONLY | constants2.O_CREAT | constants2.O_EXCL | constants2.O_NOFOLLOW, 420);
2426
+ try {
2427
+ await handle.writeFile(data);
2428
+ await handle.sync();
2429
+ } catch (e) {
2430
+ await handle.close();
2431
+ await unlink(temp).catch(() => {
2432
+ });
2433
+ throw e;
2434
+ }
2435
+ await handle.close();
2436
+ return temp;
2437
+ }
2438
+ async function versionAfter(path) {
2439
+ return versionOf(await stat4(path, { bigint: true }));
2440
+ }
2441
+ var lineCount = (text) => text === "" ? 0 : text.split("\n").length - (text.endsWith("\n") ? 1 : 0);
2442
+ async function writeText(path, content, expect) {
2443
+ if (Buffer.byteLength(content) > MAX_TEXT_BYTES) {
2444
+ throw new RpcFailure(TOO_LARGE, "\u5185\u5BB9\u8D85\u8FC7 10 MB \u4E0A\u9650", { size: Buffer.byteLength(content), limit: MAX_TEXT_BYTES });
2445
+ }
2446
+ const mode = await checkExpect(path, expect);
2447
+ await ensureParent(path);
2448
+ await commit(await writeTemp(path, content), path, mode);
2449
+ return { version: await versionAfter(path), created: mode === null, lines: lineCount(content) };
2450
+ }
2451
+ function decodeForEdit(path, raw) {
2452
+ let text;
2453
+ try {
2454
+ text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(raw);
2455
+ } catch {
2456
+ throw new RpcFailure(NOT_A_TEXT_FILE, `${path} \u4E0D\u662F UTF-8 \u6587\u672C\uFF0C\u4E0D\u80FD\u7528 edit \u4FEE\u6539`);
2457
+ }
2458
+ if (text.includes("\0")) throw new RpcFailure(NOT_A_TEXT_FILE, `${path} \u4E0D\u662F\u6587\u672C\u6587\u4EF6`);
2459
+ const bom = text.charCodeAt(0) === 65279;
2460
+ if (bom) text = text.slice(1);
2461
+ const sample = text.slice(0, 4096);
2462
+ const crlfCount = sample.split("\r\n").length - 1;
2463
+ const lfCount = sample.split("\n").length - 1 - crlfCount;
2464
+ return { text: text.replaceAll("\r\n", "\n"), bom, crlf: crlfCount > lfCount };
2465
+ }
2466
+ function encodeBack(d, text) {
2467
+ return (d.bom ? "\uFEFF" : "") + (d.crlf ? text.split("\n").join("\r\n") : text);
2468
+ }
2469
+ function countOccurrences(text, needle) {
2470
+ let count = 0;
2471
+ for (let i = text.indexOf(needle); i !== -1; i = text.indexOf(needle, i + needle.length)) count++;
2472
+ return count;
2473
+ }
2474
+ var SNIPPET_CONTEXT = 3;
2475
+ async function editText(path, oldString, newString, replaceAll, expect) {
2476
+ const mode = await checkExpect(path, expect);
2477
+ const raw = await readBytes(path);
2478
+ if (raw.length > MAX_TEXT_BYTES) throw new RpcFailure(TOO_LARGE, "\u6587\u4EF6\u8D85\u8FC7 10 MB\uFF0C\u4E0D\u80FD\u7528 edit \u4FEE\u6539", { size: raw.length, limit: MAX_TEXT_BYTES });
2479
+ const decoded = decodeForEdit(path, raw);
2480
+ const needle = oldString.replaceAll("\r\n", "\n");
2481
+ const replacement = newString.replaceAll("\r\n", "\n");
2482
+ const count = countOccurrences(decoded.text, needle);
2483
+ if (count === 0) throw new RpcFailure(EDIT_NOT_FOUND, `\u5728 ${path} \u91CC\u6CA1\u6709\u627E\u5230 old_string`);
2484
+ if (count > 1 && !replaceAll) throw new RpcFailure(EDIT_AMBIGUOUS, `old_string \u5728 ${path} \u91CC\u51FA\u73B0\u4E86 ${count} \u6B21`, { count });
2485
+ const first = decoded.text.indexOf(needle);
2486
+ const edited = replaceAll ? decoded.text.split(needle).join(replacement) : decoded.text.replace(needle, () => replacement);
2487
+ await commit(await writeTemp(path, encodeBack(decoded, edited)), path, mode);
2488
+ const startLine = decoded.text.slice(0, first).split("\n").length;
2489
+ const all = edited.split("\n");
2490
+ const from = Math.max(1, startLine - SNIPPET_CONTEXT);
2491
+ const to = Math.min(all.length, startLine + replacement.split("\n").length - 1 + SNIPPET_CONTEXT);
2492
+ return {
2493
+ version: await versionAfter(path),
2494
+ replaced: replaceAll ? count : 1,
2495
+ snippet: { start_line: from, lines: all.slice(from - 1, to) }
2496
+ };
2497
+ }
2498
+ async function downloadTo(path, body, expect, signal) {
2499
+ const mode = await checkExpect(path, expect);
2500
+ await ensureParent(path);
2501
+ const temp = tempPath(path);
2502
+ let size = 0;
2503
+ try {
2504
+ const source = Readable2.fromWeb(body);
2505
+ source.on("data", (chunk) => {
2506
+ size += chunk.length;
2507
+ if (size > MAX_DOWNLOAD_BYTES) {
2508
+ source.destroy(new RpcFailure(TOO_LARGE, "\u6587\u4EF6\u8D85\u8FC7 200 MB \u4E0A\u9650", { size, limit: MAX_DOWNLOAD_BYTES }));
2509
+ }
2510
+ });
2511
+ await pipeline2(source, createWriteStream2(temp, { flags: "wx", mode: 420 }), { signal });
2512
+ if (mode !== null) await checkExpect(path, expect);
2513
+ } catch (e) {
2514
+ await unlink(temp).catch(() => {
2515
+ });
2516
+ throw e;
2517
+ }
2518
+ await commit(temp, path, mode);
2519
+ return { version: await versionAfter(path), size, created: mode === null };
2520
+ }
2521
+
2522
+ // ../link/src/core/pc/instructions.ts
2523
+ var INSTRUCTION_NAMES = ["AGENTS.md", "CLAUDE.md"];
2524
+ var MAX_INSTRUCTION_BYTES = 256 * 1024;
2525
+ var exists = (p) => lstat3(p).then(() => true, () => false);
2526
+ function aboveProjects(p, home) {
2527
+ return within(home, p) !== null;
2528
+ }
2529
+ async function projectRoot(dir, home) {
2530
+ if (aboveProjects(dir, home)) return null;
2531
+ for (let cur = dir; !aboveProjects(cur, home); cur = dirname4(cur)) {
2532
+ if (await exists(join7(cur, ".git"))) return cur;
2533
+ if (dirname4(cur) === cur) break;
2534
+ }
2535
+ return dir;
2536
+ }
2537
+ function chain(root, dir) {
2538
+ const out = [];
2539
+ for (let cur = dir; ; cur = dirname4(cur)) {
2540
+ out.push(cur);
2541
+ if (cur === root || dirname4(cur) === cur) break;
2542
+ }
2543
+ return out.reverse();
2544
+ }
2545
+ async function pick(dir, root) {
2546
+ for (const name of INSTRUCTION_NAMES) {
2547
+ const path = join7(dir, name);
2548
+ const st = await lstat3(path).catch(() => null);
2549
+ if (!st) continue;
2550
+ if (st.isFile()) return { path, target: path };
2551
+ if (!st.isSymbolicLink()) continue;
2552
+ const target = await realpath5(path).catch(() => null);
2553
+ if (target && within(target, root) !== null && (await stat5(target)).isFile()) return { path, target };
2554
+ }
2555
+ return null;
2556
+ }
2557
+ async function load(path, target, scope, opts) {
2558
+ if (await classify(target, [], opts.sensitive) === "sensitive") return null;
2559
+ const cur = await currentVersion(target);
2560
+ if (!cur?.isFile) return null;
2561
+ const bytes = (await stat5(target)).size;
2562
+ const base = { path, scope, version: cur.version, bytes };
2563
+ if (opts.known?.[path] === cur.version) return base;
2564
+ const content = decodeHead(await readHead(target, MAX_INSTRUCTION_BYTES), bytes > MAX_INSTRUCTION_BYTES);
2565
+ if (content === null) return { ...base, error: "not_utf8" };
2566
+ return { ...base, content, ...bytes > MAX_INSTRUCTION_BYTES ? { truncated: true } : {} };
2567
+ }
2568
+ async function readHead(path, max) {
2569
+ const handle = await open3(path, "r");
2570
+ try {
2571
+ const buf = Buffer.alloc(max);
2572
+ const { bytesRead } = await handle.read(buf, 0, max, 0);
2573
+ return buf.subarray(0, bytesRead);
2574
+ } finally {
2575
+ await handle.close();
2576
+ }
2577
+ }
2578
+ function decodeHead(buf, cut) {
2579
+ const decoder = new TextDecoder("utf-8", { fatal: true });
2580
+ for (let drop = 0; drop <= (cut ? 3 : 0); drop++) {
2581
+ try {
2582
+ return decoder.decode(buf.subarray(0, buf.length - drop));
2583
+ } catch {
2584
+ }
2585
+ }
2586
+ return null;
2587
+ }
2588
+ async function findInstructions(targets, opts) {
2589
+ const seen = /* @__PURE__ */ new Set();
2590
+ const out = [];
2591
+ for (const target of targets) {
2592
+ const st = await stat5(target).catch(() => null);
2593
+ if (!st?.isDirectory() || await classify(target, [], opts.sensitive) === "sensitive") continue;
2594
+ const root = await projectRoot(target, opts.home);
2595
+ if (!root) continue;
2596
+ for (const dir of chain(root, target)) {
2597
+ if (seen.has(dir)) continue;
2598
+ seen.add(dir);
2599
+ const chosen = await pick(dir, root);
2600
+ const file = chosen && await load(chosen.path, chosen.target, dir, opts);
2601
+ if (file) out.push(file);
2602
+ }
2603
+ }
2604
+ return out;
2605
+ }
2606
+
2607
+ // ../link/src/core/pc/search.ts
2608
+ import { spawn as nodeSpawn2 } from "child_process";
2609
+ import { open as open4, opendir } from "fs/promises";
2610
+ import { join as join8 } from "path";
2611
+ var MAX_OUTPUT_LINE = 8 * 1024 * 1024;
2612
+ function permissionMessage(path, platform = process.platform) {
2613
+ const base = `\u6CA1\u6709\u6743\u9650\u8BFB\u53D6 ${path}`;
2614
+ if (platform !== "darwin") return base;
2615
+ return `${base}\uFF1AmacOS \u6CA1\u6709\u5141\u8BB8\u8BBF\u95EE\u8FD9\u4E2A\u4F4D\u7F6E\uFF0C\u5230\u300C\u7CFB\u7EDF\u8BBE\u7F6E \u2192 \u9690\u79C1\u4E0E\u5B89\u5168\u6027 \u2192 \u6587\u4EF6\u548C\u6587\u4EF6\u5939\u300D\u91CC\u7ED9\u8FD0\u884C Leo \u7684\u7A0B\u5E8F\u6253\u5F00\uFF08\u684C\u9762\u7AEF\u662F Leo\uFF0C\u547D\u4EE4\u884C\u7248 leo-link \u662F node\uFF09`;
2616
+ }
2617
+ async function assertReadable(path, isDir) {
2618
+ try {
2619
+ if (isDir) await (await opendir(path)).close();
2620
+ else await (await open4(path, "r")).close();
2621
+ } catch (e) {
2622
+ const code = e.code;
2623
+ if (code === "EPERM" || code === "EACCES") throw new Error(permissionMessage(path));
2624
+ throw e;
2625
+ }
2626
+ }
2627
+ async function* splitStream(stream, sep3) {
2628
+ let parts = [];
2629
+ let len = 0;
2630
+ let oversize = false;
2631
+ for await (const chunk of stream) {
2632
+ let start2 = 0;
2633
+ for (; ; ) {
2634
+ const idx = chunk.indexOf(sep3, start2);
2635
+ const end = idx === -1 ? chunk.length : idx;
2636
+ if (!oversize) {
2637
+ if (len + end - start2 > MAX_OUTPUT_LINE) {
2638
+ oversize = true;
2639
+ parts = [];
2640
+ len = 0;
2641
+ } else if (end > start2) {
2642
+ parts.push(chunk.subarray(start2, end));
2643
+ len += end - start2;
2644
+ }
2645
+ }
2646
+ if (idx === -1) break;
2647
+ if (!oversize) yield Buffer.concat(parts, len);
2648
+ parts = [];
2649
+ len = 0;
2650
+ oversize = false;
2651
+ start2 = idx + 1;
2652
+ }
2653
+ }
2654
+ if (len && !oversize) yield Buffer.concat(parts, len);
2655
+ }
2656
+ async function runRg(opts, consume) {
2657
+ if (opts.signal.aborted) throw new RpcFailure(REQUEST_CANCELLED, "Request cancelled");
2658
+ const child = (opts.spawnImpl ?? nodeSpawn2)(opts.rgPath, opts.args, {
2659
+ cwd: opts.cwd,
2660
+ stdio: ["ignore", "pipe", "pipe"],
2661
+ // rg 不需要任何环境;不继承,免得 RIPGREP_CONFIG_PATH 之类改写行为。Windows 上进程启动要 SystemRoot
2662
+ env: { PATH: "/usr/bin:/bin", LANG: "en_US.UTF-8", SystemRoot: process.env.SystemRoot },
2663
+ windowsHide: true
2664
+ });
2665
+ const done = new Promise((resolve3) => {
2666
+ child.once("error", (error) => resolve3({ code: null, error }));
2667
+ child.once("close", (code) => resolve3({ code }));
2668
+ });
2669
+ let stderr = "";
2670
+ child.stderr?.on("data", (d) => {
2671
+ if (stderr.length < 8192) stderr += d.toString("utf8");
2672
+ });
2673
+ const kill = () => {
2674
+ if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
2675
+ };
2676
+ opts.signal.addEventListener("abort", kill, { once: true });
2677
+ let stopped = false;
2678
+ try {
2679
+ for await (const item of splitStream(child.stdout, opts.sep)) {
2680
+ if (opts.signal.aborted) break;
2681
+ if (!await consume(item)) {
2682
+ stopped = true;
2683
+ kill();
2684
+ break;
2685
+ }
2686
+ }
2687
+ const { code, error } = await done;
2688
+ if (opts.signal.aborted) throw new RpcFailure(REQUEST_CANCELLED, "Request cancelled");
2689
+ if (error) throw new Error(`\u65E0\u6CD5\u542F\u52A8 ripgrep\uFF1A${error.message}`);
2690
+ if (!stopped && code === 2 && /regex parse error|error parsing/.test(stderr)) {
2691
+ throw invalid(stderr.replace(/^rg: /, "").trim());
2692
+ }
2693
+ return { stopped };
2694
+ } finally {
2695
+ opts.signal.removeEventListener("abort", kill);
2696
+ kill();
2697
+ }
2698
+ }
2699
+ var stripDot = (p) => p.replace(/^\.[\\/]/, "");
2700
+ async function rgGlob(opts) {
2701
+ await assertReadable(opts.cwd, true);
2702
+ const paths = [];
2703
+ const args = ["--no-config", "--files", "--null", "--hidden", "--glob", opts.pattern, "--glob", "!.git", "--sortr", "modified", "--", "."];
2704
+ const { stopped } = await runRg({ ...opts, args, sep: 0 }, async (item) => {
2705
+ const rel = stripDot(item.toString("utf8"));
2706
+ if (!rel || !await opts.keep(rel)) return true;
2707
+ if (paths.length >= opts.limit) return false;
2708
+ paths.push(rel);
2709
+ return true;
2710
+ });
2711
+ return { paths, truncated: stopped };
2712
+ }
2713
+ function lineText(lines, maxChars) {
2714
+ const raw = lines?.text ?? (lines?.bytes ? Buffer.from(lines.bytes, "base64").toString("utf8") : "");
2715
+ const text = raw.replace(/\r?\n$/, "");
2716
+ return text.length > maxChars ? text.slice(0, maxChars) : text;
2717
+ }
2718
+ async function rgGrep(opts) {
2719
+ await (opts.target === "." ? assertReadable(opts.cwd, true) : assertReadable(join8(opts.cwd, opts.target), false));
2720
+ const args = [
2721
+ "--no-config",
2722
+ "--json",
2723
+ "--hidden",
2724
+ ...opts.glob ? ["--glob", opts.glob] : [],
2725
+ "--glob",
2726
+ "!.git",
2727
+ ...opts.ignoreCase ? ["-i"] : [],
2728
+ ...opts.mode === "files_with_matches" ? ["--max-count", "1"] : [],
2729
+ ...opts.mode === "content" && opts.context > 0 ? ["--context", String(opts.context)] : [],
2730
+ "-e",
2731
+ opts.pattern,
2732
+ "--",
2733
+ opts.target
2734
+ ];
2735
+ const kept = /* @__PURE__ */ new Map();
2736
+ const keep = async (rel) => {
2737
+ let v = kept.get(rel);
2738
+ if (v === void 0) kept.set(rel, v = await opts.keep(rel));
2739
+ return v;
2740
+ };
2741
+ const files = [];
2742
+ const counts = [];
2743
+ const matches = [];
2744
+ let before = [];
2745
+ let open5 = [];
2746
+ const { stopped } = await runRg({ ...opts, args, sep: 10 }, async (item) => {
2747
+ let ev;
2748
+ try {
2749
+ ev = JSON.parse(item.toString("utf8"));
2750
+ } catch {
2751
+ return true;
2752
+ }
2753
+ const rawPath = ev.data?.path?.text;
2754
+ if (ev.type === "begin") {
2755
+ before = [];
2756
+ open5 = [];
2757
+ return true;
2758
+ }
2759
+ if (rawPath === void 0) return true;
2760
+ const rel = stripDot(rawPath);
2761
+ if (!await keep(rel)) return true;
2762
+ if (opts.mode === "files_with_matches") {
2763
+ if (ev.type !== "match" || files.at(-1) === rel) return true;
2764
+ if (files.length >= opts.limit) return false;
2765
+ files.push(rel);
2766
+ } else if (opts.mode === "count") {
2767
+ const n = ev.type === "end" ? ev.data.stats?.matched_lines ?? 0 : 0;
2768
+ if (!n) return true;
2769
+ if (counts.length >= opts.limit) return false;
2770
+ counts.push({ path: rel, count: n });
2771
+ } else if (ev.type === "context") {
2772
+ const ctxLine = { line: ev.data.line_number ?? 0, text: lineText(ev.data.lines, opts.maxLineChars) };
2773
+ for (const m of open5) if (ctxLine.line <= m.line + opts.context) (m.context_after ??= []).push(ctxLine);
2774
+ open5 = open5.filter((m) => ctxLine.line < m.line + opts.context);
2775
+ before.push(ctxLine);
2776
+ if (before.length > opts.context) before.shift();
2777
+ } else if (ev.type === "match") {
2778
+ if (matches.length >= opts.limit) return false;
2779
+ const line = ev.data.line_number ?? 0;
2780
+ const m = { path: rel, line, text: lineText(ev.data.lines, opts.maxLineChars) };
2781
+ if (opts.context > 0) {
2782
+ const b = before.filter((c) => c.line >= line - opts.context);
2783
+ if (b.length) m.context_before = b;
2784
+ open5.push(m);
2785
+ }
2786
+ before = [];
2787
+ matches.push(m);
2788
+ }
2789
+ return true;
2790
+ });
2791
+ if (opts.mode === "files_with_matches") return { files, truncated: stopped };
2792
+ if (opts.mode === "count") return { counts, truncated: stopped };
2793
+ return { matches, truncated: stopped };
2794
+ }
2795
+
2796
+ // ../link/src/core/pc/workspace.ts
2797
+ import { lstat as lstat4, readdir as readdir2, stat as stat6 } from "fs/promises";
2798
+ import { existsSync as existsSync2, mkdirSync as mkdirSync2, realpathSync } from "fs";
2799
+ import { join as join9 } from "path";
2800
+ var SESSION_RE = /^[A-Za-z0-9_.:-]{1,200}$/;
2801
+ function isValidSessionId(id) {
2802
+ return typeof id === "string" && SESSION_RE.test(id);
2803
+ }
2804
+ var LeoFolder = class {
2805
+ dir;
2806
+ canonical = null;
2807
+ constructor(dir) {
2808
+ this.dir = dir;
2809
+ }
2810
+ /** 建好目录(权限 700;已存在则沿用),返回规范路径;失败时返回 null。用户删了也会补回来。 */
2811
+ ensure() {
2812
+ try {
2813
+ mkdirSync2(this.dir, { recursive: true, mode: 448 });
2814
+ this.canonical = realpathSync(this.dir);
2815
+ } catch {
2816
+ this.canonical = null;
2817
+ }
2818
+ return this.canonical;
2819
+ }
2820
+ /** 规范路径;还没建好时是 null */
2821
+ get path() {
2822
+ return this.canonical;
2823
+ }
2824
+ };
2825
+ async function vetFolders(paths, sensitive, fs = nodeBoundaryFs) {
2826
+ const result = { accepted: [], rejected: [] };
2827
+ for (const p of paths) {
2828
+ try {
2829
+ if ((await lstat4(p)).isSymbolicLink()) {
2830
+ result.rejected.push({ path: p, code: "symlink", reason: "\u662F\u7B26\u53F7\u94FE\u63A5\uFF0C\u8BF7\u76F4\u63A5\u9009\u62E9\u5B83\u6307\u5411\u7684\u4F4D\u7F6E" });
2831
+ continue;
2832
+ }
2833
+ const canonical = await fs.realpath(p);
2834
+ if (await classify(canonical, [], sensitive, fs) === "sensitive") {
2835
+ result.rejected.push({ path: p, code: "sensitive", reason: "\u5C5E\u4E8E\u654F\u611F\u4F4D\u7F6E\uFF08\u51ED\u8BC1\u3001\u5BC6\u94A5\u3001\u6D4F\u89C8\u5668\u6216\u90AE\u4EF6\u6570\u636E\u7B49\uFF09\uFF0C\u4E0D\u80FD\u4EA4\u7ED9 Leo" });
2836
+ continue;
2837
+ }
2838
+ if (!(await stat6(canonical)).isDirectory()) {
2839
+ result.rejected.push({ path: p, code: "type", reason: "\u4E0D\u662F\u6587\u4EF6\u5939\uFF0C\u5DE5\u4F5C\u7A7A\u95F4\u53EA\u80FD\u52A0\u6587\u4EF6\u5939" });
2840
+ continue;
2841
+ }
2842
+ result.accepted.push({ path: canonical, kind: "dir" });
2843
+ } catch {
2844
+ result.rejected.push({ path: p, code: "unreadable", reason: "\u65E0\u6CD5\u8BFB\u53D6" });
2845
+ }
2846
+ }
2847
+ return result;
2848
+ }
2849
+ function listDrives(platform = process.platform, exists2 = existsSync2) {
2850
+ if (platform !== "win32") return void 0;
2851
+ return [..."CDEFGHIJKLMNOPQRSTUVWXYZ"].map((l) => `${l}:\\`).filter((d) => exists2(d));
2852
+ }
2853
+ var BROWSE_LIMIT = 500;
2854
+ var byName = (a, b) => a.localeCompare(b, void 0, { numeric: true, sensitivity: "base" });
2855
+ var WINDOWS_HIDDEN = /^(appdata|\$recycle\.bin|system volume information|recovery|config\.msi|ntuser\..*|desktop\.ini|thumbs\.db|(pagefile|hiberfil|swapfile)\.sys|dumpstack\.log.*)$/i;
2856
+ var isHiddenEntry = (name, platform = process.platform) => name.startsWith(".") || platform === "win32" && WINDOWS_HIDDEN.test(name);
2857
+ async function browseDir(path, home, sensitive, fs = nodeBoundaryFs, limit = BROWSE_LIMIT) {
2858
+ const dir = await canonicalize(path, fs);
2859
+ if (await classify(dir, [], sensitive, fs) === "sensitive") throw new RpcFailure(PATH_SENSITIVE, `\u654F\u611F\u4F4D\u7F6E\uFF0C\u4E0D\u80FD\u6D4F\u89C8\uFF1A${dir}`);
2860
+ if (!(await stat6(dir)).isDirectory()) throw invalid(`\u4E0D\u662F\u6587\u4EF6\u5939\uFF1A${dir}`);
2861
+ const dirs = [];
2862
+ const files = [];
2863
+ for (const e of await readdir2(dir, { withFileTypes: true })) {
2864
+ if (isHiddenEntry(e.name) || e.isSymbolicLink()) continue;
2865
+ if (e.isDirectory()) {
2866
+ if (await classify(join9(dir, e.name), [], sensitive, fs) !== "sensitive") dirs.push(e.name);
2867
+ } else if (e.isFile()) {
2868
+ files.push(e.name);
2869
+ }
2870
+ }
2871
+ dirs.sort(byName);
2872
+ files.sort(byName);
2873
+ const drives = listDrives();
2874
+ return {
2875
+ path: dir,
2876
+ home: await fs.realpath(home).catch(() => home),
2877
+ dirs: dirs.slice(0, limit),
2878
+ files: files.slice(0, limit),
2879
+ truncated: dirs.length > limit || files.length > limit,
2880
+ ...drives && { drives }
2881
+ };
2882
+ }
2883
+
2884
+ // ../link/src/core/pc/index.ts
2885
+ function parseSessionId(v) {
2886
+ if (!isValidSessionId(v)) throw invalid("session_id must be a Leo session id");
2887
+ return v;
2888
+ }
2889
+ function parseCtx(params) {
2890
+ const ctx = params.ctx;
2891
+ if (!ctx || typeof ctx !== "object" || Array.isArray(ctx)) throw invalid("ctx must be an object");
2892
+ if (ctx.scope !== "workspace" && ctx.scope !== "outside_approved") throw invalid('ctx.scope must be "workspace" or "outside_approved"');
2893
+ if (ctx.roots !== void 0 && !Array.isArray(ctx.roots)) throw invalid("ctx.roots must be an array");
2894
+ return { sessionId: parseSessionId(ctx.session_id), scope: ctx.scope, roots: ctx.roots ?? [] };
2895
+ }
2896
+ function intParam(params, key, fallback, min, max) {
2897
+ const v = params[key];
2898
+ if (v === void 0 || v === null) return fallback;
2899
+ if (typeof v !== "number" || !Number.isInteger(v) || v < min || v > max) throw invalid(`${key} must be an integer in [${min}, ${max}]`);
2900
+ return v;
2901
+ }
2902
+ function optString(params, key) {
2903
+ const v = params[key];
2904
+ if (v === void 0 || v === null) return void 0;
2905
+ if (typeof v !== "string" || v === "") throw invalid(`${key} must be a non-empty string`);
2906
+ return v;
2907
+ }
2908
+ function enforce(cls, scope, path) {
2909
+ if (cls === "sensitive") throw new RpcFailure(PATH_SENSITIVE, `\u654F\u611F\u8DEF\u5F84\uFF0C\u4E0D\u5141\u8BB8\u8BBF\u95EE\uFF1A${path}`);
2910
+ if (cls === "outside" && scope !== "outside_approved") throw new RpcFailure(PATH_OUTSIDE, `\u8DEF\u5F84\u5728\u5DE5\u4F5C\u7A7A\u95F4\u4E4B\u5916\uFF1A${path}`);
2911
+ }
2912
+ function enforceWrite(cls, scope, path) {
2913
+ if (cls === "protected") throw new RpcFailure(PATH_PROTECTED, `\u53D7\u4FDD\u62A4\u7684\u4F4D\u7F6E\uFF0C\u4E0D\u80FD\u4FEE\u6539\uFF1A${path}`);
2914
+ enforce(cls, scope, path);
2915
+ }
2916
+ async function isExecutable(path, platform = process.platform, statImpl = stat7) {
2917
+ const exts = openExecutableExts(platform, process.env.PATHEXT ?? "");
2918
+ const P = platform === "win32" ? win325 : posix3;
2919
+ if (path.split(P.sep).some((part) => exts.has(P.extname(part).toLowerCase()))) return true;
2920
+ if (platform === "win32") return false;
2921
+ const st = await statImpl(path);
2922
+ return st.isFile() && (st.mode & 73) !== 0;
2923
+ }
2924
+ var GREP_MODES = ["files_with_matches", "content", "count"];
2925
+ var EXEC_MODES = ["read-only", "workspace-write", "escalated", "unsandboxed"];
2926
+ function createPcHandlers(deps) {
2927
+ const home = deps.home ?? homedir4();
2928
+ const fs = deps.fs ?? nodeBoundaryFs;
2929
+ const locks = new PathLocks();
2930
+ const rootsOf = async (ctx, sensitive) => {
2931
+ const claimed = ctx.roots.map((r) => r && typeof r === "object" ? r.path : void 0).filter((p) => typeof p === "string" && isRootPath(p));
2932
+ return claimed.length ? (await vetFolders(claimed, sensitive, fs)).accepted : [];
2933
+ };
2934
+ const locate = async (ctx, raw) => {
2935
+ const sensitive = await loadSensitive(home, deps.sensitiveExtra, fs);
2936
+ const roots = await rootsOf(ctx, sensitive);
2937
+ const path = await canonicalize(resolveInput(raw, roots, home), fs);
2938
+ return { path, roots, sensitive, cls: await classify(path, roots, sensitive, fs) };
2939
+ };
2940
+ const locateWrite = async (ctx, raw) => {
2941
+ const sensitive = await loadSensitive(home, deps.sensitiveExtra, fs);
2942
+ const roots = await rootsOf(ctx, sensitive);
2943
+ const path = await resolveForCreate(resolveInput(raw, roots, home), fs);
2944
+ return { path, roots, sensitive, cls: await classifyWrite(path, roots, sensitive, home, fs) };
2945
+ };
2946
+ const searchBase = async (ctx, params) => {
2947
+ const raw = optString(params, "path");
2948
+ let target;
2949
+ if (raw !== void 0) {
2950
+ target = await locate(ctx, raw);
2951
+ } else {
2952
+ const root = primaryRoot(await rootsOf(ctx, await loadSensitive(home, deps.sensitiveExtra, fs)));
2953
+ if (!root) throw invalid("\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u5DE5\u4F5C\u7A7A\u95F4\uFF0C\u8BF7\u7ED9\u51FA path");
2954
+ target = await locate(ctx, baseOfRoot(root));
2955
+ }
2956
+ enforce(target.cls, ctx.scope, target.path);
2957
+ const rg = deps.rgPath();
2958
+ if (!rg) throw new Error("\u8FD9\u53F0\u7535\u8111\u4E0A\u7684 ripgrep \u4E0D\u53EF\u7528");
2959
+ const keep = async (base, rel) => await classify(join10(base, rel), target.roots, target.sensitive, fs) !== "sensitive";
2960
+ return { ...target, rg, keep, isDir: (await stat7(target.path)).isDirectory() };
2961
+ };
2962
+ return {
2963
+ // 准备加入工作空间的路径(目录浏览里选的、Leo 的加入请求经用户批准后):只收文件夹
2964
+ "pc.fs.vet": async (params) => {
2965
+ const path = await canonicalize(resolveInput(params.path, [], home), fs);
2966
+ const vetted = await vetFolders([path], await loadSensitive(home, deps.sensitiveExtra, fs), fs);
2967
+ const rejected = vetted.rejected[0];
2968
+ if (rejected) {
2969
+ if (rejected.code === "sensitive") throw new RpcFailure(PATH_SENSITIVE, `\u654F\u611F\u8DEF\u5F84\uFF0C\u4E0D\u80FD\u52A0\u5165\u5DE5\u4F5C\u7A7A\u95F4\uFF1A${path}`);
2970
+ throw invalid(`${path} ${rejected.reason}`);
2971
+ }
2972
+ return vetted.accepted[0];
2973
+ },
2974
+ // 目录浏览:三端选文件夹都用它。只接受绝对路径与 ~/…;起点 Leo 文件夹被删了先补回来
2975
+ "pc.fs.browse": async (params) => {
2976
+ deps.leoFolder.ensure();
2977
+ const path = resolveInput(optString(params, "path") ?? "~", [], home);
2978
+ return browseDir(path, home, await loadSensitive(home, deps.sensitiveExtra, fs), fs);
2979
+ },
2980
+ // 项目说明文件(AGENTS.md / CLAUDE.md):服务端发起的只读读取,不经审批、不看工作空间——
2981
+ // 范围只靠固定文件名与 instructions.ts 的限制(敏感、软链、主目录以上)
2982
+ "pc.fs.instructions": async (params) => {
2983
+ const raw = params.dirs;
2984
+ if (!Array.isArray(raw) || raw.length > 64) throw invalid("dirs must be an array of at most 64 paths");
2985
+ const known = params.known ?? {};
2986
+ if (typeof known !== "object" || Array.isArray(known) || Object.values(known).some((v) => typeof v !== "string")) {
2987
+ throw invalid("known must map paths to version strings");
2988
+ }
2989
+ const targets = await Promise.all(raw.map((d) => fs.realpath(resolveInput(d, [], home)).catch(() => null)));
2990
+ return {
2991
+ files: await findInstructions(targets.filter((t) => t !== null), {
2992
+ home: await fs.realpath(home).catch(() => home),
2993
+ sensitive: await loadSensitive(home, deps.sensitiveExtra, fs),
2994
+ known
2995
+ })
2996
+ };
2997
+ },
2998
+ "pc.fs.stat": async (params) => {
2999
+ const ctx = parseCtx(params);
3000
+ let target;
3001
+ try {
3002
+ target = await locate(ctx, params.path);
3003
+ } catch (e) {
3004
+ if (e instanceof RpcFailure && e.code === NOT_FOUND) {
3005
+ const w = await locateWrite(ctx, params.path);
3006
+ throw new RpcFailure(NOT_FOUND, e.message, { path: w.path, class: w.cls });
3007
+ }
3008
+ throw e;
3009
+ }
3010
+ const { path, cls } = target;
3011
+ if (cls === "sensitive") return { path, class: cls };
3012
+ const version = (await currentVersion(path))?.version;
3013
+ return { path, class: cls, protected: isProtected(path, home), ...version ? { version } : {}, ...await statInfo(path) };
3014
+ },
3015
+ "pc.fs.read": async (params) => {
3016
+ const ctx = parseCtx(params);
3017
+ const { path, cls } = await locate(ctx, params.path);
3018
+ enforce(cls, ctx.scope, path);
3019
+ const version = (await currentVersion(path))?.version;
3020
+ const result = await readFile2(path, {
3021
+ offset: intParam(params, "offset", 1, 1, Number.MAX_SAFE_INTEGER),
3022
+ limit: intParam(params, "limit", 2e3, 1, 1e5),
3023
+ maxBytes: intParam(params, "max_bytes", 51200, 2, 10 * 1024 * 1024),
3024
+ maxLineChars: intParam(params, "max_line_chars", 2e3, 1, 1e5)
3025
+ });
3026
+ return { path, ...version ? { version } : {}, ...result };
3027
+ },
3028
+ "pc.fs.glob": async (params, rpc) => {
3029
+ const ctx = parseCtx(params);
3030
+ const pattern = optString(params, "pattern");
3031
+ if (pattern === void 0) throw invalid("pattern is required");
3032
+ const limit = intParam(params, "limit", 200, 1, 1e4);
3033
+ const base = await searchBase(ctx, params);
3034
+ if (!base.isDir) throw invalid("path \u4E0D\u662F\u76EE\u5F55");
3035
+ const result = await rgGlob({
3036
+ rgPath: base.rg,
3037
+ cwd: base.path,
3038
+ signal: rpc.signal,
3039
+ pattern,
3040
+ limit,
3041
+ keep: (rel) => base.keep(base.path, rel),
3042
+ spawnImpl: deps.spawnImpl
3043
+ });
3044
+ return { base: base.path, ...result };
3045
+ },
3046
+ "pc.fs.grep": async (params, rpc) => {
3047
+ const ctx = parseCtx(params);
3048
+ const pattern = typeof params.pattern === "string" ? params.pattern : void 0;
3049
+ if (!pattern) throw invalid("pattern is required");
3050
+ const glob = optString(params, "glob");
3051
+ const mode = params.output_mode ?? "files_with_matches";
3052
+ if (!GREP_MODES.includes(mode)) throw invalid(`output_mode must be one of ${GREP_MODES.join(", ")}`);
3053
+ if (params.ignore_case !== void 0 && typeof params.ignore_case !== "boolean") throw invalid("ignore_case must be boolean");
3054
+ const context = intParam(params, "context", 0, 0, 50);
3055
+ const limit = intParam(params, "limit", 100, 1, 1e4);
3056
+ const maxLineChars = intParam(params, "max_line_chars", 2e3, 1, 1e5);
3057
+ const base = await searchBase(ctx, params);
3058
+ const cwd = base.isDir ? base.path : dirname5(base.path);
3059
+ const result = await rgGrep({
3060
+ rgPath: base.rg,
3061
+ cwd,
3062
+ target: base.isDir ? "." : basename5(base.path),
3063
+ signal: rpc.signal,
3064
+ pattern,
3065
+ glob,
3066
+ mode,
3067
+ context,
3068
+ ignoreCase: params.ignore_case === true,
3069
+ limit,
3070
+ maxLineChars,
3071
+ keep: (rel) => base.keep(cwd, rel),
3072
+ spawnImpl: deps.spawnImpl
3073
+ });
3074
+ return { base: cwd, ...result };
3075
+ },
3076
+ "pc.fs.upload": async (params, rpc) => {
3077
+ const ctx = parseCtx(params);
3078
+ const { path, cls } = await locate(ctx, params.path);
3079
+ enforce(cls, ctx.scope, path);
3080
+ const info = await statInfo(path);
3081
+ if (info.kind !== "file") throw invalid("\u53EA\u80FD\u4E0A\u4F20\u666E\u901A\u6587\u4EF6");
3082
+ if ((info.size ?? 0) > MAX_UPLOAD_BYTES) throw new RpcFailure(TOO_LARGE, "\u6587\u4EF6\u8D85\u8FC7 20 MB \u4E0A\u9650", { size: info.size, limit: MAX_UPLOAD_BYTES });
3083
+ const server = deps.getServer();
3084
+ if (!server) throw new Error("not paired");
3085
+ const version = (await currentVersion(path))?.version;
3086
+ try {
3087
+ const file = await uploadLocalFile({
3088
+ path,
3089
+ server,
3090
+ signal: rpc.signal,
3091
+ fetchImpl: deps.fetchImpl,
3092
+ cache: deps.cache,
3093
+ mimetype: mimeByExt(path)
3094
+ });
3095
+ return { file_id: file.id, name: file.name, mimetype: file.mimetype, size: file.size, ...version ? { version } : {} };
3096
+ } catch (e) {
3097
+ if (e instanceof UploadTooLarge) throw new RpcFailure(TOO_LARGE, e.message, { size: e.size, limit: e.limit });
3098
+ if (e instanceof UploadHttpError && e.status === 413) {
3099
+ throw new RpcFailure(TOO_LARGE, "\u670D\u52A1\u7AEF\u62D2\u7EDD\uFF1A\u6587\u4EF6\u8FC7\u5927", { size: info.size, limit: MAX_UPLOAD_BYTES });
3100
+ }
3101
+ throw e;
3102
+ }
3103
+ },
3104
+ // ── 写入(P2):先读后写的记录在服务端,这里按 expect 原子比对 ──────────────
3105
+ "pc.fs.write": async (params) => {
3106
+ const ctx = parseCtx(params);
3107
+ if (typeof params.content !== "string") throw invalid("content must be a string");
3108
+ const content = params.content;
3109
+ const expect = parseExpect(params.expect);
3110
+ const { path, cls } = await locateWrite(ctx, params.path);
3111
+ enforceWrite(cls, ctx.scope, path);
3112
+ const r = await locks.run([path], () => writeText(path, content, expect));
3113
+ return { path, ...r };
3114
+ },
3115
+ "pc.fs.edit": async (params) => {
3116
+ const ctx = parseCtx(params);
3117
+ const oldString = params.old_string;
3118
+ const newString = params.new_string;
3119
+ if (typeof oldString !== "string" || oldString === "") throw invalid("old_string must be a non-empty string");
3120
+ if (typeof newString !== "string") throw invalid("new_string must be a string");
3121
+ if (oldString === newString) throw invalid("old_string and new_string must differ");
3122
+ if (params.replace_all !== void 0 && typeof params.replace_all !== "boolean") throw invalid("replace_all must be boolean");
3123
+ const expect = parseExpect(params.expect);
3124
+ if (!("version" in expect)) throw invalid("edit needs expect.version");
3125
+ const { path, cls } = await locateWrite(ctx, params.path);
3126
+ enforceWrite(cls, ctx.scope, path);
3127
+ const r = await locks.run([path], () => editText(path, oldString, newString, params.replace_all === true, expect));
3128
+ return { path, ...r };
3129
+ },
3130
+ "pc.fs.trash": async (params) => {
3131
+ const ctx = parseCtx(params);
3132
+ if (!deps.trashItem) throw new Error("\u8FD9\u53F0\u7535\u8111\u4E0A\u4E0D\u80FD\u79FB\u8FDB\u5E9F\u7EB8\u7BD3");
3133
+ const { path, roots, sensitive, cls } = await locateWrite(ctx, params.path);
3134
+ enforceWrite(cls, ctx.scope, path);
3135
+ if (containsSensitive(path, sensitive)) throw new RpcFailure(PATH_SENSITIVE, `${path} \u91CC\u6709\u654F\u611F\u4F4D\u7F6E\uFF0C\u4E0D\u80FD\u79FB\u8FDB\u5E9F\u7EB8\u7BD3`);
3136
+ if (roots.some((r) => within(path, r.path) === "")) throw invalid(`${path} \u662F\u5DE5\u4F5C\u7A7A\u95F4\u7684\u6839\uFF0C\u4E0D\u80FD\u79FB\u8FDB\u5E9F\u7EB8\u7BD3`);
3137
+ const expect = params.expect === void 0 ? null : parseExpect(params.expect);
3138
+ await locks.run([path], async () => {
3139
+ const cur = await currentVersion(path);
3140
+ if (!cur) throw new RpcFailure(NOT_FOUND, `\u8DEF\u5F84\u4E0D\u5B58\u5728\uFF1A${path}`);
3141
+ if (cur.isFile) {
3142
+ if (!expect || !("version" in expect)) throw invalid("trashing a file needs expect.version");
3143
+ if (cur.version !== expect.version) throw new RpcFailure(STALE_VERSION, `${path} \u5728\u8BFB\u53D6\u4E4B\u540E\u88AB\u6539\u8FC7`);
3144
+ } else if (!cur.isDir) {
3145
+ throw invalid(`${path} \u4E0D\u662F\u666E\u901A\u6587\u4EF6\u6216\u76EE\u5F55`);
3146
+ }
3147
+ await deps.trashItem(path);
3148
+ });
3149
+ return { path };
3150
+ },
3151
+ "pc.fs.download": async (params, rpc) => {
3152
+ const ctx = parseCtx(params);
3153
+ if (!isValidFileId(params.file_id)) throw invalid("file_id must be a Leo file id");
3154
+ const fileId = params.file_id;
3155
+ if (!deps.fetchFile) throw new Error("not paired");
3156
+ const expect = parseExpect(params.expect);
3157
+ const { path, cls } = await locateWrite(ctx, params.path);
3158
+ enforceWrite(cls, ctx.scope, path);
3159
+ const r = await locks.run([path], async () => {
3160
+ const res = await deps.fetchFile(fileId);
3161
+ if (!res.ok || !res.body) throw new Error(`\u53D6\u6587\u4EF6\u5931\u8D25\uFF08HTTP ${res.status}\uFF09`);
3162
+ return downloadTo(path, res.body, expect, rpc.signal);
3163
+ });
3164
+ return { path, ...r };
3165
+ },
3166
+ "pc.open": async (params) => {
3167
+ if (params.url !== void 0) {
3168
+ if (typeof params.url !== "string" || !/^https?:\/\//i.test(params.url)) throw invalid("url must be http(s)");
3169
+ if (!deps.openExternal) throw new Error("\u8FD9\u53F0\u7535\u8111\u4E0A\u4E0D\u80FD\u6253\u5F00\u7F51\u5740");
3170
+ await deps.openExternal(params.url);
3171
+ return {};
3172
+ }
3173
+ const ctx = parseCtx(params);
3174
+ if (!deps.openPath) throw new Error("\u8FD9\u53F0\u7535\u8111\u4E0A\u4E0D\u80FD\u6253\u5F00\u6587\u4EF6");
3175
+ const { path, cls } = await locate(ctx, params.path);
3176
+ enforce(cls, ctx.scope, path);
3177
+ if (await isExecutable(path)) {
3178
+ throw new RpcFailure(OPEN_EXECUTABLE, `${path} \u662F\u5E94\u7528\u3001\u811A\u672C\u6216\u53EF\u6267\u884C\u6587\u4EF6\uFF0C\u6253\u5F00\u5B83\u7B49\u4E8E\u8FD0\u884C\u5B83\uFF0C\u4E0D\u80FD\u8FD9\u6837\u6253\u5F00`);
3179
+ }
3180
+ const error = await deps.openPath(path);
3181
+ if (error) throw new Error(`\u6253\u5F00\u5931\u8D25\uFF1A${error}`);
3182
+ return {};
3183
+ },
3184
+ // ── 命令(P3):在 Seatbelt 里跑,输出经 pc.exec.output 流回;后台与截断都在服务端 ──
3185
+ "pc.exec": async (params, rpc) => {
3186
+ const ctx = parseCtx(params);
3187
+ const command = params.command;
3188
+ if (typeof command !== "string" || command.trim() === "" || command.includes("\0")) throw invalid("command must be a non-empty string");
3189
+ const mode = params.sandbox;
3190
+ if (!EXEC_MODES.includes(mode)) throw invalid(`sandbox must be one of ${EXEC_MODES.join(", ")}`);
3191
+ const executor = deps.exec?.();
3192
+ if (!executor) throw new Error("\u8FD9\u53F0\u7535\u8111\u4E0A\u4E0D\u80FD\u8FD0\u884C\u547D\u4EE4\uFF08\u6CA1\u6709\u53EF\u7528\u7684\u6C99\u7BB1\u6216 shell\uFF09");
3193
+ const sensitive = await loadSensitive(home, deps.sensitiveExtra, fs);
3194
+ const roots = await rootsOf(ctx, sensitive);
3195
+ const rawWorkdir = optString(params, "workdir");
3196
+ const start2 = primaryRoot(roots);
3197
+ if (rawWorkdir === void 0 && !start2) throw invalid("\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u5DE5\u4F5C\u7A7A\u95F4\uFF0C\u8BF7\u7ED9\u51FA workdir");
3198
+ const cwd = await canonicalize(rawWorkdir === void 0 ? baseOfRoot(start2) : resolveInput(rawWorkdir, roots, home), fs);
3199
+ const cls = await classify(cwd, roots, sensitive, fs);
3200
+ if (cls === "sensitive") throw new RpcFailure(PATH_SENSITIVE, `\u654F\u611F\u8DEF\u5F84\uFF0C\u4E0D\u80FD\u4F5C\u4E3A\u5DE5\u4F5C\u76EE\u5F55\uFF1A${cwd}`);
3201
+ if (cls === "outside" && mode !== "escalated" && mode !== "unsandboxed") throw new RpcFailure(PATH_OUTSIDE, `\u5DE5\u4F5C\u76EE\u5F55\u5728\u5DE5\u4F5C\u7A7A\u95F4\u4E4B\u5916\uFF1A${cwd}`);
3202
+ if (!(await stat7(cwd)).isDirectory()) throw invalid(`workdir \u4E0D\u662F\u76EE\u5F55\uFF1A${cwd}`);
3203
+ return executor.run({
3204
+ sessionId: ctx.sessionId,
3205
+ command,
3206
+ cwd,
3207
+ mode,
3208
+ roots,
3209
+ sshAgent: params.ssh_agent === true,
3210
+ signal: rpc.signal,
3211
+ notify: (method, p) => rpc.notify(method, p)
3212
+ });
3213
+ }
3214
+ };
3215
+ }
3216
+
3217
+ // ../link/src/core/pc/exec.ts
3218
+ import { spawn as nodeSpawn4 } from "child_process";
3219
+ import { randomBytes as randomBytes2 } from "crypto";
3220
+ import { constants as constants3, createWriteStream as createWriteStream3 } from "fs";
3221
+ import { access, mkdir as mkdir3, readdir as readdir3, rm as rm3, stat as stat8 } from "fs/promises";
3222
+ import { join as join11 } from "path";
3223
+ var RETAIN_MS = 7 * 24 * 36e5;
3224
+ var shQuote = (s) => `'${s.replaceAll("'", `'\\''`)}'`;
3225
+ async function onPath(name, dirs) {
3226
+ for (const dir of dirs) {
3227
+ if (await access(join11(dir, name), constants3.X_OK).then(() => true, () => false)) return true;
3228
+ }
3229
+ return false;
3230
+ }
3231
+ function execEnv(base, sessionTmp, { scrub = true } = {}) {
3232
+ const env = {};
3233
+ const win = process.platform === "win32";
3234
+ for (const [k, v] of Object.entries(base)) {
3235
+ if (v === void 0 || scrub && SECRET_ENV_NAME.test(k) || k.startsWith("ELECTRON_")) continue;
3236
+ if (win && k !== "PATH" && k.toUpperCase() === "PATH") continue;
3237
+ env[k] = v;
3238
+ }
3239
+ env.PATH = loginPathEnv().PATH;
3240
+ env.TMPDIR = env.TMP = env.TEMP = sessionTmp;
3241
+ return env;
3242
+ }
3243
+ var spillDir = (dataDir, sessionId) => join11(dataDir, "spill", sessionId);
3244
+ var PcExecutor = class {
3245
+ /** 正在跑的命令,各自带着 shell 给的结束方式 */
3246
+ live = /* @__PURE__ */ new Map();
3247
+ lastSweep = 0;
3248
+ deps;
3249
+ constructor(deps) {
3250
+ this.deps = deps;
3251
+ }
3252
+ /** 正在跑的命令数 */
3253
+ get running() {
3254
+ return this.live.size;
3255
+ }
3256
+ /** 结束 Leo 启动的全部进程(/desktop 页、退出 App)。返回结束了几个 */
3257
+ killAll() {
3258
+ const n = this.live.size;
3259
+ for (const child of this.live.keys()) this.terminate(child);
3260
+ return n;
3261
+ }
3262
+ async run(req) {
3263
+ const { deps } = this;
3264
+ void this.sweep();
3265
+ const callId = randomBytes2(6).toString("hex");
3266
+ const sessionTmp = join11(deps.dataDir, "tmp", req.sessionId);
3267
+ const spillPath = join11(spillDir(deps.dataDir, req.sessionId), `${callId}.log`);
3268
+ await mkdir3(sessionTmp, { recursive: true, mode: 448 });
3269
+ await mkdir3(spillDir(deps.dataDir, req.sessionId), { recursive: true, mode: 448 });
3270
+ const shellEnv = deps.shellEnv ?? shellPath;
3271
+ await shellEnv.ready();
3272
+ const proc = await deps.shell.prepare({
3273
+ callId,
3274
+ command: req.command,
3275
+ mode: req.mode,
3276
+ roots: req.roots,
3277
+ sshAgent: req.sshAgent === true,
3278
+ sessionTmp,
3279
+ env: execEnv(deps.env ?? process.env, sessionTmp, { scrub: req.mode !== "unsandboxed" }),
3280
+ reapplyPath: shellEnv.get().length > 0
3281
+ });
3282
+ if (req.signal.aborted) {
3283
+ await proc.dispose();
3284
+ throw new RpcFailure(-32002, "Request cancelled");
3285
+ }
3286
+ const { spillsText } = deps.shell;
3287
+ const spill = createWriteStream3(spillPath, { mode: 384 });
3288
+ const child = (deps.spawnImpl ?? nodeSpawn4)(proc.file, proc.args, {
3289
+ cwd: req.cwd,
3290
+ env: proc.env,
3291
+ ...proc.spawnOptions,
3292
+ stdio: ["ignore", "pipe", "pipe"]
3293
+ });
3294
+ this.live.set(child, proc);
3295
+ req.notify("pc.exec.started", { call_id: callId, spill_path: spillPath });
3296
+ const onAbort = () => this.terminate(child);
3297
+ req.signal.addEventListener("abort", onAbort);
3298
+ let stderrTail = "";
3299
+ for (const stream of ["stdout", "stderr"]) {
3300
+ const decoder = deps.shell.decoder();
3301
+ const emit = (data) => {
3302
+ if (!data) return;
3303
+ if (stream === "stderr") stderrTail = (stderrTail + data).slice(-8192);
3304
+ if (spillsText) spill.write(data);
3305
+ req.notify("pc.exec.output", { stream, data });
3306
+ };
3307
+ child[stream]?.on("data", (chunk) => {
3308
+ if (!spillsText) spill.write(chunk);
3309
+ emit(decoder.write(chunk));
3310
+ });
3311
+ child[stream]?.on("end", () => emit(decoder.end()));
3312
+ }
3313
+ try {
3314
+ const { code, signal } = await new Promise((resolve3, reject) => {
3315
+ child.on("error", (e) => reject(new RpcFailure(-32603, `\u542F\u52A8\u547D\u4EE4\u5931\u8D25\uFF1A${e.message}`)));
3316
+ child.on("close", (code2, signal2) => resolve3({ code: code2, signal: signal2 }));
3317
+ });
3318
+ await new Promise((resolve3) => spill.end(resolve3));
3319
+ const { denied, sshAgentDenied } = await proc.denials(code, stderrTail);
3320
+ const result = { exit_code: code, signal, spill_path: spillPath, sandbox_denied: denied, ssh_agent_denied: sshAgentDenied };
3321
+ const missing = code === 127 ? deps.shell.missingCommand(stderrTail) : void 0;
3322
+ if (missing && await shellEnv.refresh() !== null) {
3323
+ result.env_refreshed = await onPath(missing, [...shellEnv.get(), ...loginPathEnv().PATH.split(":")]);
3324
+ }
3325
+ return result;
3326
+ } finally {
3327
+ req.signal.removeEventListener("abort", onAbort);
3328
+ this.live.delete(child);
3329
+ if (!spill.closed) spill.destroy();
3330
+ await proc.dispose();
3331
+ }
3332
+ }
3333
+ terminate(child) {
3334
+ if (child.pid === void 0 || child.exitCode !== null || child.signalCode !== null) return;
3335
+ this.live.get(child)?.kill(child);
3336
+ }
3337
+ /** 7 天前的会话临时目录与溢出文件(每小时最多扫一次,best-effort) */
3338
+ async sweep(now = Date.now()) {
3339
+ if (now - this.lastSweep < 36e5) return;
3340
+ this.lastSweep = now;
3341
+ for (const sub of ["tmp", "spill"]) {
3342
+ const dir = join11(this.deps.dataDir, sub);
3343
+ const names = await readdir3(dir).catch(() => []);
3344
+ for (const name of names) {
3345
+ const p = join11(dir, name);
3346
+ const st = await stat8(p).catch(() => null);
3347
+ if (st && now - st.mtimeMs > RETAIN_MS) await rm3(p, { recursive: true, force: true }).catch(() => {
3348
+ });
3349
+ }
3350
+ }
3351
+ }
3352
+ };
3353
+
3354
+ // ../link/src/core/runtime.ts
3355
+ function safeExternalUrl(url) {
3356
+ try {
3357
+ const u = new URL(url);
3358
+ return u.protocol === "https:" || u.protocol === "http:" ? u.toString() : null;
3359
+ } catch {
3360
+ return null;
3361
+ }
3362
+ }
3363
+ function createLinkRuntime(host, makeApp) {
3364
+ const workDir = join12(host.dataDir, "work");
3365
+ mkdirSync3(workDir, { recursive: true });
3366
+ const fileCache = new FileCache(join12(host.dataDir, "cache", "files"));
3367
+ mkdirSync3(fileCache.root, { recursive: true });
3368
+ const leoFolder = new LeoFolder(host.leoFolder);
3369
+ const pcDataDir = join12(host.dataDir, "pc");
3370
+ const sensitiveExtra = [
3371
+ // 例外:pc.exec 的输出溢出文件(pc/spill/),文件工具要能读(pc_read 分页看完整输出)
3372
+ { path: host.dataDir, allow: (rel) => rel.startsWith(join12("pc", "spill") + sep2) },
3373
+ // 另一个外壳(桌面端 / leo-link 的正式版、开发版)的数据目录:别人的配对凭证,没有例外
3374
+ ...otherShellDataDirs(host.dataDir, homedir5()),
3375
+ // 改过配置目录的 agent CLI 的登录凭据(默认位置在 rules.ts 的清单里)
3376
+ ...envCredentialPaths(process.env)
3377
+ ];
3378
+ let rgPath = null;
3379
+ let commands = null;
3380
+ let executor = null;
3381
+ const server = () => app.getServer();
3382
+ const fetchServerFile = (id) => {
3383
+ const s = server();
3384
+ if (!s) return Promise.reject(new Error("not paired"));
3385
+ return host.fetch(`${s.baseUrl}/api/v2/files/${encodeURIComponent(id)}`, { headers: { Authorization: `Bearer ${s.token}` } });
3386
+ };
3387
+ const app = makeApp({
3388
+ platform: process.platform,
3389
+ arch: process.arch,
3390
+ connectWs: host.connectWs,
3391
+ // 借出本机 CLI:program 路径由本机探测结果解析,服务端只传名字
3392
+ handlers: {
3393
+ ...createProcessHandlers({
3394
+ resolveProgram: (program) => app.cliPath(program),
3395
+ cwd: workDir,
3396
+ cache: fileCache,
3397
+ fetchFile: fetchServerFile,
3398
+ // 公开资源:不带 bearer;重定向一律拒绝,免得被带去别的源
3399
+ fetchAsset: (path) => {
3400
+ const s = server();
3401
+ if (!s) return Promise.reject(new Error("not paired"));
3402
+ return host.fetch(`${s.baseUrl}${path}`, { redirect: "error" });
3403
+ }
3404
+ }),
3405
+ ...createCodexHandlers({
3406
+ resolveProgram: (program) => app.cliPath(program),
3407
+ cwd: workDir,
3408
+ cache: fileCache,
3409
+ getMcpUrl: () => `${server().baseUrl}/mcp/`,
3410
+ getServer: server,
3411
+ fetchImpl: host.fetch
3412
+ }),
3413
+ // 操作这台电脑:读写文件。工作空间由服务端随调用带来,这里每次重新检查;硬边界是开关、敏感清单与受保护路径
3414
+ ...createPcHandlers({
3415
+ leoFolder,
3416
+ sensitiveExtra,
3417
+ exec: () => executor,
3418
+ rgPath: () => rgPath,
3419
+ getServer: server,
3420
+ fetchImpl: host.fetch,
3421
+ cache: fileCache,
3422
+ fetchFile: fetchServerFile,
3423
+ trashItem: host.trashItem,
3424
+ openPath: host.openPath,
3425
+ openExternal: (url) => {
3426
+ const safe = safeExternalUrl(url);
3427
+ return safe ? host.openExternal(safe) : Promise.resolve();
3428
+ }
3429
+ })
3430
+ },
3431
+ stageRoot: fileCache.root,
3432
+ rgAvailable: () => rgPath !== null,
3433
+ pcDefaultRoot: () => leoFolder.path ?? leoFolder.ensure(),
3434
+ pcCommands: () => commands?.hello ?? null,
3435
+ onState: (state) => {
3436
+ if (state.toggles.userpc) {
3437
+ leoFolder.ensure();
3438
+ commands?.monitor?.start();
3439
+ } else {
3440
+ commands?.monitor?.stop();
3441
+ }
3442
+ }
3443
+ });
3444
+ return {
3445
+ app,
3446
+ fileCache,
3447
+ async start() {
3448
+ void shellPath.refresh();
3449
+ rgPath = await host.resolveRipgrep();
3450
+ commands = await host.platform.commands({ home: await realpath6(homedir5()), sensitiveExtra, locale: host.locale?.() });
3451
+ if (commands) executor = new PcExecutor({ dataDir: pcDataDir, shell: commands });
3452
+ await app.start();
3453
+ },
3454
+ async stop() {
3455
+ executor?.killAll();
3456
+ commands?.monitor?.stop();
3457
+ await app.stop();
3458
+ },
3459
+ killPcProcesses: () => executor?.killAll() ?? 0
3460
+ };
3461
+ }
3462
+
3463
+ // src/commands.ts
3464
+ import { existsSync as existsSync3 } from "fs";
3465
+
3466
+ // src/args.ts
3467
+ import { parseArgs as parseFlags } from "util";
3468
+ var UsageError = class extends Error {
3469
+ };
3470
+ var USAGE = `\u7528\u6CD5\uFF1Aleo-link [\u547D\u4EE4]
3471
+
3472
+ \uFF08\u4E0D\u5E26\u547D\u4EE4\uFF09 \u67E5\u770B\u72B6\u6001\uFF1A\u914D\u5BF9\u3001\u5728\u7EBF\u3001\u80FD\u529B\u3001\u540E\u53F0\u670D\u52A1
3473
+ setup \u914D\u7F6E\u5411\u5BFC\uFF1A\u670D\u52A1\u5668\u5730\u5740 \u2192 \u914D\u5BF9\u7801 \u2192 \u8981\u5F00\u7684\u80FD\u529B \u2192 \u88C5\u597D\u5E76\u542F\u52A8\u540E\u53F0\u670D\u52A1\uFF1B\u6539\u8BBE\u7F6E\u4E5F\u662F\u91CD\u65B0\u8FD0\u884C\u5B83
3474
+ unpair \u89E3\u9664\u914D\u5BF9\uFF1A\u5411\u670D\u52A1\u7AEF\u540A\u9500\u672C\u673A\u51ED\u8BC1\uFF0C\u5E76\u5378\u6389\u540E\u53F0\u670D\u52A1\uFF08\u518D\u914D\u5BF9\u5C31\u662F\u4E00\u53F0\u65B0\u8BBE\u5907\uFF09
3475
+ start \u542F\u52A8\u540E\u53F0\u670D\u52A1\uFF0C\u767B\u5F55\u540E\u81EA\u52A8\u8FD0\u884C\uFF08\u914D\u5BF9\u4E0D\u53D8\uFF09
3476
+ stop \u505C\u4E0B\u540E\u53F0\u670D\u52A1\uFF0C\u91CD\u542F\u540E\u4E5F\u4E0D\u4F1A\u81EA\u5DF1\u8D77\u6765\uFF08\u914D\u5BF9\u4E0D\u53D8\uFF09
3477
+ logs \u6301\u7EED\u67E5\u770B\u540E\u53F0\u670D\u52A1\u7684\u65E5\u5FD7\uFF08Ctrl-C \u9000\u51FA\uFF09
3478
+
3479
+ setup \u7684\u53C2\u6570\uFF08\u7ED9\u4E86\u7684\u90A3\u4E00\u6B65\u5C31\u4E0D\u95EE\uFF1B\u4E0D\u5728\u7EC8\u7AEF\u91CC\u8FD0\u884C\u65F6\uFF0C\u7F3A\u7684\u53D6\u5F53\u524D\u503C\uFF09\uFF1A
3480
+ --server <\u5730\u5740> Leo \u670D\u52A1\u5668\u5730\u5740
3481
+ --code <\u914D\u5BF9\u7801> \u914D\u5BF9\u7801\uFF0C\u5728\u7F51\u9875\u7684 \u914D\u7F6E \u2192 \u5BA2\u6237\u7AEF \u2192 \u8BBE\u5907 \u91CC
3482
+ --name <\u8BBE\u5907\u540D> \u914D\u5BF9\u65F6\u7528\u7684\u8BBE\u5907\u540D\uFF0C\u9ED8\u8BA4\u662F\u4E3B\u673A\u540D
3483
+ --cli | --no-cli \u501F\u51FA\u672C\u673A\u7684 Claude Code / Codex
3484
+ --userpc | --no-userpc \u5141\u8BB8 Leo \u64CD\u4F5C\u8FD9\u53F0\u7535\u8111
3485
+ -y, --yes \u90FD\u4E0D\u95EE\uFF0C\u6CA1\u7ED9\u7684\u53D6\u5F53\u524D\u503C
3486
+
3487
+ -h, --help \u663E\u793A\u672C\u5E2E\u52A9
3488
+ -v, --version \u663E\u793A\u7248\u672C`;
3489
+ function flags(name, args, options) {
3490
+ try {
3491
+ return parseFlags({ args, options, allowPositionals: true, strict: true });
3492
+ } catch (e) {
3493
+ throw new UsageError(`${name}\uFF1A${e.message}`);
3494
+ }
3495
+ }
3496
+ function noPositionals(name, got) {
3497
+ if (got.length) throw new UsageError(`${name} \u4E0D\u63A5\u53D7\u53C2\u6570\uFF1A${got.join(" ")}`);
3498
+ }
3499
+ function tri(name, on, off) {
3500
+ if (on && off) throw new UsageError(`--${name} \u4E0E --no-${name} \u4E0D\u80FD\u540C\u65F6\u7528`);
3501
+ return on ? true : off ? false : void 0;
3502
+ }
3503
+ function parseArgs(argv) {
3504
+ const [name, ...rest] = argv;
3505
+ if (name === void 0) return { name: "status" };
3506
+ if (name === "help" || argv.includes("--help") || argv.includes("-h")) return { name: "help" };
3507
+ if (name === "--version" || name === "-v") return { name: "version" };
3508
+ switch (name) {
3509
+ case "setup": {
3510
+ const { values, positionals } = flags(name, rest, {
3511
+ server: { type: "string" },
3512
+ code: { type: "string" },
3513
+ name: { type: "string" },
3514
+ cli: { type: "boolean" },
3515
+ "no-cli": { type: "boolean" },
3516
+ userpc: { type: "boolean" },
3517
+ "no-userpc": { type: "boolean" },
3518
+ yes: { type: "boolean", short: "y" }
3519
+ });
3520
+ noPositionals(name, positionals);
3521
+ for (const key of ["server", "code", "name"]) {
3522
+ if (values[key] !== void 0 && !values[key].trim()) throw new UsageError(`--${key} \u4E0D\u80FD\u4E3A\u7A7A`);
3523
+ }
3524
+ const toggles = {};
3525
+ const cli = tri("cli", values.cli, values["no-cli"]);
3526
+ const userpc = tri("userpc", values.userpc, values["no-userpc"]);
3527
+ if (cli !== void 0) toggles.cli = cli;
3528
+ if (userpc !== void 0) toggles.userpc = userpc;
3529
+ return {
3530
+ name,
3531
+ ...values.server !== void 0 ? { server: values.server } : {},
3532
+ ...values.code !== void 0 ? { code: values.code } : {},
3533
+ ...values.name !== void 0 ? { deviceName: values.name } : {},
3534
+ toggles,
3535
+ yes: values.yes ?? false
3536
+ };
3537
+ }
3538
+ case "logs":
3539
+ case "start":
3540
+ case "stop":
3541
+ case "unpair":
3542
+ case "daemon":
3543
+ noPositionals(name, flags(name, rest, {}).positionals);
3544
+ return { name };
3545
+ default:
3546
+ throw new UsageError(`\u672A\u77E5\u547D\u4EE4\uFF1A${name}`);
3547
+ }
3548
+ }
3549
+
3550
+ // src/log.ts
3551
+ import { statSync, truncateSync } from "fs";
3552
+ var onOff = (v) => v ? "\u5F00" : "\u5173";
3553
+ function describeCli(cli) {
3554
+ const one = (label, d) => `${label}\uFF1A${d.found ? `${d.version ?? "\u7248\u672C\u672A\u77E5"}\uFF08${d.path ?? "?"}\uFF09` : "\u672A\u627E\u5230"}`;
3555
+ return `${one("Claude Code", cli.claude)}\u3000${one("Codex", cli.codex)}`;
3556
+ }
3557
+ function describeState(s) {
3558
+ return [
3559
+ `\u8BBE\u5907\uFF1A${s.deviceName}\uFF08${s.paired ? `\u5DF2\u914D\u5BF9\u5230 ${s.serverUrl}` : "\u672A\u914D\u5BF9"}\uFF09`,
3560
+ `\u501F\u51FA Claude Code / Codex\uFF1A${onOff(s.toggles.cli)}\u3000\u64CD\u4F5C\u8FD9\u53F0\u7535\u8111\uFF1A${onOff(s.toggles.userpc)}`,
3561
+ describeCli(s.cli)
3562
+ ];
3563
+ }
3564
+ function describeChange(prev, next) {
3565
+ if (!prev) return [];
3566
+ const lines = [];
3567
+ if (prev.link !== next.link || next.linkError && prev.linkError !== next.linkError) {
3568
+ if (next.link === "online") lines.push(`\u5DF2\u8FDE\u63A5 ${next.serverUrl}`);
3569
+ else if (next.link === "connecting") lines.push("\u8FDE\u63A5\u4E2D\u2026");
3570
+ else if (next.linkError) lines.push(`${prev.link === "online" ? "\u5DF2\u65AD\u5F00" : "\u8FDE\u63A5\u5931\u8D25"}\uFF1A${next.linkError}`);
3571
+ else lines.push("\u5DF2\u65AD\u5F00");
3572
+ }
3573
+ if (next.lastNotice && next.lastNotice !== prev.lastNotice) lines.push(next.lastNotice);
3574
+ if (JSON.stringify(prev.cli) !== JSON.stringify(next.cli)) lines.push(describeCli(next.cli));
3575
+ return lines;
3576
+ }
3577
+ var pad = (n) => String(n).padStart(2, "0");
3578
+ function stamp(message, now = /* @__PURE__ */ new Date()) {
3579
+ const d = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
3580
+ return `${d} ${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())} ${message}`;
3581
+ }
3582
+ var QUIET = /* @__PURE__ */ new Set(["process.write", "process.codex_write", "process.close_stdin"]);
3583
+ function withRequestLog(handlers, log, now = Date.now) {
3584
+ return Object.fromEntries(
3585
+ Object.entries(handlers).map(([method, handler]) => {
3586
+ if (QUIET.has(method)) return [method, handler];
3587
+ return [
3588
+ method,
3589
+ async (params, ctx) => {
3590
+ const started = now();
3591
+ try {
3592
+ const result = await handler(params, ctx);
3593
+ log(`${method} ${now() - started}ms`);
3594
+ return result;
3595
+ } catch (e) {
3596
+ log(`${method} \u5931\u8D25\uFF1A${e.message}`);
3597
+ throw e;
3598
+ }
3599
+ }
3600
+ ];
3601
+ })
3602
+ );
3603
+ }
3604
+ function trimLogFile(path, maxBytes = 10 * 1024 * 1024) {
3605
+ try {
3606
+ if (statSync(path).size > maxBytes) truncateSync(path, 0);
3607
+ } catch {
3608
+ }
3609
+ }
3610
+
3611
+ // src/prompt.ts
3612
+ import { createInterface } from "readline";
3613
+ var PromptClosed = class extends Error {
3614
+ constructor() {
3615
+ super("\u5DF2\u53D6\u6D88");
3616
+ }
3617
+ };
3618
+ function makePrompter({ input = process.stdin, output = process.stderr } = {}) {
3619
+ const interactive = Boolean(input.isTTY);
3620
+ let rl = null;
3621
+ let closed = false;
3622
+ const line = (prompt) => {
3623
+ if (closed) return Promise.reject(new PromptClosed());
3624
+ rl ??= createInterface({ input, output });
3625
+ const current = rl;
3626
+ return new Promise((resolve3, reject) => {
3627
+ const onClose = () => {
3628
+ closed = true;
3629
+ reject(new PromptClosed());
3630
+ };
3631
+ current.once("close", onClose);
3632
+ current.question(prompt, (answer) => {
3633
+ current.off("close", onClose);
3634
+ resolve3(answer);
3635
+ });
3636
+ });
3637
+ };
3638
+ return {
3639
+ interactive,
3640
+ async ask(question, fallback) {
3641
+ if (!interactive) return fallback ?? "";
3642
+ const answer = (await line(fallback ? `${question} [${fallback}]: ` : `${question}: `)).trim();
3643
+ return answer || (fallback ?? "");
3644
+ },
3645
+ async yesNo(question, fallback) {
3646
+ if (!interactive) return fallback;
3647
+ for (; ; ) {
3648
+ const answer = (await line(`${question} ${fallback ? "[Y/n]" : "[y/N]"} `)).trim().toLowerCase();
3649
+ if (!answer) return fallback;
3650
+ if (answer === "y" || answer === "yes") return true;
3651
+ if (answer === "n" || answer === "no") return false;
3652
+ }
3653
+ },
3654
+ close() {
3655
+ rl?.close();
3656
+ rl = null;
3657
+ }
3658
+ };
3659
+ }
3660
+
3661
+ // src/commands.ts
3662
+ var NOT_CONFIGURED = "\u8FD8\u6CA1\u6709\u914D\u7F6E\uFF1A\u8FD0\u884C leo-link setup";
3663
+ function banner(ctx) {
3664
+ return ctx.paths.channel === "development" ? `leo-link ${ctx.version}\uFF08\u5F00\u53D1\u7248\uFF0C\u6570\u636E\u5728 ${ctx.paths.dataDir}\uFF09` : `leo-link ${ctx.version}`;
3665
+ }
3666
+ function warnDesktop(ctx, print) {
3667
+ const desktop = parseLinkConfig(readConfigFile(ctx.paths.desktopConfigPath), "");
3668
+ if (!isPaired(desktop)) return;
3669
+ print(`\u26A0 \u8FD9\u53F0 Mac \u4E0A\u7684 Leo \u684C\u9762\u7AEF\u4E5F\u914D\u5BF9\u5230\u4E86 ${desktop.serverUrl}\u3002\u4E24\u4E2A\u540C\u65F6\u8FD0\u884C\u4F1A\u88AB\u670D\u52A1\u7AEF\u5F53\u6210\u4E24\u53F0\u7535\u8111\uFF1A\u8BF7\u4E8C\u9009\u4E00\uFF08\u5728\u684C\u9762\u7AEF\u91CC\u89E3\u9664\u914D\u5BF9\u5E76\u9000\u51FA\u5B83\uFF0C\u6216\u4E0D\u7528 leo-link\uFF09`);
3670
+ }
3671
+ function foundClis(cli) {
3672
+ const found = [
3673
+ ...cli.claude.found ? [`Claude Code ${cli.claude.version ?? ""}`.trim()] : [],
3674
+ ...cli.codex.found ? [`Codex ${cli.codex.version ?? ""}`.trim()] : []
3675
+ ];
3676
+ return found.length ? `\uFF08\u672C\u673A\u627E\u5230 ${found.join("\u3001")}\uFF09` : "\uFF08\u672C\u673A\u6CA1\u627E\u5230 claude / codex\uFF0C\u5F00\u4E86\u4E5F\u501F\u4E0D\u51FA\u53BB\uFF09";
3677
+ }
3678
+ async function askCode(ctx, ask) {
3679
+ if (!ask) return "";
3680
+ for (; ; ) {
3681
+ const code = await ctx.prompter.ask("\u914D\u5BF9\u7801\uFF08\u5728\u7F51\u9875\u7684 \u914D\u7F6E \u2192 \u5BA2\u6237\u7AEF \u2192 \u8BBE\u5907 \u91CC\uFF09");
3682
+ if (code) return code;
3683
+ }
3684
+ }
3685
+ async function setup(cmd, ctx) {
3686
+ const problem = await ctx.service.installable();
3687
+ if (problem) {
3688
+ ctx.out(problem);
3689
+ return 1;
3690
+ }
3691
+ ctx.out(banner(ctx));
3692
+ warnDesktop(ctx, ctx.out);
3693
+ const ask = ctx.prompter.interactive && !cmd.yes;
3694
+ const { app } = ctx.createRuntime({});
3695
+ let state = app.getState();
3696
+ let serverUrl;
3697
+ for (; ; ) {
3698
+ const input = cmd.server ?? (ask ? await ctx.prompter.ask("Leo \u670D\u52A1\u5668\u5730\u5740", state.serverUrl ?? void 0) : state.serverUrl ?? "");
3699
+ if (!input) {
3700
+ if (ask) continue;
3701
+ ctx.out("\u9700\u8981\u670D\u52A1\u5668\u5730\u5740\uFF1A\u7528 --server <\u5730\u5740> \u7ED9\u51FA\uFF0C\u6216\u5728\u7EC8\u7AEF\u91CC\u8FD0\u884C leo-link setup");
3702
+ return 1;
3703
+ }
3704
+ try {
3705
+ serverUrl = normalizeServerUrl(input);
3706
+ break;
3707
+ } catch (e) {
3708
+ ctx.out(`\u5730\u5740\u4E0D\u5BF9\uFF1A${e.message}`);
3709
+ if (!ask || cmd.server !== void 0) return 1;
3710
+ }
3711
+ }
3712
+ const needPair = cmd.code !== void 0 || !state.paired || serverUrl !== state.serverUrl;
3713
+ let deviceName = state.deviceName;
3714
+ let code = "";
3715
+ if (needPair) {
3716
+ deviceName = cmd.deviceName ?? (ask ? await ctx.prompter.ask("\u8BBE\u5907\u540D\uFF08\u5728 Leo \u91CC\u663E\u793A\uFF09", state.deviceName) : state.deviceName);
3717
+ code = cmd.code ?? await askCode(ctx, ask);
3718
+ if (!code) {
3719
+ ctx.out("\u9700\u8981\u914D\u5BF9\u7801\uFF1A\u7528 --code <\u914D\u5BF9\u7801> \u7ED9\u51FA\uFF08\u5728\u7F51\u9875\u7684 \u914D\u7F6E \u2192 \u5BA2\u6237\u7AEF \u2192 \u8BBE\u5907 \u91CC\uFF09");
3720
+ return 1;
3721
+ }
3722
+ }
3723
+ ctx.refreshShellPath();
3724
+ state = await app.redetectCli();
3725
+ const current = serverUrl === state.serverUrl ? state.toggles : DEFAULT_TOGGLES;
3726
+ const cli = cmd.toggles.cli ?? (ask ? await ctx.prompter.yesNo(`\u501F\u51FA\u672C\u673A\u7684 Claude Code / Codex \u7ED9 Leo \u5F53\u6A21\u578B\u6765\u6E90\uFF1F${foundClis(state.cli)}`, current.cli) : current.cli);
3727
+ const userpc = cmd.toggles.userpc ?? (ask ? await ctx.prompter.yesNo("\u5141\u8BB8 Leo \u64CD\u4F5C\u8FD9\u53F0\u7535\u8111\uFF1F\uFF08\u8BFB\u5199\u4F60\u5728\u804A\u5929\u91CC\u9009\u7684\u6587\u4EF6\u5939\uFF0C\u547D\u4EE4\u5728\u6C99\u7BB1\u91CC\u8FD0\u884C\uFF09", current.userpc) : current.userpc);
3728
+ if (needPair) {
3729
+ for (; ; ) {
3730
+ try {
3731
+ await app.pair({ serverUrl, code, deviceName });
3732
+ break;
3733
+ } catch (e) {
3734
+ ctx.out(`\u914D\u5BF9\u5931\u8D25\uFF1A${e.message}`);
3735
+ if (!ask || cmd.code !== void 0) return 1;
3736
+ code = await askCode(ctx, ask);
3737
+ } finally {
3738
+ await app.stop();
3739
+ }
3740
+ }
3741
+ state = app.getState();
3742
+ ctx.out(`\u5DF2\u914D\u5BF9\u5230 ${state.serverUrl}\uFF08\u8BBE\u5907\u540D\uFF1A${state.deviceName}\uFF09`);
3743
+ if (state.lastNotice) ctx.out(state.lastNotice);
3744
+ }
3745
+ await app.setToggle("cli", cli);
3746
+ await app.setToggle("userpc", userpc);
3747
+ for (const line of await ctx.service.install()) ctx.out(line);
3748
+ ctx.out(describeState(app.getState())[1]);
3749
+ ctx.out("\u67E5\u770B\u72B6\u6001\uFF1Aleo-link\uFF1B\u770B\u65E5\u5FD7\uFF1Aleo-link logs");
3750
+ return 0;
3751
+ }
3752
+ async function onlineLine(fetchImpl, server, deviceId) {
3753
+ try {
3754
+ const res = await fetchImpl(`${server.baseUrl}/api/v2/config/devices`, {
3755
+ headers: { Authorization: `Bearer ${server.token}` },
3756
+ signal: AbortSignal.timeout(5e3)
3757
+ });
3758
+ if (res.status === 401) return "\u670D\u52A1\u7AEF\uFF1A\u4E0D\u8BA4\u8FD9\u53F0\u8BBE\u5907\u7684\u51ED\u8BC1\uFF08\u53EF\u80FD\u5DF2\u5728\u914D\u7F6E\u9875\u5220\u9664\uFF09\uFF0C\u8BF7\u91CD\u65B0\u8FD0\u884C leo-link setup";
3759
+ if (!res.ok) return `\u670D\u52A1\u7AEF\uFF1A\u67E5\u8BE2\u5931\u8D25\uFF08HTTP ${res.status}\uFF09`;
3760
+ const body = await res.json();
3761
+ const me = body.devices?.find((d) => d.device_id === deviceId);
3762
+ if (!me) return "\u670D\u52A1\u7AEF\uFF1A\u627E\u4E0D\u5230\u8FD9\u53F0\u8BBE\u5907\uFF08\u53EF\u80FD\u5DF2\u5728\u914D\u7F6E\u9875\u5220\u9664\uFF09\uFF0C\u8BF7\u91CD\u65B0\u8FD0\u884C leo-link setup";
3763
+ return me.online ? "\u670D\u52A1\u7AEF\uFF1A\u5728\u7EBF" : "\u670D\u52A1\u7AEF\uFF1A\u79BB\u7EBF";
3764
+ } catch (e) {
3765
+ return `\u670D\u52A1\u7AEF\uFF1A\u67E5\u8BE2\u5931\u8D25\uFF08${e.message}\uFF09`;
3766
+ }
3767
+ }
3768
+ async function status(ctx) {
3769
+ ctx.out(banner(ctx));
3770
+ warnDesktop(ctx, ctx.out);
3771
+ const { app, host } = ctx.createRuntime({});
3772
+ const initial = app.getState();
3773
+ if (!initial.paired) {
3774
+ if (initial.lastNotice) ctx.out(initial.lastNotice);
3775
+ ctx.out(NOT_CONFIGURED);
3776
+ return 0;
3777
+ }
3778
+ ctx.refreshShellPath();
3779
+ const state = await app.redetectCli();
3780
+ for (const line of describeState(state)) ctx.out(line);
3781
+ const rg = await host.resolveRipgrep();
3782
+ ctx.out(rg ? `ripgrep\uFF1A${rg}` : "ripgrep\uFF1A\u672A\u627E\u5230\uFF08pc \u7684 glob / grep \u4E0D\u53EF\u7528\uFF09");
3783
+ const shell = await host.platform.commands({ home: ctx.home, sensitiveExtra: [] });
3784
+ ctx.out(shell ? "\u547D\u4EE4\u6C99\u7BB1\uFF1ASeatbelt \u53EF\u7528" : "\u547D\u4EE4\u6C99\u7BB1\uFF1A\u4E0D\u53EF\u7528\uFF08\u670D\u52A1\u7AEF\u4E0D\u63D0\u4F9B pc_bash\uFF09");
3785
+ ctx.out(await onlineLine(ctx.fetch, app.getServer(), state.deviceId));
3786
+ for (const line of await ctx.service.status()) ctx.out(line);
3787
+ ctx.out("\u770B\u65E5\u5FD7\uFF1Aleo-link logs\u3000\u6539\u8BBE\u7F6E\uFF1Aleo-link setup");
3788
+ return 0;
3789
+ }
3790
+ async function logs(ctx) {
3791
+ if (!existsSync3(ctx.paths.logPath)) {
3792
+ ctx.out("\u8FD8\u6CA1\u6709\u65E5\u5FD7\uFF1A\u540E\u53F0\u670D\u52A1\u8FD8\u6CA1\u8FD0\u884C\u8FC7\uFF08\u5148\u8FD0\u884C leo-link setup\uFF09");
3793
+ return 1;
3794
+ }
3795
+ return ctx.followLog(ctx.paths.logPath);
3796
+ }
3797
+ async function start(ctx) {
3798
+ const problem = await ctx.service.installable();
3799
+ if (problem) {
3800
+ ctx.out(problem);
3801
+ return 1;
3802
+ }
3803
+ if (!ctx.createRuntime({}).app.getState().paired) {
3804
+ ctx.out(NOT_CONFIGURED);
3805
+ return 1;
3806
+ }
3807
+ for (const line of await ctx.service.install()) ctx.out(line);
3808
+ ctx.out("\u767B\u5F55\u540E\u4F1A\u81EA\u52A8\u8FD0\u884C\uFF1B\u505C\u4E0B\u7528 leo-link stop");
3809
+ return 0;
3810
+ }
3811
+ async function stop(ctx) {
3812
+ ctx.out(await ctx.service.uninstall() ? "\u540E\u53F0\u670D\u52A1\u5DF2\u505C\u4E0B\uFF0C\u91CD\u542F\u540E\u4E5F\u4E0D\u4F1A\u81EA\u5DF1\u8D77\u6765\uFF1B\u6062\u590D\u7528 leo-link start" : "\u540E\u53F0\u670D\u52A1\u672C\u6765\u5C31\u6CA1\u5728\u8FD0\u884C");
3813
+ return 0;
3814
+ }
3815
+ async function unpair(ctx) {
3816
+ const stopped = await ctx.service.uninstall();
3817
+ const { app } = ctx.createRuntime({});
3818
+ if (app.getState().paired) {
3819
+ const state = await app.unpair();
3820
+ if (state.lastNotice) ctx.out(state.lastNotice);
3821
+ } else {
3822
+ ctx.out("\u672C\u6765\u5C31\u6CA1\u6709\u914D\u5BF9");
3823
+ }
3824
+ if (stopped) ctx.out("\u540E\u53F0\u670D\u52A1\u5DF2\u505C\u4E0B");
3825
+ return 0;
3826
+ }
3827
+ async function daemon(ctx) {
3828
+ let prev = null;
3829
+ const runtime = ctx.createRuntime({
3830
+ logRequests: true,
3831
+ onState: (state) => {
3832
+ for (const line of describeChange(prev, state)) ctx.log(line);
3833
+ prev = state;
3834
+ }
3835
+ });
3836
+ const { app } = runtime;
3837
+ ctx.log(banner(ctx));
3838
+ warnDesktop(ctx, ctx.log);
3839
+ const initial = app.getState();
3840
+ if (!initial.paired) {
3841
+ if (initial.lastNotice) ctx.log(initial.lastNotice);
3842
+ ctx.log(NOT_CONFIGURED);
3843
+ return 0;
3844
+ }
3845
+ const [device, toggles] = describeState(initial);
3846
+ ctx.log(device);
3847
+ ctx.log(toggles);
3848
+ prev = initial;
3849
+ trimLogFile(ctx.paths.logPath);
3850
+ await runtime.start();
3851
+ const userpc = app.hello().capabilities.userpc;
3852
+ ctx.log(userpc.sandbox === "seatbelt" ? "\u547D\u4EE4\u6C99\u7BB1\uFF1ASeatbelt" : "\u547D\u4EE4\u6C99\u7BB1\uFF1A\u4E0D\u53EF\u7528\uFF08\u670D\u52A1\u7AEF\u4E0D\u63D0\u4F9B pc_bash\uFF09");
3853
+ if (userpc.rg === false) ctx.log("ripgrep\uFF1A\u672A\u627E\u5230\uFF08pc \u7684 glob / grep \u4E0D\u53EF\u7528\uFF09");
3854
+ const signal = await ctx.waitForSignal();
3855
+ ctx.log(`\u6536\u5230 ${signal}\uFF0C\u6B63\u5728\u9000\u51FA\u2026`);
3856
+ await runtime.stop();
3857
+ return 0;
3858
+ }
3859
+ async function run(argv, ctx) {
3860
+ let cmd;
3861
+ try {
3862
+ cmd = parseArgs(argv);
3863
+ } catch (e) {
3864
+ if (!(e instanceof UsageError)) throw e;
3865
+ ctx.out(e.message);
3866
+ ctx.out(USAGE);
3867
+ return 2;
3868
+ }
3869
+ try {
3870
+ switch (cmd.name) {
3871
+ case "help":
3872
+ ctx.out(USAGE);
3873
+ return 0;
3874
+ case "version":
3875
+ ctx.out(ctx.version);
3876
+ return 0;
3877
+ case "status":
3878
+ return await status(ctx);
3879
+ case "setup":
3880
+ return await setup(cmd, ctx);
3881
+ case "logs":
3882
+ return await logs(ctx);
3883
+ case "start":
3884
+ return await start(ctx);
3885
+ case "stop":
3886
+ return await stop(ctx);
3887
+ case "unpair":
3888
+ return await unpair(ctx);
3889
+ case "daemon":
3890
+ return await daemon(ctx);
3891
+ }
3892
+ } catch (e) {
3893
+ if (e instanceof PromptClosed) {
3894
+ ctx.out("\u5DF2\u53D6\u6D88");
3895
+ return 1;
3896
+ }
3897
+ ctx.out(`\u9519\u8BEF\uFF1A${e.message}`);
3898
+ return 1;
3899
+ } finally {
3900
+ ctx.prompter.close();
3901
+ }
3902
+ }
3903
+
3904
+ // src/host.ts
3905
+ import { execFile as execFile4 } from "child_process";
3906
+ import { access as access2, constants as constants4 } from "fs/promises";
3907
+ import { join as join14 } from "path";
3908
+ import { promisify as promisify2 } from "util";
3909
+ import WebSocket from "ws";
3910
+
3911
+ // ../link/src/platform/darwin/index.ts
3912
+ import { realpath as realpath8 } from "fs/promises";
3913
+ import { tmpdir as tmpdir3 } from "os";
3914
+
3915
+ // ../link/src/platform/darwin/commands.ts
3916
+ import { realpath as realpath7 } from "fs/promises";
3917
+ import { StringDecoder as StringDecoder2 } from "string_decoder";
3918
+
3919
+ // ../link/src/platform/darwin/sandbox.ts
3920
+ import { execFile as execFile3, spawn as nodeSpawn5 } from "child_process";
3921
+ import { homedir as homedir6 } from "os";
3922
+ import { dirname as dirname6, join as join13 } from "path";
3923
+ import { createInterface as createInterface2 } from "readline";
3924
+ var SANDBOX_EXEC = "/usr/bin/sandbox-exec";
3925
+ var BASE_POLICY = `
3926
+ (allow process-exec)
3927
+ (allow process-fork)
3928
+ (allow signal (target same-sandbox))
3929
+ (allow process-info* (target same-sandbox))
3930
+ (allow file-write-data (require-all (path "/dev/null") (vnode-type CHARACTER-DEVICE)))
3931
+ (allow sysctl-read
3932
+ (sysctl-name "hw.activecpu") (sysctl-name "hw.busfrequency_compat") (sysctl-name "hw.byteorder")
3933
+ (sysctl-name "hw.cacheconfig") (sysctl-name "hw.cachelinesize_compat") (sysctl-name "hw.cpufamily")
3934
+ (sysctl-name "hw.cpufrequency_compat") (sysctl-name "hw.cputype") (sysctl-name "hw.l1dcachesize_compat")
3935
+ (sysctl-name "hw.l1icachesize_compat") (sysctl-name "hw.l2cachesize_compat") (sysctl-name "hw.l3cachesize_compat")
3936
+ (sysctl-name "hw.logicalcpu_max") (sysctl-name "hw.machine") (sysctl-name "hw.model") (sysctl-name "hw.memsize")
3937
+ (sysctl-name "hw.ncpu") (sysctl-name "hw.nperflevels") (sysctl-name-prefix "hw.optional.arm.")
3938
+ (sysctl-name-prefix "hw.optional.armv8_") (sysctl-name "hw.packages") (sysctl-name "hw.pagesize_compat")
3939
+ (sysctl-name "hw.pagesize") (sysctl-name "hw.physicalcpu") (sysctl-name "hw.physicalcpu_max")
3940
+ (sysctl-name "hw.logicalcpu") (sysctl-name "hw.cpufrequency") (sysctl-name "hw.tbfrequency_compat")
3941
+ (sysctl-name "hw.vectorunit") (sysctl-name "machdep.cpu.brand_string") (sysctl-name "kern.argmax")
3942
+ (sysctl-name "kern.hostname") (sysctl-name "kern.maxfilesperproc") (sysctl-name "kern.maxproc")
3943
+ (sysctl-name "kern.osproductversion") (sysctl-name "kern.osrelease") (sysctl-name "kern.ostype")
3944
+ (sysctl-name "kern.osvariant_status") (sysctl-name "kern.osversion") (sysctl-name "kern.secure_kernel")
3945
+ (sysctl-name "kern.sysv.semmns") (sysctl-name "kern.usrstack64") (sysctl-name "kern.version")
3946
+ (sysctl-name "sysctl.proc_cputype") (sysctl-name "vm.loadavg") (sysctl-name-prefix "hw.perflevel")
3947
+ (sysctl-name-prefix "kern.proc.pgrp.") (sysctl-name-prefix "kern.proc.pid.") (sysctl-name-prefix "net.routetable."))
3948
+ (allow sysctl-write (sysctl-name "kern.grade_cputype"))
3949
+ ; E4\uFF1Azsh / bash / id / git / node \u6BCF\u6B21\u542F\u52A8\u90FD\u8BFB\uFF0C\u653E\u884C\u53EA\u4E3A\u964D\u566A
3950
+ (allow sysctl-read
3951
+ (sysctl-name "kern.bootargs") (sysctl-name "kern.iossupportversion") (sysctl-name "kern.ngroups")
3952
+ (sysctl-name "kern.willshutdown") (sysctl-name "security.mac.lockdown_mode_state"))
3953
+ (allow iokit-open (iokit-registry-entry-class "RootDomainUserClient"))
3954
+ (allow mach-lookup (global-name "com.apple.system.opendirectoryd.libinfo"))
3955
+ (allow ipc-posix-sem)
3956
+ (allow ipc-posix-shm-read-data ipc-posix-shm-write-create ipc-posix-shm-write-unlink
3957
+ (ipc-posix-name-regex #"^/__KMP_REGISTERED_LIB_[0-9]+$"))
3958
+ (allow mach-lookup (global-name "com.apple.PowerManagement.control"))
3959
+ (allow pseudo-tty)
3960
+ (allow file-read* file-write* file-ioctl (literal "/dev/ptmx"))
3961
+ (allow file-read* file-write* (require-all (regex #"^/dev/ttys[0-9]+") (extension "com.apple.sandbox.pty")))
3962
+ (allow file-ioctl (regex #"^/dev/ttys[0-9]+"))
3963
+ (allow ipc-posix-shm-read* (ipc-posix-name-prefix "apple.cfprefs."))
3964
+ (allow mach-lookup
3965
+ (global-name "com.apple.cfprefsd.daemon") (global-name "com.apple.cfprefsd.agent") (local-name "com.apple.cfprefsd.agent"))
3966
+ (allow user-preference-read)
3967
+ ; \xA77.2-A \u8BBE\u5907\u6587\u4EF6\uFF08\u5404\u6863\u90FD\u53EF\u5199\uFF09
3968
+ (allow file-read* file-write* file-ioctl
3969
+ (literal "/dev/null") (literal "/dev/zero") (literal "/dev/stdout") (literal "/dev/stderr") (literal "/dev/tty")
3970
+ (literal "/dev/dtracehelper") (literal "/dev/autofs_nowait") (literal "/dev/random") (literal "/dev/urandom")
3971
+ (subpath "/dev/fd") (regex #"^/dev/ttys[0-9]+$"))
3972
+ ; \u8BFB\uFF1A\u5168\u90E8\uFF08\u654F\u611F\u8DEF\u5F84\u5728\u6700\u540E\u7981\u6389\uFF0C\u540E\u51FA\u73B0\u7684\u89C4\u5219\u4F18\u5148\uFF09
3973
+ (allow file-read*)
3974
+ `;
3975
+ var NETWORK_POLICY = `
3976
+ (allow network-outbound (remote ip))
3977
+ (allow network-inbound (local ip))
3978
+ (allow system-socket (require-all (socket-domain AF_SYSTEM) (socket-protocol 2)))
3979
+ (allow network-outbound (require-all (socket-domain AF_SYSTEM) (socket-protocol 2)))
3980
+ ; \u4E0D\u653E\u884C com.apple.SecurityServer\uFF08Codex \u653E\u4E86\uFF09\uFF1A\u5B83\u66FF\u8FDB\u7A0B\u67E5\u6587\u4EF6\u94A5\u5319\u4E32\uFF0C\u653E\u884C\u65F6\u8BFB\u4E0D\u4E86 Keychains \u76EE\u5F55\u4E5F\u80FD\u67E5\u51FA\u53E3\u4EE4\u3002
3981
+ ; TLS \u6821\u9A8C\u8D70 trustd\uFF0C\u4E0D\u9700\u8981\u5B83
3982
+ (allow mach-lookup
3983
+ (global-name "com.apple.bsd.dirhelper") (global-name "com.apple.system.opendirectoryd.membership")
3984
+ (global-name "com.apple.networkd") (global-name "com.apple.ocspd") (global-name "com.apple.trustd.agent")
3985
+ (global-name "com.apple.TrustEvaluationAgent") (global-name "com.apple.SystemConfiguration.DNSConfiguration")
3986
+ (global-name "com.apple.SystemConfiguration.configd"))
3987
+ (allow sysctl-read (sysctl-name-regex #"^net.routetable"))
3988
+ ; DNS \u7ECF mDNSResponder \u7684 unix socket
3989
+ (allow network-outbound (remote unix-socket (path-literal "/private/var/run/mDNSResponder")))
3990
+ `;
3991
+ var CALL_ID_RE = /^[A-Za-z0-9_-]+$/;
3992
+ function regexLiteral(path) {
3993
+ if (/["\x00-\x1f]/.test(path)) throw new Error(`\u6C99\u7BB1\u62D2\u7EDD\u542B\u5F15\u53F7\u6216\u63A7\u5236\u5B57\u7B26\u7684\u8DEF\u5F84\uFF1A${JSON.stringify(path)}`);
3994
+ return path.replace(/[.^$*+?()[\]{}|\\]/g, "\\$&");
3995
+ }
3996
+ function buildProfile(input) {
3997
+ const { mode, callId, home } = input;
3998
+ if (!CALL_ID_RE.test(callId)) throw new Error("call id must be [A-Za-z0-9_-]+");
3999
+ const tag = `(with message "leo-${callId}")`;
4000
+ const params = [];
4001
+ const param = (name, value) => {
4002
+ if (value.includes("\0")) throw new Error("\u6C99\u7BB1\u62D2\u7EDD\u542B NUL \u7684\u8DEF\u5F84");
4003
+ const key = `${name}_${params.length}`;
4004
+ params.push([key, value]);
4005
+ return `(param "${key}")`;
4006
+ };
4007
+ const out = ["(version 1)", `(deny default ${tag})`, BASE_POLICY];
4008
+ const writes = [`(subpath ${param("SESSION_TMP", input.sessionTmp)})`];
4009
+ const unlinkDenies = [];
4010
+ const launchAgents = join13(home, ...PROTECTED_HOME_DIRS[0].split("/"));
4011
+ const protectedNots = (anchor, opts) => {
4012
+ const names = opts.released ? PROTECTED_NAMES.filter((n) => !ESCALATED_RELEASED_NAMES.includes(n)) : PROTECTED_NAMES;
4013
+ const dirs = opts.released ? PROTECTED_DIRS.filter((d) => !ESCALATED_RELEASED_DIRS.includes(d)) : PROTECTED_DIRS;
4014
+ const nots = [
4015
+ ...names.map((n) => `(require-not (regex #"^(/.*)?/${regexLiteral(n)}$"))`),
4016
+ ...dirs.map((d) => `(require-not (regex #"^(/.*)?/${regexLiteral(d)}(/.*)?$"))`)
4017
+ ];
4018
+ if (opts.git) {
4019
+ nots.push(
4020
+ ...GIT_PROTECTED_SUFFIXES.map((suffix) => `(require-not (regex #"^(/.*)?/\\.git${suffix}$"))`),
4021
+ // 文件或软链形态的 .git(gitdir: 指向任意目录);目录形态可以新建(init / clone 再因写 config 失败)
4022
+ `(require-not (require-all (regex #"^(/.*)?/\\.git$") (require-any (vnode-type REGULAR-FILE) (vnode-type SYMLINK))))`
4023
+ );
4024
+ }
4025
+ if (anchor === "/" || within(launchAgents, anchor) !== null || within(anchor, launchAgents) !== null) {
4026
+ nots.push(`(require-not (subpath ${param("LAUNCH_AGENTS", launchAgents)}))`);
4027
+ }
4028
+ return nots;
4029
+ };
4030
+ const writableTree = (name, dir) => {
4031
+ const p = param(name, dir);
4032
+ writes.push(`(require-all (subpath ${p})
4033
+ ${protectedNots(dir, { git: true, released: false }).join("\n ")})`);
4034
+ unlinkDenies.push(`(deny file-write-unlink (require-all (subpath ${p}) (regex #"^(/.*)?/\\.git(/hooks|/modules)?$")) ${tag})`);
4035
+ return p;
4036
+ };
4037
+ if (mode === "workspace-write") {
4038
+ for (const d of /* @__PURE__ */ new Set([...input.systemDirs.tmp, ...input.systemDirs.cache ? [input.systemDirs.cache] : []])) {
4039
+ writableTree("TMP", d);
4040
+ }
4041
+ for (const rel of WRITABLE_HOME_CACHES) writes.push(`(subpath ${param("CACHE", join13(home, rel))})`);
4042
+ for (const root of input.roots) {
4043
+ if (root.kind === "file") {
4044
+ writes.push(`(require-all (literal ${param("ROOT", root.path)})
4045
+ ${protectedNots(dirname6(root.path), { git: true, released: false }).join("\n ")})`);
4046
+ continue;
4047
+ }
4048
+ const p = writableTree("ROOT", root.path);
4049
+ unlinkDenies.push(`(deny file-write-unlink (literal ${p}) ${tag})`);
4050
+ }
4051
+ } else if (mode === "escalated") {
4052
+ writes.push(`(require-all (subpath "/")
4053
+ ${protectedNots("/", { git: false, released: false }).join("\n ")})`);
4054
+ for (const root of input.roots) {
4055
+ if (root.kind !== "dir") continue;
4056
+ writes.push(`(require-all (subpath ${param("ROOT", root.path)})
4057
+ ${protectedNots(root.path, { git: false, released: true }).join("\n ")})`);
4058
+ }
4059
+ }
4060
+ out.push(`(allow file-write*
4061
+ ${writes.join("\n ")})`);
4062
+ out.push(NETWORK_POLICY);
4063
+ if (input.sshAuthSock) {
4064
+ out.push(`(allow network-outbound (remote unix-socket (path-literal ${param("SSH_AUTH_SOCK", input.sshAuthSock)})))`);
4065
+ }
4066
+ const { paths: sensitive, ssh } = input.sensitive;
4067
+ const sshReadable2 = [...SSH_READABLE_NAMES.map(regexLiteral), "[^/]*\\.pub"].join("|");
4068
+ out.push(
4069
+ `(deny file-read* file-write*
4070
+ ${[...sensitive, ssh].map((s) => `(subpath ${param("SENSITIVE", s)})`).join("\n ")}
4071
+ ${tag})`,
4072
+ // 目录本身可列(ssh 要 stat 它),只放开直接子项里的公钥、known_hosts、config;写仍然禁
4073
+ `(allow file-read* (regex #"^${regexLiteral(ssh)}(/(${sshReadable2}))?$"))`,
4074
+ // 会话临时目录在桌面端 userData 之下(敏感),只把这一个目录重新放开
4075
+ `(allow file-read* file-write* (subpath ${param("SESSION_TMP", input.sessionTmp)}))`
4076
+ );
4077
+ const ancestors = /* @__PURE__ */ new Set();
4078
+ for (const s of [...sensitive, ssh]) {
4079
+ if (within(s, home) === null) continue;
4080
+ for (let cur = s; within(cur, home) !== null; cur = dirname6(cur)) {
4081
+ ancestors.add(cur);
4082
+ if (cur === home) break;
4083
+ }
4084
+ }
4085
+ if (ancestors.size) {
4086
+ out.push(`(deny file-write-unlink
4087
+ ${[...ancestors].sort().map((a) => `(literal ${param("SENS_ANCESTOR", a)})`).join("\n ")}
4088
+ ${tag})`);
4089
+ }
4090
+ out.push(...unlinkDenies);
4091
+ out.push(
4092
+ `(deny process-exec ${EXEC_DENY.map((p) => `(literal "${p}")`).join(" ")} ${tag})`,
4093
+ `(deny mach-lookup (xpc-service-name-prefix "") ${tag})`,
4094
+ // 这两个 fcntl 能经只读描述符改文件,绕过 file-write 检查(Codex)
4095
+ `(deny system-fcntl (fcntl-command 80 110) ${tag})`
4096
+ );
4097
+ return { text: out.join("\n") + "\n", params };
4098
+ }
4099
+ function sandboxArgv(profile, command) {
4100
+ return [SANDBOX_EXEC, "-p", profile.text, ...profile.params.map(([k, v]) => `-D${k}=${v}`), "--", ...command];
4101
+ }
4102
+ async function collectSensitive(home, extra, fs = nodeBoundaryFs) {
4103
+ const canonicalHome = await canonicalForCreate(home, fs);
4104
+ const literal = [
4105
+ ...[...SENSITIVE_HOME_PATHS, ...SANDBOX_SENSITIVE_HOME].filter((rel) => rel !== ".ssh").map((rel) => join13(canonicalHome, rel)),
4106
+ // 例外(溢出文件)只对文件工具:shell 读不到 userData 里的任何东西
4107
+ ...extra.map(extraPath),
4108
+ ...SANDBOX_SENSITIVE_ABS
4109
+ ];
4110
+ const paths = /* @__PURE__ */ new Set();
4111
+ for (const p of literal) {
4112
+ paths.add(p);
4113
+ paths.add(await canonicalForCreate(p, fs));
4114
+ }
4115
+ return { paths: [...paths], ssh: await canonicalForCreate(join13(canonicalHome, ".ssh"), fs) };
4116
+ }
4117
+ async function canonicalForCreate(path, fs) {
4118
+ return resolveForCreate(path, fs).catch(() => path);
4119
+ }
4120
+ var nodeExecFile = (file, args, opts) => new Promise((resolve3, reject) => {
4121
+ execFile3(file, args, { ...opts, encoding: "utf8" }, (err, stdout) => err ? reject(err) : resolve3({ stdout }));
4122
+ });
4123
+ async function loadSystemDirs(fs = nodeBoundaryFs, run3 = nodeExecFile, env = process.env) {
4124
+ const getconf = (name) => run3("/usr/bin/getconf", [name], { timeout: 5e3 }).then((r) => r.stdout.trim(), () => "");
4125
+ const tmp = /* @__PURE__ */ new Set();
4126
+ for (const d of ["/private/tmp", env.TMPDIR ?? "", await getconf("DARWIN_USER_TEMP_DIR")]) {
4127
+ if (d) tmp.add(await canonicalForCreate(d.replace(/\/+$/, "") || "/", fs));
4128
+ }
4129
+ const cache = await getconf("DARWIN_USER_CACHE_DIR");
4130
+ return { tmp: [...tmp], cache: cache ? await canonicalForCreate(cache.replace(/\/+$/, ""), fs) : null };
4131
+ }
4132
+ async function probeSeatbelt(opts) {
4133
+ if ((opts.platform ?? process.platform) !== "darwin") return false;
4134
+ try {
4135
+ const home = await canonicalForCreate(opts.home ?? homedir6(), nodeBoundaryFs);
4136
+ const profile = buildProfile({
4137
+ mode: "read-only",
4138
+ callId: "probe",
4139
+ home,
4140
+ roots: [],
4141
+ sessionTmp: opts.sessionTmp,
4142
+ sensitive: await collectSensitive(home, []),
4143
+ systemDirs: opts.systemDirs
4144
+ });
4145
+ const [file, ...args] = sandboxArgv(profile, ["/usr/bin/true"]);
4146
+ await (opts.run ?? nodeExecFile)(file, args, { timeout: 1e4 });
4147
+ return true;
4148
+ } catch {
4149
+ return false;
4150
+ }
4151
+ }
4152
+ var NOISE = /* @__PURE__ */ new Set(["com.apple.diagnosticd", "com.apple.logd", "com.apple.system.notification_center", "com.apple.analyticsd"]);
4153
+ var ENTRY_RE = /^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\.\d+ /;
4154
+ var DENY_RE = /Sandbox: .+?\(\d+\) deny\(\d+\) (\S+)(?: (.*))?$/;
4155
+ var TAG_RE = /^leo-([A-Za-z0-9_-]+)$/;
4156
+ var LOG_BIN = "/usr/bin/log";
4157
+ var PREDICATE = 'sender == "Sandbox" AND eventMessage CONTAINS "leo-"';
4158
+ var ViolationLog = class {
4159
+ child = null;
4160
+ running = false;
4161
+ ready = false;
4162
+ pending = null;
4163
+ calls = /* @__PURE__ */ new Map();
4164
+ drops = /* @__PURE__ */ new Map();
4165
+ restartTimer = null;
4166
+ opts;
4167
+ constructor(opts = {}) {
4168
+ this.opts = opts;
4169
+ }
4170
+ get available() {
4171
+ return this.ready;
4172
+ }
4173
+ start() {
4174
+ if (this.running) return;
4175
+ this.running = true;
4176
+ this.spawn();
4177
+ }
4178
+ stop() {
4179
+ this.running = false;
4180
+ this.ready = false;
4181
+ if (this.restartTimer) clearTimeout(this.restartTimer);
4182
+ this.restartTimer = null;
4183
+ this.child?.kill();
4184
+ this.child = null;
4185
+ }
4186
+ begin(callId) {
4187
+ const drop = this.drops.get(callId);
4188
+ if (drop) clearTimeout(drop);
4189
+ this.drops.delete(callId);
4190
+ if (!this.calls.has(callId)) this.calls.set(callId, []);
4191
+ }
4192
+ finish(callId) {
4193
+ if (!this.calls.has(callId)) return;
4194
+ const timer = setTimeout(() => {
4195
+ this.calls.delete(callId);
4196
+ this.drops.delete(callId);
4197
+ }, this.opts.retainMs ?? 3e4);
4198
+ timer.unref?.();
4199
+ this.drops.set(callId, timer);
4200
+ }
4201
+ denials(callId) {
4202
+ return [...this.calls.get(callId) ?? []];
4203
+ }
4204
+ /** 一行 log stream 输出(导出供测试) */
4205
+ feed(line) {
4206
+ const tag = TAG_RE.exec(line.trim());
4207
+ if (tag) {
4208
+ const d = this.pending;
4209
+ this.pending = null;
4210
+ const list = d ? this.calls.get(tag[1]) : void 0;
4211
+ if (!d || !list || d.op === "mach-lookup" && NOISE.has(d.path)) return;
4212
+ if (list.some((x) => x.op === d.op && x.path === d.path)) return;
4213
+ list.push(d);
4214
+ if (list.length > (this.opts.perCall ?? 50)) list.shift();
4215
+ return;
4216
+ }
4217
+ if (ENTRY_RE.test(line)) {
4218
+ const m = DENY_RE.exec(line);
4219
+ this.pending = m ? { op: m[1], path: m[2] ?? "" } : null;
4220
+ }
4221
+ }
4222
+ spawn() {
4223
+ const child = (this.opts.spawnImpl ?? nodeSpawn5)(LOG_BIN, ["stream", "--style", "compact", "--predicate", PREDICATE], {
4224
+ stdio: ["ignore", "pipe", "ignore"]
4225
+ });
4226
+ this.child = child;
4227
+ child.on("error", () => this.onExit(child));
4228
+ child.on("exit", () => this.onExit(child));
4229
+ if (!child.stdout) return;
4230
+ const lines = createInterface2({ input: child.stdout });
4231
+ lines.on("line", (line) => {
4232
+ this.ready = true;
4233
+ this.feed(line);
4234
+ });
4235
+ }
4236
+ onExit(child) {
4237
+ if (this.child !== child) return;
4238
+ this.child = null;
4239
+ this.ready = false;
4240
+ if (!this.running || this.restartTimer) return;
4241
+ this.restartTimer = setTimeout(() => {
4242
+ this.restartTimer = null;
4243
+ if (this.running) this.spawn();
4244
+ }, this.opts.restartMs ?? 1e4);
4245
+ this.restartTimer.unref?.();
4246
+ }
4247
+ };
4248
+
4249
+ // ../link/src/platform/darwin/commands.ts
4250
+ var NOT_FOUND_RE = /command not found: (\S+)/;
4251
+ var SCRUB_SECRETS = `() { setopt localoptions extendedglob; local n; for n in \${(k)parameters}; do [[ \${parameters[$n]} == *export* && $n == (#i)*(${SECRET_ENV_WORDS.join("|")})* ]] && unset -- $n; done; return 0 } 2>/dev/null
4252
+ `;
4253
+ var ZSH = ["/bin/zsh", "-o", "nobgnice", "-lc"];
4254
+ function seatbeltShell(deps) {
4255
+ return {
4256
+ hello: { sandbox: "seatbelt" },
4257
+ monitor: deps.log,
4258
+ spillsText: false,
4259
+ decoder: () => new StringDecoder2("utf8"),
4260
+ missingCommand: (stderrTail) => NOT_FOUND_RE.exec(stderrTail)?.[1],
4261
+ prepare: (run3) => prepare(deps, run3)
4262
+ };
4263
+ }
4264
+ async function prepare(deps, run3) {
4265
+ const sandboxed = run3.mode !== "unsandboxed";
4266
+ const agentSock = sandboxed && run3.env.SSH_AUTH_SOCK ? await realpath7(run3.env.SSH_AUTH_SOCK).catch(() => void 0) : void 0;
4267
+ const profile = sandboxed && buildProfile({
4268
+ mode: run3.mode,
4269
+ callId: run3.callId,
4270
+ home: deps.home,
4271
+ roots: run3.roots,
4272
+ sessionTmp: run3.sessionTmp,
4273
+ sensitive: await collectSensitive(deps.home, deps.sensitiveExtra),
4274
+ systemDirs: deps.systemDirs,
4275
+ sshAuthSock: run3.sshAgent ? agentSock : void 0
4276
+ });
4277
+ const command = (run3.reapplyPath ? `export PATH=${shQuote(run3.env.PATH)}
4278
+ ` : "") + run3.command;
4279
+ const [file, ...args] = profile ? sandboxArgv(profile, [...ZSH, SCRUB_SECRETS + command]) : [...ZSH, command];
4280
+ if (sandboxed) deps.log.begin(run3.callId);
4281
+ return {
4282
+ file,
4283
+ args,
4284
+ env: run3.env,
4285
+ spawnOptions: { detached: true },
4286
+ kill: (child) => killGroup(child, deps.killGraceMs ?? 2e3),
4287
+ denials: async (code, stderrTail) => {
4288
+ let denied;
4289
+ if (!sandboxed) {
4290
+ denied = [];
4291
+ } else if (deps.log.available) {
4292
+ await new Promise((r) => setTimeout(r, deps.denialSettleMs ?? 150));
4293
+ denied = deps.log.denials(run3.callId);
4294
+ } else {
4295
+ denied = code !== 0 && /Operation not permitted/i.test(stderrTail) ? [{ op: "unknown", path: "" }] : [];
4296
+ }
4297
+ const sshAgentDenied = agentSock !== void 0 && denied.some((d) => d.path === agentSock);
4298
+ return { denied: sshAgentDenied ? denied.filter((d) => d.path !== agentSock) : denied, sshAgentDenied };
4299
+ },
4300
+ dispose: async () => deps.log.finish(run3.callId)
4301
+ };
4302
+ }
4303
+ function killGroup(child, graceMs) {
4304
+ const pid = child.pid;
4305
+ const group = (sig) => {
4306
+ try {
4307
+ process.kill(-pid, sig);
4308
+ } catch {
4309
+ }
4310
+ };
4311
+ group("SIGTERM");
4312
+ const t = setTimeout(() => group("SIGKILL"), graceMs);
4313
+ t.unref?.();
4314
+ child.once("close", () => clearTimeout(t));
4315
+ }
4316
+
4317
+ // ../link/src/platform/darwin/index.ts
4318
+ var darwin = {
4319
+ async commands({ home, sensitiveExtra }) {
4320
+ const probeTmp = await realpath8(tmpdir3()).catch(() => tmpdir3());
4321
+ const systemDirs = await loadSystemDirs();
4322
+ if (!await probeSeatbelt({ sessionTmp: probeTmp, systemDirs })) return null;
4323
+ return seatbeltShell({ home, sensitiveExtra, systemDirs, log: new ViolationLog() });
4324
+ }
4325
+ };
4326
+
4327
+ // src/host.ts
4328
+ var execFileP2 = promisify2(execFile4);
4329
+ var run2 = async (file, args) => {
4330
+ try {
4331
+ const { stdout } = await execFileP2(file, args, { timeout: 3e4 });
4332
+ return stdout;
4333
+ } catch (e) {
4334
+ const stderr = e.stderr?.trim();
4335
+ throw new Error(stderr || e.message);
4336
+ }
4337
+ };
4338
+ var isExecutable2 = (path) => access2(path, constants4.X_OK).then(() => true, () => false);
4339
+ async function bundledRipgrep() {
4340
+ try {
4341
+ const m = await import("@vscode/ripgrep");
4342
+ return m.rgPath ?? m.default?.rgPath ?? null;
4343
+ } catch {
4344
+ return null;
4345
+ }
4346
+ }
4347
+ function nodeHost(paths, deps = {}) {
4348
+ const exec = deps.run ?? run2;
4349
+ const canExec = deps.isExecutable ?? isExecutable2;
4350
+ const Ws = deps.WebSocket ?? WebSocket;
4351
+ return {
4352
+ dataDir: paths.dataDir,
4353
+ leoFolder: paths.leoFolder,
4354
+ platform: darwin,
4355
+ connectWs: (url, token) => new Ws(url, ["leo-bearer", token]),
4356
+ // Node 的 fetch 不走系统代理(桌面端的 net.fetch 走);Link 的 ws 本来就不走,能连上 Link 的环境一般同源 HTTP 也通
4357
+ fetch: globalThis.fetch,
4358
+ async trashItem(path) {
4359
+ if (await canExec("/usr/bin/trash")) {
4360
+ await exec("/usr/bin/trash", [path]);
4361
+ return;
4362
+ }
4363
+ await exec("/usr/bin/osascript", [
4364
+ "-e",
4365
+ "on run argv",
4366
+ "-e",
4367
+ 'tell application "Finder" to delete (POSIX file (item 1 of argv) as alias)',
4368
+ "-e",
4369
+ "end run",
4370
+ path
4371
+ ]);
4372
+ },
4373
+ async openPath(path) {
4374
+ try {
4375
+ await exec("/usr/bin/open", [path]);
4376
+ return "";
4377
+ } catch (e) {
4378
+ return e.message;
4379
+ }
4380
+ },
4381
+ async openExternal(url) {
4382
+ await exec("/usr/bin/open", [url]);
4383
+ },
4384
+ async resolveRipgrep() {
4385
+ await shellPath.ready();
4386
+ const dirs = (deps.pathEnv?.() ?? loginPathEnv().PATH ?? "").split(":").filter((d) => d.startsWith("/"));
4387
+ for (const dir of dirs) {
4388
+ const candidate = join14(dir, "rg");
4389
+ if (await canExec(candidate)) return candidate;
4390
+ }
4391
+ const bundled = await (deps.bundledRipgrep ?? bundledRipgrep)();
4392
+ return bundled && await canExec(bundled) ? bundled : null;
4393
+ }
4394
+ };
4395
+ }
4396
+
4397
+ // src/paths.ts
4398
+ import { homedir as homedir7 } from "os";
4399
+ import { join as join15 } from "path";
4400
+ var channelOf = (entry) => entry.includes("/node_modules/") ? "stable" : "development";
4401
+ function cliPaths(home = homedir7(), channel = "stable") {
4402
+ const dev = channel === "development";
4403
+ const suffix = dev ? "-dev" : "";
4404
+ const dataDir = join15(home, "Library", "Application Support", `leo-link${suffix}`);
4405
+ const serviceLabel = dev ? "ai.leo.link.dev" : "ai.leo.link";
4406
+ return {
4407
+ channel,
4408
+ dataDir,
4409
+ configPath: join15(dataDir, "config.json"),
4410
+ lockPath: join15(dataDir, "leo-link.pid"),
4411
+ leoFolder: join15(home, "Documents", dev ? "leo-dev-workspace" : "leo-workspace"),
4412
+ desktopConfigPath: join15(home, "Library", "Application Support", `leo-desktop${suffix}`, "config.json"),
4413
+ serviceLabel,
4414
+ launchAgentPath: join15(home, "Library", "LaunchAgents", `${serviceLabel}.plist`),
4415
+ logPath: join15(home, "Library", "Logs", `leo-link${suffix}`, "leo-link.log")
4416
+ };
4417
+ }
4418
+
4419
+ // src/service.ts
4420
+ import { existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync3, unlinkSync, writeFileSync as writeFileSync2 } from "fs";
4421
+ import { dirname as dirname7 } from "path";
4422
+ var ServiceError = class extends Error {
4423
+ };
4424
+ var xml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
4425
+ var unxml = (s) => s.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
4426
+ function renderPlist({ label, node, entry, logPath }) {
4427
+ return `<?xml version="1.0" encoding="UTF-8"?>
4428
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
4429
+ <plist version="1.0">
4430
+ <dict>
4431
+ <key>Label</key>
4432
+ <string>${xml(label)}</string>
4433
+ <key>ProgramArguments</key>
4434
+ <array>
4435
+ <string>${xml(node)}</string>
4436
+ <string>${xml(entry)}</string>
4437
+ <string>daemon</string>
4438
+ </array>
4439
+ <key>RunAtLoad</key>
4440
+ <true/>
4441
+ <key>KeepAlive</key>
4442
+ <dict>
4443
+ <key>SuccessfulExit</key>
4444
+ <false/>
4445
+ </dict>
4446
+ <key>StandardOutPath</key>
4447
+ <string>${xml(logPath)}</string>
4448
+ <key>StandardErrorPath</key>
4449
+ <string>${xml(logPath)}</string>
4450
+ </dict>
4451
+ </plist>
4452
+ `;
4453
+ }
4454
+ function plistProgram(text) {
4455
+ const array = text.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/)?.[1];
4456
+ const strings = [...(array ?? "").matchAll(/<string>([^<]*)<\/string>/g)].map((m) => unxml(m[1]));
4457
+ return strings.length >= 2 ? { node: strings[0], entry: strings[1] } : null;
4458
+ }
4459
+ async function stableNode(execPath, realpath10) {
4460
+ const m = execPath.match(/^(.*)\/Cellar\/([^/]+)\/[^/]+\/bin\/node$/);
4461
+ if (!m) return execPath;
4462
+ const [, prefix, formula] = m;
4463
+ const real = await realpath10(execPath).catch(() => execPath);
4464
+ for (const candidate of [`${prefix}/opt/${formula}/bin/node`, `${prefix}/bin/node`]) {
4465
+ if (await realpath10(candidate).then((r) => r === real, () => false)) return candidate;
4466
+ }
4467
+ return execPath;
4468
+ }
4469
+ function describeLoaded(printed) {
4470
+ if (printed === null) return "\u540E\u53F0\u670D\u52A1\uFF1A\u6CA1\u5728\u8FD0\u884C\uFF08leo-link start \u542F\u52A8\uFF09";
4471
+ const state = printed.match(/^\s*state = (.+)$/m)?.[1].trim();
4472
+ const pid = printed.match(/^\s*pid = (\d+)$/m)?.[1];
4473
+ const exit = printed.match(/^\s*last exit code = (-?\d+)/m)?.[1];
4474
+ return state === "running" && pid ? `\u540E\u53F0\u670D\u52A1\uFF1A\u8FD0\u884C\u4E2D\uFF08pid ${pid}\uFF09` : `\u540E\u53F0\u670D\u52A1\uFF1A\u88C5\u4E86\u4F46\u6CA1\u6709\u5728\u8FD0\u884C${exit ? `\uFF08\u4E0A\u6B21\u9000\u51FA\u7801 ${exit}\uFF09` : ""}`;
4475
+ }
4476
+ var inNpxCache = (entry) => entry.includes("/_npx/");
4477
+ var LaunchdService = class {
4478
+ deps;
4479
+ constructor(deps) {
4480
+ this.deps = deps;
4481
+ }
4482
+ get target() {
4483
+ return `gui/${this.deps.uid}/${this.deps.paths.serviceLabel}`;
4484
+ }
4485
+ launchctl(...args) {
4486
+ return this.deps.run("/bin/launchctl", args);
4487
+ }
4488
+ /**
4489
+ * launchctl print 的输出;没加载为 null。只有「Could not find service」(退出码 113)才是没加载——
4490
+ * 权限、I/O 之类的失败是「不知道」,抛 ServiceError,不能当成服务已经不在了
4491
+ */
4492
+ async print() {
4493
+ try {
4494
+ return await this.launchctl("print", this.target);
4495
+ } catch (e) {
4496
+ const message = e.message;
4497
+ if (/Could not find service/.test(message)) return null;
4498
+ throw new ServiceError(`\u67E5\u4E0D\u5230\u540E\u53F0\u670D\u52A1\u7684\u72B6\u6001\uFF1A${message}`);
4499
+ }
4500
+ }
4501
+ /** 不能装服务的原因(setup 一开始就查,免得问完一圈才发现);能装为 null */
4502
+ async installable() {
4503
+ const entry = await this.deps.realpath(this.deps.entry);
4504
+ if (!inNpxCache(entry)) return null;
4505
+ return `\u73B0\u5728\u662F\u7ECF npx \u4E34\u65F6\u8FD0\u884C\u7684\uFF1A\u540E\u53F0\u670D\u52A1\u8981\u6307\u5411\u4E00\u4EFD\u88C5\u597D\u7684 leo-link\uFF0C\u7F13\u5B58\u4E00\u6E05\u5C31\u5931\u6548\u4E86\u3002\u8BF7\u5148\u5168\u5C40\u5B89\u88C5\uFF1Anpm i -g leo-link@${this.deps.version}\uFF0C\u518D\u8FD0\u884C leo-link setup`;
4506
+ }
4507
+ async install() {
4508
+ const { paths } = this.deps;
4509
+ const problem = await this.installable();
4510
+ if (problem) throw new ServiceError(problem);
4511
+ const entry = await this.deps.realpath(this.deps.entry);
4512
+ const node = await stableNode(this.deps.execPath, this.deps.realpath);
4513
+ mkdirSync4(dirname7(paths.launchAgentPath), { recursive: true });
4514
+ mkdirSync4(dirname7(paths.logPath), { recursive: true });
4515
+ writeFileSync2(paths.launchAgentPath, renderPlist({ label: paths.serviceLabel, node, entry, logPath: paths.logPath }));
4516
+ await this.launchctl("bootout", this.target).catch(() => {
4517
+ });
4518
+ await this.launchctl("bootstrap", `gui/${this.deps.uid}`, paths.launchAgentPath);
4519
+ return [
4520
+ `\u5DF2\u542F\u52A8\u540E\u53F0\u670D\u52A1\uFF08launchd ${paths.serviceLabel}\uFF09\uFF0C\u767B\u5F55\u540E\u81EA\u52A8\u8FD0\u884C`,
4521
+ `node\uFF1A${node}`,
4522
+ `leo-link\uFF1A${entry}`,
4523
+ `\u65E5\u5FD7\uFF1A${paths.logPath}`
4524
+ ];
4525
+ }
4526
+ /** 从 launchd 卸下并删掉 plist(重启后也不会自己起来);返回有没有真的卸掉东西 */
4527
+ async uninstall() {
4528
+ const installed = existsSync4(this.deps.paths.launchAgentPath);
4529
+ const loaded = await this.print() !== null;
4530
+ if (!installed && !loaded) return false;
4531
+ try {
4532
+ await this.launchctl("bootout", this.target);
4533
+ } catch (e) {
4534
+ if (await this.print() !== null) throw new ServiceError(`\u6CA1\u80FD\u505C\u4E0B\u540E\u53F0\u670D\u52A1\uFF1A${e.message}`);
4535
+ }
4536
+ if (installed) unlinkSync(this.deps.paths.launchAgentPath);
4537
+ return true;
4538
+ }
4539
+ /**
4540
+ * 一屏汇总里的服务状态:以 launchd 为准(plist 被删了、服务仍在跑是 stop 认得的合法状态);
4541
+ * plist 只用来补充提示——不在了就说登录后不会再自动运行,在就检查它写的 node 与入口还在不在
4542
+ */
4543
+ async status() {
4544
+ const plistPath = this.deps.paths.launchAgentPath;
4545
+ let printed;
4546
+ try {
4547
+ printed = await this.print();
4548
+ } catch (e) {
4549
+ return [`\u540E\u53F0\u670D\u52A1\uFF1A\u67E5\u4E0D\u5230\u72B6\u6001\uFF08${e.message.replace(/^查不到后台服务的状态:/, "")}\uFF09`];
4550
+ }
4551
+ const lines = [describeLoaded(printed)];
4552
+ if (!existsSync4(plistPath)) {
4553
+ if (printed !== null) lines.push("\u26A0 plist \u4E0D\u5728\u4E86\uFF1A\u767B\u5F55\u540E\u4E0D\u4F1A\u518D\u81EA\u52A8\u8FD0\u884C\uFF08leo-link start \u8865\u4E0A\uFF09");
4554
+ return lines;
4555
+ }
4556
+ const program = plistProgram(readFileSync3(plistPath, "utf8"));
4557
+ const exists2 = this.deps.exists ?? existsSync4;
4558
+ if (program && !exists2(program.node)) lines.push(`\u26A0 \u540E\u53F0\u670D\u52A1\u7528\u7684 node \u5DF2\u4E0D\u5B58\u5728\uFF1A${program.node}\uFF0C\u8BF7\u91CD\u65B0\u8FD0\u884C leo-link setup`);
4559
+ if (program && !exists2(program.entry)) lines.push(`\u26A0 \u540E\u53F0\u670D\u52A1\u7528\u7684 leo-link \u5DF2\u4E0D\u5B58\u5728\uFF1A${program.entry}\uFF0C\u8BF7\u91CD\u65B0\u8FD0\u884C leo-link setup`);
4560
+ return lines;
4561
+ }
4562
+ };
4563
+
4564
+ // src/version.ts
4565
+ var VERSION = "1.3.0";
4566
+
4567
+ // src/main.ts
4568
+ var defaultDeviceName = (name = hostname()) => name.replace(/\.local$/, "") || "Mac";
4569
+ function cliAppDeps(deps, paths, options) {
4570
+ return {
4571
+ ...deps,
4572
+ handlers: options.logRequests && options.log ? withRequestLog(deps.handlers, options.log) : deps.handlers,
4573
+ // 与桌面端同一种格式,只有 Link 的字段(没有 SPA 会话 cookie、托盘偏好)
4574
+ config: linkConfigStore(paths.configPath, defaultDeviceName()),
4575
+ appVersion: options.version,
4576
+ // 服务端照样当成一台桌面端,只在设备列表里显示为 leo-link
4577
+ client: "cli",
4578
+ // 没有 confirm:开启能力、改配到别的服务器都是在 setup 向导里问过的(或命令行参数明确给的)
4579
+ onState: (state) => {
4580
+ deps.onState(state);
4581
+ options.onState?.(state);
4582
+ }
4583
+ };
4584
+ }
4585
+ function createCliRuntime(paths, options) {
4586
+ const host = nodeHost(paths);
4587
+ const runtime = createLinkRuntime(host, (deps) => new LinkApp(cliAppDeps(deps, paths, options)));
4588
+ return { runtime, host };
4589
+ }
4590
+ function realContext() {
4591
+ const entry = realpathSync2(process.argv[1]);
4592
+ const paths = cliPaths(homedir8(), channelOf(entry));
4593
+ const out = (line) => process.stdout.write(`${line}
4594
+ `);
4595
+ const log = (line) => out(stamp(line));
4596
+ return {
4597
+ paths,
4598
+ version: VERSION,
4599
+ home: realpathSync2(homedir8()),
4600
+ out,
4601
+ log,
4602
+ createRuntime: (options) => {
4603
+ const { runtime, host } = createCliRuntime(paths, { ...options, version: VERSION, log });
4604
+ return { app: runtime.app, host, start: () => runtime.start(), stop: () => runtime.stop() };
4605
+ },
4606
+ service: new LaunchdService({ paths, uid: process.getuid(), execPath: process.execPath, entry, version: VERSION, run: run2, realpath: realpath9 }),
4607
+ fetch: globalThis.fetch,
4608
+ prompter: makePrompter(),
4609
+ followLog: (path) => followLog(path),
4610
+ waitForSignal: () => new Promise((resolve3) => {
4611
+ process.once("SIGINT", () => resolve3("SIGINT"));
4612
+ process.once("SIGTERM", () => resolve3("SIGTERM"));
4613
+ }),
4614
+ refreshShellPath: () => void shellPath.refresh()
4615
+ };
4616
+ }
4617
+ function followLog(path, spawnImpl = spawn4) {
4618
+ return new Promise((resolve3, reject) => {
4619
+ const ignore = () => {
4620
+ };
4621
+ process.on("SIGINT", ignore);
4622
+ const child = spawnImpl("/usr/bin/tail", ["-n", "100", "-F", path], { stdio: "inherit" });
4623
+ const done = () => process.off("SIGINT", ignore);
4624
+ child.once("error", (e) => {
4625
+ done();
4626
+ reject(e);
4627
+ });
4628
+ child.once("close", (code) => {
4629
+ done();
4630
+ resolve3(code ?? 0);
4631
+ });
4632
+ });
4633
+ }
4634
+ function exitQuietlyOnEpipe(stream, exit = process.exit) {
4635
+ stream.on("error", (e) => {
4636
+ if (e.code !== "EPIPE") throw e;
4637
+ exit(0);
4638
+ });
4639
+ }
4640
+ async function main(argv) {
4641
+ exitQuietlyOnEpipe(process.stdout);
4642
+ const code = await run(argv, realContext());
4643
+ process.exitCode = code;
4644
+ setTimeout(() => process.exit(code), 1e3).unref();
4645
+ }
4646
+
4647
+ // src/index.ts
4648
+ void main(process.argv.slice(2));