@saltpub/xiaojiu-agent-bridge 0.1.9 → 0.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -20,6 +20,386 @@ var manifest = JSON.parse(readFileSync(packageJsonPath, "utf8"));
20
20
  var packageName = manifest.name;
21
21
  var version = manifest.version;
22
22
 
23
+ // src/selfupdate/install.ts
24
+ import { existsSync as existsSync2, readFileSync as readFileSync3 } from "fs";
25
+ import { dirname as dirname3, join as join5 } from "path";
26
+ import { fileURLToPath as fileURLToPath2 } from "url";
27
+
28
+ // src/config/app-paths.ts
29
+ import { homedir } from "os";
30
+ import { join as join2 } from "path";
31
+ var DEFAULT_PROFILE = "claude";
32
+ function resolveAppPaths(opts = {}) {
33
+ const rootDir = opts.rootDir ?? process.env.XIAOJIU_BRIDGE_HOME ?? join2(homedir(), ".xiaojiu-agent-bridge");
34
+ const profile2 = normalizeProfileName(opts.profile ?? DEFAULT_PROFILE);
35
+ const profileDir = join2(rootDir, "profiles", profile2);
36
+ const registryDir = join2(rootDir, "registry");
37
+ const userLockDir = join2(registryDir, "locks");
38
+ return {
39
+ rootDir,
40
+ profile: profile2,
41
+ profileDir,
42
+ defaultWorkspaceDir: join2(`${rootDir}-workspaces`, profile2, "default"),
43
+ configFile: join2(rootDir, "config.json"),
44
+ activeProfileFile: join2(rootDir, "active-profile"),
45
+ sessionsFile: join2(profileDir, "sessions.json"),
46
+ workspacesFile: join2(profileDir, "workspaces.json"),
47
+ promptsFile: join2(profileDir, "prompts.json"),
48
+ secretsFile: join2(profileDir, "secrets.enc"),
49
+ keystoreSaltFile: join2(profileDir, ".keystore.salt"),
50
+ secretsGetterScript: join2(rootDir, "secrets-getter"),
51
+ mediaDir: join2(profileDir, "media"),
52
+ logsDir: join2(profileDir, "logs"),
53
+ uiFile: join2(profileDir, "ui.json"),
54
+ hostUiFile: join2(rootDir, "ui.json"),
55
+ hostLogsDir: join2(rootDir, "logs"),
56
+ hostLockFile: join2(userLockDir, "supervisor.lock"),
57
+ updateStateFile: join2(rootDir, "update-state.json"),
58
+ updateDir: join2(rootDir, "update"),
59
+ versionsDir: join2(rootDir, "versions"),
60
+ launcherDir: join2(rootDir, "launcher"),
61
+ launcherFile: join2(rootDir, "launcher", "launcher.mjs"),
62
+ currentVersionFile: join2(rootDir, "update", "current.json"),
63
+ pendingVersionFile: join2(rootDir, "update", "pending.json"),
64
+ bootStateFile: join2(rootDir, "update", "boot.json"),
65
+ badVersionsFile: join2(rootDir, "update", "bad.json"),
66
+ stageLockFile: join2(rootDir, "update", "stage.lock"),
67
+ selfUpdateLogFile: join2(rootDir, "update", "self-update.log"),
68
+ registryDir,
69
+ userRegistryFile: join2(registryDir, "processes.json"),
70
+ userLockDir,
71
+ profileLockFile: join2(userLockDir, "profile", `${profile2}.lock`),
72
+ appLockFile: (appId) => join2(userLockDir, "app", `${lockSafeName(appId)}.lock`)
73
+ };
74
+ }
75
+ function normalizeProfileName(profile2) {
76
+ const trimmed = profile2.trim();
77
+ if (!trimmed) throw new Error("profile name is required");
78
+ if (/[\u0000-\u001f\s/\\:*?"<>|]/.test(trimmed) || trimmed === "." || trimmed === "..") {
79
+ throw new Error(`invalid profile name: ${profile2}`);
80
+ }
81
+ return trimmed;
82
+ }
83
+ function lockSafeName(value) {
84
+ return value.replace(/[^A-Za-z0-9._-]/g, "_");
85
+ }
86
+
87
+ // src/config/paths.ts
88
+ var appPaths = resolveAppPaths();
89
+ var paths = {
90
+ ...appPaths,
91
+ appDir: appPaths.rootDir,
92
+ cacheDir: appPaths.rootDir,
93
+ processesFile: appPaths.userRegistryFile
94
+ /**
95
+ * Thin shell wrapper that exec-provider consumers invoke
96
+ * to resolve secrets from the bridge's encrypted store.
97
+ * Written user-owned and non-symlinked so it passes the
98
+ * AssertSecurePath audit on machines where `node` is a Homebrew/Volta
99
+ * symlink or root-owned (`/usr/bin/node`). Wrapper internals do the
100
+ * `node ... secrets get` invocation; the wrapper is the audited path.
101
+ */
102
+ };
103
+
104
+ // src/selfupdate/store.ts
105
+ import { readFileSync as readFileSync2 } from "fs";
106
+ import { mkdir as mkdir2, readdir, readFile, rm as rm2 } from "fs/promises";
107
+ import { dirname as dirname2, join as join4 } from "path";
108
+
109
+ // src/platform/atomic-write.ts
110
+ import { randomBytes } from "crypto";
111
+ import { chmod, mkdir, open, rm } from "fs/promises";
112
+ import { basename, dirname, join as join3 } from "path";
113
+ import { promisify } from "util";
114
+ import gracefulFs from "graceful-fs";
115
+ var gracefulRename = promisify(gracefulFs.rename);
116
+ var DEFAULT_RENAME_ATTEMPTS = 5;
117
+ var DEFAULT_RETRY_DELAY_MS = 25;
118
+ async function writeFileAtomic(path4, data, opts = {}) {
119
+ await mkdir(dirname(path4), { recursive: true });
120
+ const tmp = join3(
121
+ dirname(path4),
122
+ `.${basename(path4)}.tmp-${process.pid}-${Date.now()}-${randomBytes(3).toString("hex")}`
123
+ );
124
+ try {
125
+ const handle2 = await open(tmp, "w", opts.mode ?? 384);
126
+ try {
127
+ await handle2.writeFile(data);
128
+ try {
129
+ await handle2.sync();
130
+ } catch (err) {
131
+ if (!isIgnorableWindowsFsyncError(err)) throw err;
132
+ }
133
+ } finally {
134
+ await handle2.close();
135
+ }
136
+ await chmod(tmp, opts.mode ?? 384);
137
+ await renameWithRetry(tmp, path4, opts);
138
+ await fsyncDir(dirname(path4));
139
+ } catch (err) {
140
+ await rm(tmp, { force: true }).catch(() => {
141
+ });
142
+ throw err;
143
+ }
144
+ }
145
+ async function renameWithRetry(from, to, opts) {
146
+ const maxAttempts = opts.maxRenameAttempts ?? DEFAULT_RENAME_ATTEMPTS;
147
+ const delayMs = opts.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS;
148
+ const rename4 = opts.rename ?? ((src, dest, fallback) => fallback(src, dest));
149
+ let lastErr;
150
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
151
+ try {
152
+ await rename4(from, to, gracefulRename);
153
+ return;
154
+ } catch (err) {
155
+ lastErr = err;
156
+ if (!isTransientRenameError(err) || attempt === maxAttempts) break;
157
+ await sleep(delayMs * attempt);
158
+ }
159
+ }
160
+ throw lastErr;
161
+ }
162
+ function isTransientRenameError(err) {
163
+ const code = err?.code;
164
+ return code === "EPERM" || code === "EBUSY";
165
+ }
166
+ function isIgnorableWindowsFsyncError(err) {
167
+ return process.platform === "win32" && err?.code === "EPERM";
168
+ }
169
+ async function fsyncDir(path4) {
170
+ try {
171
+ const handle2 = await open(path4, "r");
172
+ try {
173
+ await handle2.sync();
174
+ } finally {
175
+ await handle2.close();
176
+ }
177
+ } catch {
178
+ }
179
+ }
180
+ function sleep(ms) {
181
+ return new Promise((resolve5) => setTimeout(resolve5, ms));
182
+ }
183
+
184
+ // src/selfupdate/version-check.ts
185
+ var REGISTRY_URL = "https://registry.npmjs.org";
186
+ var PASSIVE_REQUEST_TIMEOUT_MS = 1500;
187
+ var EXPLICIT_REQUEST_TIMEOUT_MS = 1e4;
188
+ function compareVersions(left, right) {
189
+ const a = parseVersion(left);
190
+ const b = parseVersion(right);
191
+ for (let index = 0; index < 3; index += 1) {
192
+ const difference = (a.numbers[index] ?? 0) - (b.numbers[index] ?? 0);
193
+ if (difference !== 0) return difference;
194
+ }
195
+ if (a.prerelease.length === 0 && b.prerelease.length === 0) return 0;
196
+ if (a.prerelease.length === 0) return 1;
197
+ if (b.prerelease.length === 0) return -1;
198
+ const length = Math.max(a.prerelease.length, b.prerelease.length);
199
+ for (let index = 0; index < length; index += 1) {
200
+ const leftPart = a.prerelease[index];
201
+ const rightPart = b.prerelease[index];
202
+ if (leftPart === void 0) return -1;
203
+ if (rightPart === void 0) return 1;
204
+ if (leftPart === rightPart) continue;
205
+ const leftNumeric = /^\d+$/.test(leftPart);
206
+ const rightNumeric = /^\d+$/.test(rightPart);
207
+ if (leftNumeric && rightNumeric) {
208
+ if (leftPart.length !== rightPart.length) return leftPart.length - rightPart.length;
209
+ return leftPart < rightPart ? -1 : 1;
210
+ }
211
+ if (leftNumeric) return -1;
212
+ if (rightNumeric) return 1;
213
+ return leftPart < rightPart ? -1 : 1;
214
+ }
215
+ return 0;
216
+ }
217
+ function parseUpdateInfo(metadata, currentVersion = version, expectedName = packageName) {
218
+ if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) throw new Error("Invalid npm Registry package metadata");
219
+ const pkg = metadata;
220
+ if (pkg.name !== expectedName || typeof pkg.version !== "string") throw new Error("Invalid npm Registry package identity or version");
221
+ const current = parseVersion(currentVersion);
222
+ const latest = parseVersion(pkg.version);
223
+ if (current.prerelease.length === 0 && latest.prerelease.length > 0) {
224
+ throw new Error("npm Registry latest points to a prerelease; refusing to update a stable installation");
225
+ }
226
+ if (compareVersions(pkg.version, currentVersion) <= 0) return void 0;
227
+ const update = pkg.xiaojiu?.update;
228
+ return {
229
+ currentVersion,
230
+ latestVersion: pkg.version,
231
+ highlights: stringList(update?.highlights),
232
+ breakingChanges: stringList(update?.breakingChanges),
233
+ securityFix: update?.securityFix === true,
234
+ requiresRestart: update?.requiresRestart === true
235
+ };
236
+ }
237
+ async function fetchUpdateInfo(options = {}) {
238
+ const fetchImpl = options.fetchImpl ?? fetch;
239
+ const name = options.packageName ?? packageName;
240
+ const controller = new AbortController();
241
+ const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? PASSIVE_REQUEST_TIMEOUT_MS);
242
+ try {
243
+ const response = await fetchImpl(`${REGISTRY_URL}/${encodeURIComponent(name)}/latest`, {
244
+ headers: { accept: "application/json" },
245
+ signal: controller.signal
246
+ });
247
+ if (!response.ok) {
248
+ if (options.throwOnError) throw new Error(`npm Registry returned ${response.status}`);
249
+ return void 0;
250
+ }
251
+ const metadata = await response.json();
252
+ return parseUpdateInfo(metadata, options.currentVersion ?? version, name);
253
+ } catch (error) {
254
+ if (options.throwOnError) throw error;
255
+ return void 0;
256
+ } finally {
257
+ clearTimeout(timer);
258
+ }
259
+ }
260
+ function parseVersion(value) {
261
+ const match = value.match(
262
+ /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/
263
+ );
264
+ if (!match || match[0] !== value) throw new Error(`invalid semantic version: ${value}`);
265
+ if (![match[1], match[2], match[3]].every((part) => Number.isSafeInteger(Number(part)))) {
266
+ throw new Error(`invalid semantic version: ${value}`);
267
+ }
268
+ return {
269
+ numbers: [Number(match[1]), Number(match[2]), Number(match[3])],
270
+ prerelease: match[4]?.split(".") ?? []
271
+ };
272
+ }
273
+ function stringList(value) {
274
+ if (!Array.isArray(value)) return [];
275
+ return value.filter((item) => typeof item === "string").map((item) => item.replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").trim().slice(0, 200)).filter((item) => item.length > 0).slice(0, 5);
276
+ }
277
+
278
+ // src/selfupdate/store.ts
279
+ function updateLayout(rootDir) {
280
+ return {
281
+ updateDir: join4(rootDir, "update"),
282
+ versionsDir: join4(rootDir, "versions"),
283
+ launcherDir: join4(rootDir, "launcher"),
284
+ launcherFile: join4(rootDir, "launcher", "launcher.mjs"),
285
+ currentVersionFile: join4(rootDir, "update", "current.json"),
286
+ pendingVersionFile: join4(rootDir, "update", "pending.json"),
287
+ bootStateFile: join4(rootDir, "update", "boot.json"),
288
+ badVersionsFile: join4(rootDir, "update", "bad.json"),
289
+ stageLockFile: join4(rootDir, "update", "stage.lock"),
290
+ selfUpdateLogFile: join4(rootDir, "update", "self-update.log")
291
+ };
292
+ }
293
+ function versionDir(layout, version3) {
294
+ return join4(layout.versionsDir, version3);
295
+ }
296
+ function packageDirOf(installRoot, name = packageName) {
297
+ return join4(installRoot, "node_modules", ...name.split("/"));
298
+ }
299
+ async function readJson(file) {
300
+ try {
301
+ return JSON.parse(await readFile(file, "utf8"));
302
+ } catch {
303
+ return void 0;
304
+ }
305
+ }
306
+ async function writeJson(file, value) {
307
+ await mkdir2(dirname2(file), { recursive: true });
308
+ await writeFileAtomic(file, `${JSON.stringify(value, null, 2)}
309
+ `, { mode: 384 });
310
+ }
311
+ function isPointer(value) {
312
+ if (!value || typeof value !== "object") return false;
313
+ const v = value;
314
+ return typeof v.version === "string" && typeof v.dir === "string";
315
+ }
316
+ function readCurrent(layout) {
317
+ return readJson(layout.currentVersionFile).then((v) => v && isPointer(v) ? v : void 0);
318
+ }
319
+ function readCurrentSync(layout) {
320
+ try {
321
+ const value = JSON.parse(readFileSync2(layout.currentVersionFile, "utf8"));
322
+ return value && isPointer(value) ? value : void 0;
323
+ } catch {
324
+ return void 0;
325
+ }
326
+ }
327
+ function writeCurrent(layout, pointer) {
328
+ return writeJson(layout.currentVersionFile, pointer);
329
+ }
330
+ function writePending(layout, pending) {
331
+ return writeJson(layout.pendingVersionFile, pending);
332
+ }
333
+ async function readBadVersions(layout) {
334
+ const bad = await readJson(layout.badVersionsFile);
335
+ return Array.isArray(bad?.versions) ? bad.versions.filter((v) => typeof v === "string") : [];
336
+ }
337
+ async function gcVersions(layout, keep = 3) {
338
+ const current = await readCurrent(layout);
339
+ const protectedDirs = new Set(
340
+ [current?.dir, current?.previous?.dir].filter((d) => typeof d === "string")
341
+ );
342
+ let entries;
343
+ try {
344
+ entries = await readdir(layout.versionsDir);
345
+ } catch {
346
+ return [];
347
+ }
348
+ const removed = [];
349
+ const valid = [];
350
+ for (const name of entries) {
351
+ const dir = join4(layout.versionsDir, name);
352
+ if (!/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(name)) {
353
+ if (!protectedDirs.has(dir)) {
354
+ await rm2(dir, { recursive: true, force: true, maxRetries: 5 });
355
+ removed.push(dir);
356
+ }
357
+ continue;
358
+ }
359
+ if (!protectedDirs.has(dir)) valid.push({ name, dir });
360
+ }
361
+ const dirs = valid.sort((a, b) => compareVersions(a.name, b.name)).reverse().map((entry) => entry.dir);
362
+ for (const dir of dirs.slice(Math.max(keep - protectedDirs.size, 0))) {
363
+ await rm2(dir, { recursive: true, force: true, maxRetries: 5 });
364
+ removed.push(dir);
365
+ }
366
+ return removed;
367
+ }
368
+
369
+ // src/selfupdate/install.ts
370
+ function resolveInstall(options = {}) {
371
+ const pkgDir = options.pkgDir ?? invokingPackageDir();
372
+ const own = readVersionAt(pkgDir) ?? { version, dir: pkgDir };
373
+ if (existsSync2(join5(pkgDir, ".git"))) return { ...own, source: "checkout" };
374
+ const pointer = readCurrentSync(updateLayout(options.rootDir ?? paths.rootDir));
375
+ if (pointer) {
376
+ const pointed = readVersionAt(packageDirOf(pointer.dir));
377
+ if (pointed) return { ...pointed, source: "pointer" };
378
+ }
379
+ return { ...own, source: "bootstrap" };
380
+ }
381
+ function invokingPackageDir() {
382
+ let dir = dirname3(fileURLToPath2(import.meta.url));
383
+ for (; ; ) {
384
+ if (readVersionAt(dir)) return dir;
385
+ const parent = dirname3(dir);
386
+ if (parent === dir) return dir;
387
+ dir = parent;
388
+ }
389
+ }
390
+ function readVersionAt(dir) {
391
+ try {
392
+ const manifest2 = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
393
+ if (typeof manifest2 !== "object" || manifest2 === null) return void 0;
394
+ const name = "name" in manifest2 ? manifest2.name : void 0;
395
+ const found = "version" in manifest2 ? manifest2.version : void 0;
396
+ if (name !== packageName || typeof found !== "string" || found.length === 0) return void 0;
397
+ return { version: found, dir };
398
+ } catch {
399
+ return void 0;
400
+ }
401
+ }
402
+
23
403
  // src/platform/spawn.ts
24
404
  import crossSpawn from "cross-spawn";
25
405
  import { execFile } from "child_process";
@@ -176,8 +556,8 @@ async function checkAgentVersion(input) {
176
556
  );
177
557
  return;
178
558
  }
179
- const version2 = (stdout.trim() || stderr.trim()).split("\n")[0]?.trim();
180
- if (!version2) {
559
+ const version3 = (stdout.trim() || stderr.trim()).split("\n")[0]?.trim();
560
+ if (!version3) {
181
561
  reject4(
182
562
  new AgentPreflightError({
183
563
  ...base(),
@@ -188,7 +568,7 @@ async function checkAgentVersion(input) {
188
568
  );
189
569
  return;
190
570
  }
191
- resolve5(version2);
571
+ resolve5(version3);
192
572
  });
193
573
  });
194
574
  });
@@ -484,176 +864,25 @@ function getRunIdleTimeoutMs(cfg) {
484
864
  }
485
865
 
486
866
  // src/cli/commands/update.ts
487
- import { existsSync as existsSync7 } from "fs";
867
+ import { existsSync as existsSync8 } from "fs";
488
868
  import { readFile as readFile7 } from "fs/promises";
489
- import path3 from "path";
490
- import { fileURLToPath as fileURLToPath2 } from "url";
491
-
492
- // src/config/app-paths.ts
493
- import { homedir } from "os";
494
- import { join as join2 } from "path";
495
- var DEFAULT_PROFILE = "claude";
496
- function resolveAppPaths(opts = {}) {
497
- const rootDir = opts.rootDir ?? process.env.XIAOJIU_BRIDGE_HOME ?? join2(homedir(), ".xiaojiu-agent-bridge");
498
- const profile2 = normalizeProfileName(opts.profile ?? DEFAULT_PROFILE);
499
- const profileDir = join2(rootDir, "profiles", profile2);
500
- const registryDir = join2(rootDir, "registry");
501
- const userLockDir = join2(registryDir, "locks");
502
- return {
503
- rootDir,
504
- profile: profile2,
505
- profileDir,
506
- defaultWorkspaceDir: join2(`${rootDir}-workspaces`, profile2, "default"),
507
- configFile: join2(rootDir, "config.json"),
508
- activeProfileFile: join2(rootDir, "active-profile"),
509
- sessionsFile: join2(profileDir, "sessions.json"),
510
- workspacesFile: join2(profileDir, "workspaces.json"),
511
- promptsFile: join2(profileDir, "prompts.json"),
512
- secretsFile: join2(profileDir, "secrets.enc"),
513
- keystoreSaltFile: join2(profileDir, ".keystore.salt"),
514
- secretsGetterScript: join2(rootDir, "secrets-getter"),
515
- mediaDir: join2(profileDir, "media"),
516
- logsDir: join2(profileDir, "logs"),
517
- uiFile: join2(profileDir, "ui.json"),
518
- hostUiFile: join2(rootDir, "ui.json"),
519
- hostLogsDir: join2(rootDir, "logs"),
520
- hostLockFile: join2(userLockDir, "supervisor.lock"),
521
- updateStateFile: join2(rootDir, "update-state.json"),
522
- updateDir: join2(rootDir, "update"),
523
- versionsDir: join2(rootDir, "versions"),
524
- launcherDir: join2(rootDir, "launcher"),
525
- launcherFile: join2(rootDir, "launcher", "launcher.mjs"),
526
- currentVersionFile: join2(rootDir, "update", "current.json"),
527
- pendingVersionFile: join2(rootDir, "update", "pending.json"),
528
- bootStateFile: join2(rootDir, "update", "boot.json"),
529
- badVersionsFile: join2(rootDir, "update", "bad.json"),
530
- stageLockFile: join2(rootDir, "update", "stage.lock"),
531
- selfUpdateLogFile: join2(rootDir, "update", "self-update.log"),
532
- registryDir,
533
- userRegistryFile: join2(registryDir, "processes.json"),
534
- userLockDir,
535
- profileLockFile: join2(userLockDir, "profile", `${profile2}.lock`),
536
- appLockFile: (appId) => join2(userLockDir, "app", `${lockSafeName(appId)}.lock`)
537
- };
538
- }
539
- function normalizeProfileName(profile2) {
540
- const trimmed = profile2.trim();
541
- if (!trimmed) throw new Error("profile name is required");
542
- if (/[\u0000-\u001f\s/\\:*?"<>|]/.test(trimmed) || trimmed === "." || trimmed === "..") {
543
- throw new Error(`invalid profile name: ${profile2}`);
544
- }
545
- return trimmed;
546
- }
547
- function lockSafeName(value) {
548
- return value.replace(/[^A-Za-z0-9._-]/g, "_");
549
- }
550
-
551
- // src/config/paths.ts
552
- var appPaths = resolveAppPaths();
553
- var paths = {
554
- ...appPaths,
555
- appDir: appPaths.rootDir,
556
- cacheDir: appPaths.rootDir,
557
- processesFile: appPaths.userRegistryFile
558
- /**
559
- * Thin shell wrapper that exec-provider consumers invoke
560
- * to resolve secrets from the bridge's encrypted store.
561
- * Written user-owned and non-symlinked so it passes the
562
- * AssertSecurePath audit on machines where `node` is a Homebrew/Volta
563
- * symlink or root-owned (`/usr/bin/node`). Wrapper internals do the
564
- * `node ... secrets get` invocation; the wrapper is the audited path.
565
- */
566
- };
567
-
568
- // src/platform/atomic-write.ts
569
- import { randomBytes } from "crypto";
570
- import { chmod, mkdir, open, rm } from "fs/promises";
571
- import { basename, dirname, join as join3 } from "path";
572
- import { promisify } from "util";
573
- import gracefulFs from "graceful-fs";
574
- var gracefulRename = promisify(gracefulFs.rename);
575
- var DEFAULT_RENAME_ATTEMPTS = 5;
576
- var DEFAULT_RETRY_DELAY_MS = 25;
577
- async function writeFileAtomic(path4, data, opts = {}) {
578
- await mkdir(dirname(path4), { recursive: true });
579
- const tmp = join3(
580
- dirname(path4),
581
- `.${basename(path4)}.tmp-${process.pid}-${Date.now()}-${randomBytes(3).toString("hex")}`
582
- );
583
- try {
584
- const handle2 = await open(tmp, "w", opts.mode ?? 384);
585
- try {
586
- await handle2.writeFile(data);
587
- try {
588
- await handle2.sync();
589
- } catch (err) {
590
- if (!isIgnorableWindowsFsyncError(err)) throw err;
591
- }
592
- } finally {
593
- await handle2.close();
594
- }
595
- await chmod(tmp, opts.mode ?? 384);
596
- await renameWithRetry(tmp, path4, opts);
597
- await fsyncDir(dirname(path4));
598
- } catch (err) {
599
- await rm(tmp, { force: true }).catch(() => {
600
- });
601
- throw err;
602
- }
603
- }
604
- async function renameWithRetry(from, to, opts) {
605
- const maxAttempts = opts.maxRenameAttempts ?? DEFAULT_RENAME_ATTEMPTS;
606
- const delayMs = opts.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS;
607
- const rename4 = opts.rename ?? ((src, dest, fallback) => fallback(src, dest));
608
- let lastErr;
609
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
610
- try {
611
- await rename4(from, to, gracefulRename);
612
- return;
613
- } catch (err) {
614
- lastErr = err;
615
- if (!isTransientRenameError(err) || attempt === maxAttempts) break;
616
- await sleep(delayMs * attempt);
617
- }
618
- }
619
- throw lastErr;
620
- }
621
- function isTransientRenameError(err) {
622
- const code = err?.code;
623
- return code === "EPERM" || code === "EBUSY";
624
- }
625
- function isIgnorableWindowsFsyncError(err) {
626
- return process.platform === "win32" && err?.code === "EPERM";
627
- }
628
- async function fsyncDir(path4) {
629
- try {
630
- const handle2 = await open(path4, "r");
631
- try {
632
- await handle2.sync();
633
- } finally {
634
- await handle2.close();
635
- }
636
- } catch {
637
- }
638
- }
639
- function sleep(ms) {
640
- return new Promise((resolve5) => setTimeout(resolve5, ms));
641
- }
869
+ import path3 from "path";
870
+ import { fileURLToPath as fileURLToPath3 } from "url";
642
871
 
643
872
  // src/cli/commands/update-safety.ts
644
- import { readFile as readFile4, readdir as readdir3, realpath } from "fs/promises";
873
+ import { readFile as readFile5, readdir as readdir4, realpath } from "fs/promises";
645
874
  import path2 from "path";
646
875
 
647
876
  // src/daemon/launchd.ts
648
877
  import { spawnSync } from "child_process";
649
- import { existsSync as existsSync3 } from "fs";
650
- import { mkdir as mkdir2, rm as rm2, writeFile } from "fs/promises";
878
+ import { existsSync as existsSync4 } from "fs";
879
+ import { mkdir as mkdir3, rm as rm3, writeFile } from "fs/promises";
651
880
  import { userInfo } from "os";
652
- import { dirname as dirname3 } from "path";
881
+ import { dirname as dirname5 } from "path";
653
882
 
654
883
  // src/daemon/paths.ts
655
884
  import { homedir as homedir2 } from "os";
656
- import { join as join4 } from "path";
885
+ import { join as join6 } from "path";
657
886
  import { createHash } from "crypto";
658
887
  var SERVICE_NAME = "xiaojiu-agent-bridge.bot";
659
888
  function serviceProfileId(profile2) {
@@ -673,43 +902,43 @@ function launchAgentLabel(profile2 = paths.profile) {
673
902
  return `ai.${serviceNameForProfile(profile2)}`;
674
903
  }
675
904
  function launchAgentPlistPath(profile2 = paths.profile) {
676
- return join4(homedir2(), "Library", "LaunchAgents", `${launchAgentLabel(profile2)}.plist`);
905
+ return join6(homedir2(), "Library", "LaunchAgents", `${launchAgentLabel(profile2)}.plist`);
677
906
  }
678
907
  var SYSTEMD_UNIT_NAME = systemdUnitName();
679
908
  function systemdUnitName(profile2 = paths.profile) {
680
909
  return `${serviceNameForProfile(profile2)}.service`;
681
910
  }
682
911
  function systemdUnitPath(profile2 = paths.profile) {
683
- const base = process.env.XDG_CONFIG_HOME ?? join4(homedir2(), ".config");
684
- return join4(base, "systemd", "user", systemdUnitName(profile2));
912
+ const base = process.env.XDG_CONFIG_HOME ?? join6(homedir2(), ".config");
913
+ return join6(base, "systemd", "user", systemdUnitName(profile2));
685
914
  }
686
915
  var WINDOWS_TASK_NAME = windowsTaskName();
687
916
  function windowsTaskName(profile2 = paths.profile) {
688
917
  return `XiaojiuAgentBridge.Bot.${serviceProfileId(profile2)}`;
689
918
  }
690
919
  function windowsLauncherCmdPath(profile2 = paths.profile) {
691
- return join4(paths.appDir, "daemon", serviceProfileId(profile2), "launcher.cmd");
920
+ return join6(paths.appDir, "daemon", serviceProfileId(profile2), "launcher.cmd");
692
921
  }
693
922
  function windowsLauncherVbsPath(profile2 = paths.profile) {
694
- return join4(paths.appDir, "daemon", serviceProfileId(profile2), "launcher.vbs");
923
+ return join6(paths.appDir, "daemon", serviceProfileId(profile2), "launcher.vbs");
695
924
  }
696
925
  function windowsTaskXmlPath(profile2 = paths.profile) {
697
- return join4(paths.appDir, "daemon", serviceProfileId(profile2), "task.xml");
926
+ return join6(paths.appDir, "daemon", serviceProfileId(profile2), "task.xml");
698
927
  }
699
928
  function daemonLogDir(profile2 = paths.profile) {
700
- return join4(resolveAppPaths({ rootDir: paths.rootDir, profile: profile2 }).logsDir, "daemon");
929
+ return join6(resolveAppPaths({ rootDir: paths.rootDir, profile: profile2 }).logsDir, "daemon");
701
930
  }
702
931
  function daemonStdoutPath(profile2 = paths.profile) {
703
- return join4(daemonLogDir(profile2), "daemon-stdout.log");
932
+ return join6(daemonLogDir(profile2), "daemon-stdout.log");
704
933
  }
705
934
  function daemonStderrPath(profile2 = paths.profile) {
706
- return join4(daemonLogDir(profile2), "daemon-stderr.log");
935
+ return join6(daemonLogDir(profile2), "daemon-stderr.log");
707
936
  }
708
937
 
709
938
  // src/daemon/launch-spec.ts
710
- import { existsSync as existsSync2 } from "fs";
939
+ import { existsSync as existsSync3 } from "fs";
711
940
  import { createRequire } from "module";
712
- import { dirname as dirname2, resolve } from "path";
941
+ import { dirname as dirname4, resolve } from "path";
713
942
  import { pathToFileURL } from "url";
714
943
  function resolveDaemonLaunch(argv1 = process.argv[1], override) {
715
944
  if (override) return override;
@@ -720,8 +949,8 @@ function resolveDaemonLaunch(argv1 = process.argv[1], override) {
720
949
  if (!entryPath.endsWith(".ts")) {
721
950
  return { importArgs: [], entryPath };
722
951
  }
723
- const registerHtml = resolve(dirname2(entryPath), "register-html.mjs");
724
- if (!existsSync2(registerHtml)) {
952
+ const registerHtml = resolve(dirname4(entryPath), "register-html.mjs");
953
+ if (!existsSync3(registerHtml)) {
725
954
  throw new Error(
726
955
  `cannot install a daemon from TypeScript sources (${entryPath}); missing ${registerHtml}`
727
956
  );
@@ -795,12 +1024,12 @@ async function writePlist(profile2, runArgs = ["run"], launch) {
795
1024
  channelHome: paths.rootDir
796
1025
  });
797
1026
  const plistPath = launchAgentPlistPath(profile2);
798
- await mkdir2(dirname3(plistPath), { recursive: true });
799
- await mkdir2(daemonLogDir(profile2), { recursive: true });
1027
+ await mkdir3(dirname5(plistPath), { recursive: true });
1028
+ await mkdir3(daemonLogDir(profile2), { recursive: true });
800
1029
  await writeFile(plistPath, content, "utf8");
801
1030
  }
802
1031
  function plistExists(profile2) {
803
- return existsSync3(launchAgentPlistPath(profile2));
1032
+ return existsSync4(launchAgentPlistPath(profile2));
804
1033
  }
805
1034
  function userTarget() {
806
1035
  return `gui/${userInfo().uid}`;
@@ -850,14 +1079,14 @@ function describeService(profile2) {
850
1079
  return r.stdout || r.stderr || "";
851
1080
  }
852
1081
  async function deletePlist(profile2) {
853
- await rm2(launchAgentPlistPath(profile2), { force: true });
1082
+ await rm3(launchAgentPlistPath(profile2), { force: true });
854
1083
  }
855
1084
 
856
1085
  // src/daemon/schtasks.ts
857
1086
  import { spawnSync as spawnSync2 } from "child_process";
858
- import { existsSync as existsSync4 } from "fs";
859
- import { mkdir as mkdir3, rm as rm3, writeFile as writeFile2 } from "fs/promises";
860
- import { dirname as dirname4 } from "path";
1087
+ import { existsSync as existsSync5 } from "fs";
1088
+ import { mkdir as mkdir4, rm as rm4, writeFile as writeFile2 } from "fs/promises";
1089
+ import { dirname as dirname6 } from "path";
861
1090
  function buildLauncherCmd(inputs) {
862
1091
  const runArgs = inputs.runArgs.join(" ");
863
1092
  const importArgs = (inputs.importArgs ?? []).map((a) => `"${a}"`).join(" ");
@@ -942,8 +1171,8 @@ async function writeLauncherScripts(profile2, runArgs = ["run"], launch) {
942
1171
  runArgs,
943
1172
  channelHome: paths.rootDir
944
1173
  });
945
- await mkdir3(dirname4(cmdPath), { recursive: true });
946
- await mkdir3(daemonLogDir(profile2), { recursive: true });
1174
+ await mkdir4(dirname6(cmdPath), { recursive: true });
1175
+ await mkdir4(daemonLogDir(profile2), { recursive: true });
947
1176
  await writeFile2(cmdPath, content, "utf8");
948
1177
  await writeFile2(vbsPath, buildLauncherVbs(cmdPath), "utf8");
949
1178
  await writeFile2(xmlPath, `\uFEFF${buildTaskXml(profile2, vbsPath)}`, { encoding: "utf16le" });
@@ -1036,16 +1265,16 @@ async function deleteTask(profile2) {
1036
1265
  windowsLauncherVbsPath(profile2),
1037
1266
  windowsTaskXmlPath(profile2)
1038
1267
  ]) {
1039
- if (existsSync4(path4)) await rm3(path4, { force: true });
1268
+ if (existsSync5(path4)) await rm4(path4, { force: true });
1040
1269
  }
1041
1270
  return r;
1042
1271
  }
1043
1272
 
1044
1273
  // src/daemon/systemd.ts
1045
1274
  import { spawnSync as spawnSync3 } from "child_process";
1046
- import { existsSync as existsSync5 } from "fs";
1047
- import { mkdir as mkdir4, rm as rm4, writeFile as writeFile3 } from "fs/promises";
1048
- import { dirname as dirname5 } from "path";
1275
+ import { existsSync as existsSync6 } from "fs";
1276
+ import { mkdir as mkdir5, rm as rm5, writeFile as writeFile3 } from "fs/promises";
1277
+ import { dirname as dirname7 } from "path";
1049
1278
  function buildUnit(inputs) {
1050
1279
  const escape = (s) => s.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
1051
1280
  const runArgs = inputs.runArgs.join(" ");
@@ -1082,12 +1311,12 @@ async function writeUnit(profile2, runArgs = ["run"], launch) {
1082
1311
  channelHome: paths.rootDir
1083
1312
  });
1084
1313
  const unitPath = systemdUnitPath(profile2);
1085
- await mkdir4(dirname5(unitPath), { recursive: true });
1086
- await mkdir4(daemonLogDir(profile2), { recursive: true });
1314
+ await mkdir5(dirname7(unitPath), { recursive: true });
1315
+ await mkdir5(daemonLogDir(profile2), { recursive: true });
1087
1316
  await writeFile3(unitPath, content, "utf8");
1088
1317
  }
1089
1318
  function unitExists(profile2) {
1090
- return existsSync5(systemdUnitPath(profile2));
1319
+ return existsSync6(systemdUnitPath(profile2));
1091
1320
  }
1092
1321
  function runSystemctl(args) {
1093
1322
  const r = spawnSync3("systemctl", ["--user", ...args], { encoding: "utf8" });
@@ -1134,7 +1363,7 @@ async function waitUntilInactive(profile2, timeoutMs = 5e3) {
1134
1363
  return false;
1135
1364
  }
1136
1365
  async function deleteUnit(profile2) {
1137
- await rm4(systemdUnitPath(profile2), { force: true });
1366
+ await rm5(systemdUnitPath(profile2), { force: true });
1138
1367
  }
1139
1368
 
1140
1369
  // src/daemon/service-adapter.ts
@@ -1245,8 +1474,8 @@ function getServiceAdapter(profile2 = "claude", runArgs = ["run"], launch) {
1245
1474
  }
1246
1475
 
1247
1476
  // src/runtime/locks.ts
1248
- import { chmod as chmod2, mkdir as mkdir5, readFile, rm as rm5, unlink, writeFile as writeFile4 } from "fs/promises";
1249
- import { dirname as dirname6 } from "path";
1477
+ import { chmod as chmod2, mkdir as mkdir6, readFile as readFile2, rm as rm6, unlink, writeFile as writeFile4 } from "fs/promises";
1478
+ import { dirname as dirname8 } from "path";
1250
1479
  import * as lockfile from "proper-lockfile";
1251
1480
 
1252
1481
  // src/config/permissions.ts
@@ -1684,7 +1913,7 @@ async function breakDeadRuntimeLock(target) {
1684
1913
  if (!meta || pidAlive(meta.pid)) return false;
1685
1914
  await unlink(runtimeLockMetaFile(target)).catch(() => {
1686
1915
  });
1687
- await rm5(`${target}.lock`, { recursive: true, force: true }).catch(() => {
1916
+ await rm6(`${target}.lock`, { recursive: true, force: true }).catch(() => {
1688
1917
  });
1689
1918
  return true;
1690
1919
  }
@@ -1699,7 +1928,7 @@ function pidAlive(pid) {
1699
1928
  }
1700
1929
  async function readRuntimeLockMeta(target) {
1701
1930
  try {
1702
- const parsed = JSON.parse(await readFile(runtimeLockMetaFile(target), "utf8"));
1931
+ const parsed = JSON.parse(await readFile2(runtimeLockMetaFile(target), "utf8"));
1703
1932
  return isRuntimeLockMeta(parsed) ? parsed : void 0;
1704
1933
  } catch (err) {
1705
1934
  if (err.code === "ENOENT") return void 0;
@@ -1725,7 +1954,7 @@ async function checkRuntimeLock(target) {
1725
1954
  }
1726
1955
  }
1727
1956
  async function acquireRuntimeLock(meta) {
1728
- await mkdir5(dirname6(meta.target), { recursive: true });
1957
+ await mkdir6(dirname8(meta.target), { recursive: true });
1729
1958
  await writeFile4(meta.target, "", { flag: "a", mode: 384 });
1730
1959
  await chmod2(meta.target, 384);
1731
1960
  let release;
@@ -1769,17 +1998,17 @@ function isRuntimeLockMeta(value) {
1769
1998
  import { randomBytes as randomBytes2 } from "crypto";
1770
1999
  import {
1771
2000
  closeSync,
1772
- existsSync as existsSync6,
2001
+ existsSync as existsSync7,
1773
2002
  fsyncSync,
1774
2003
  mkdirSync,
1775
2004
  openSync,
1776
- readFileSync as readFileSync2,
2005
+ readFileSync as readFileSync4,
1777
2006
  renameSync,
1778
2007
  unlinkSync,
1779
2008
  writeFileSync
1780
2009
  } from "fs";
1781
- import { mkdir as mkdir6, writeFile as writeFile5 } from "fs/promises";
1782
- import { basename as basename2, dirname as dirname7, join as join5 } from "path";
2010
+ import { mkdir as mkdir7, writeFile as writeFile5 } from "fs/promises";
2011
+ import { basename as basename2, dirname as dirname9, join as join7 } from "path";
1783
2012
  import * as lockfile2 from "proper-lockfile";
1784
2013
  var EMPTY = { entries: [] };
1785
2014
  function isValidEntry(e) {
@@ -1808,7 +2037,7 @@ function writeAtomicSync(entries, path4) {
1808
2037
  const tmp = `${path4}.tmp-${process.pid}`;
1809
2038
  const body = `${JSON.stringify({ entries }, null, 2)}
1810
2039
  `;
1811
- mkdirSync(dirname7(path4), { recursive: true });
2040
+ mkdirSync(dirname9(path4), { recursive: true });
1812
2041
  const fd = openSync(tmp, "w", 384);
1813
2042
  try {
1814
2043
  writeFileSync(fd, body, "utf8");
@@ -1817,7 +2046,7 @@ function writeAtomicSync(entries, path4) {
1817
2046
  closeSync(fd);
1818
2047
  }
1819
2048
  renameSync(tmp, path4);
1820
- fsyncDirSync(dirname7(path4));
2049
+ fsyncDirSync(dirname9(path4));
1821
2050
  }
1822
2051
  function generateShortId() {
1823
2052
  return randomBytes2(2).toString("hex");
@@ -1918,7 +2147,7 @@ function withRegistryFileLockSync(registryFile, fn) {
1918
2147
  }
1919
2148
  }
1920
2149
  async function ensureRegistryFile(registryFile) {
1921
- await mkdir6(dirname7(registryFile), { recursive: true });
2150
+ await mkdir7(dirname9(registryFile), { recursive: true });
1922
2151
  const legacy = legacyRegistryFile(registryFile);
1923
2152
  const initial = legacy ? readRegistryFile(legacy) ?? EMPTY : EMPTY;
1924
2153
  try {
@@ -1932,7 +2161,7 @@ async function ensureRegistryFile(registryFile) {
1932
2161
  }
1933
2162
  }
1934
2163
  function ensureRegistryFileSync(registryFile) {
1935
- mkdirSync(dirname7(registryFile), { recursive: true });
2164
+ mkdirSync(dirname9(registryFile), { recursive: true });
1936
2165
  const legacy = legacyRegistryFile(registryFile);
1937
2166
  const initial = legacy ? readRegistryFile(legacy) ?? EMPTY : EMPTY;
1938
2167
  try {
@@ -1979,8 +2208,8 @@ function lockMatchesEntry(lock6, entry, kind) {
1979
2208
  return true;
1980
2209
  }
1981
2210
  function rootDirFromRegistryFile(registryFile) {
1982
- const parent = dirname7(registryFile);
1983
- return basename2(parent) === "registry" ? dirname7(parent) : parent;
2211
+ const parent = dirname9(registryFile);
2212
+ return basename2(parent) === "registry" ? dirname9(parent) : parent;
1984
2213
  }
1985
2214
  function readRaw(path4) {
1986
2215
  const preferred = readRegistryFile(path4);
@@ -1993,7 +2222,7 @@ function readRaw(path4) {
1993
2222
  }
1994
2223
  function readRegistryFile(path4) {
1995
2224
  try {
1996
- const text2 = readFileSync2(path4, "utf8");
2225
+ const text2 = readFileSync4(path4, "utf8");
1997
2226
  const parsed = JSON.parse(text2);
1998
2227
  if (!parsed || !Array.isArray(parsed.entries)) return { entries: [] };
1999
2228
  return { entries: parsed.entries.filter(isValidEntry) };
@@ -2004,10 +2233,10 @@ function readRegistryFile(path4) {
2004
2233
  }
2005
2234
  function legacyRegistryFile(path4) {
2006
2235
  if (basename2(path4) !== "processes.json") return void 0;
2007
- const parent = dirname7(path4);
2236
+ const parent = dirname9(path4);
2008
2237
  if (basename2(parent) !== "registry") return void 0;
2009
- const legacy = join5(dirname7(parent), "processes.json");
2010
- return existsSync6(path4) ? void 0 : legacy;
2238
+ const legacy = join7(dirname9(parent), "processes.json");
2239
+ return existsSync7(path4) ? void 0 : legacy;
2011
2240
  }
2012
2241
  function fsyncDirSync(path4) {
2013
2242
  try {
@@ -2023,14 +2252,14 @@ function fsyncDirSync(path4) {
2023
2252
 
2024
2253
  // src/runtime/listen-sidecar.ts
2025
2254
  import { createServer } from "net";
2026
- import { mkdir as mkdir8, readdir as readdir2, readFile as readFile2, rm as rm8 } from "fs/promises";
2027
- import { dirname as dirname9, join as join7 } from "path";
2255
+ import { mkdir as mkdir9, readdir as readdir3, readFile as readFile3, rm as rm9 } from "fs/promises";
2256
+ import { dirname as dirname11, join as join9 } from "path";
2028
2257
 
2029
2258
  // src/core/logger.ts
2030
2259
  import { AsyncLocalStorage } from "async_hooks";
2031
2260
  import { createWriteStream, mkdirSync as mkdirSync2 } from "fs";
2032
- import { readdir, rename, rm as rm6, stat } from "fs/promises";
2033
- import { join as join6 } from "path";
2261
+ import { readdir as readdir2, rename, rm as rm7, stat } from "fs/promises";
2262
+ import { join as join8 } from "path";
2034
2263
 
2035
2264
  // src/core/telemetry.ts
2036
2265
  var noop = {
@@ -2170,7 +2399,7 @@ function getStream() {
2170
2399
  }
2171
2400
  try {
2172
2401
  mkdirSync2(dir, { recursive: true });
2173
- stream = createWriteStream(join6(dir, logFileName(today)), { flags: "a" });
2402
+ stream = createWriteStream(join8(dir, logFileName(today)), { flags: "a" });
2174
2403
  currentDate = today;
2175
2404
  return stream;
2176
2405
  } catch {
@@ -2595,7 +2824,7 @@ async function gcOldLogs(extraDirs = []) {
2595
2824
  for (const dir of dirs) {
2596
2825
  let entries;
2597
2826
  try {
2598
- entries = await readdir(dir);
2827
+ entries = await readdir2(dir);
2599
2828
  } catch {
2600
2829
  continue;
2601
2830
  }
@@ -2605,13 +2834,13 @@ async function gcOldLogs(extraDirs = []) {
2605
2834
  const fileMs = Date.parse(`${m[1]}-${m[2]}-${m[3]}T00:00:00Z`);
2606
2835
  if (Number.isNaN(fileMs) || fileMs >= cutoff) continue;
2607
2836
  try {
2608
- await rm6(join6(dir, name));
2837
+ await rm7(join8(dir, name));
2609
2838
  removed++;
2610
2839
  } catch {
2611
2840
  }
2612
2841
  }
2613
2842
  for (const name of DAEMON_LOG_NAMES) {
2614
- await rotateIfOversized(join6(dir, name)).catch(() => void 0);
2843
+ await rotateIfOversized(join8(dir, name)).catch(() => void 0);
2615
2844
  }
2616
2845
  }
2617
2846
  if (removed > 0) {
@@ -2628,7 +2857,7 @@ async function rotateIfOversized(path4) {
2628
2857
  }
2629
2858
  if (st.size <= DAEMON_LOG_MAX_BYTES) return;
2630
2859
  const oldPath = `${path4}.old`;
2631
- await rm6(oldPath, { force: true }).catch(() => void 0);
2860
+ await rm7(oldPath, { force: true }).catch(() => void 0);
2632
2861
  await rename(path4, oldPath);
2633
2862
  log.info("logger", "daemon-log-rotated", { rotatedBytes: st.size });
2634
2863
  }
@@ -2673,11 +2902,11 @@ function sanitizeTelemetryError(err) {
2673
2902
  }
2674
2903
 
2675
2904
  // src/runtime/host-lock.ts
2676
- import { mkdir as mkdir7, rm as rm7, writeFile as writeFile6 } from "fs/promises";
2677
- import { dirname as dirname8 } from "path";
2905
+ import { mkdir as mkdir8, rm as rm8, writeFile as writeFile6 } from "fs/promises";
2906
+ import { dirname as dirname10 } from "path";
2678
2907
  import * as lockfile3 from "proper-lockfile";
2679
2908
  async function acquireHostLock(target) {
2680
- await mkdir7(dirname8(target), { recursive: true });
2909
+ await mkdir8(dirname10(target), { recursive: true });
2681
2910
  await writeFile6(target, "", { flag: "a", mode: 384 }).catch(() => {
2682
2911
  });
2683
2912
  try {
@@ -2694,24 +2923,24 @@ async function acquireHostLock(target) {
2694
2923
  }
2695
2924
  async function forceReleaseHostLock(target) {
2696
2925
  await lockfile3.unlock(target, { realpath: false }).catch(() => void 0);
2697
- await rm7(`${target}.lock`, { recursive: true, force: true }).catch(() => void 0);
2926
+ await rm8(`${target}.lock`, { recursive: true, force: true }).catch(() => void 0);
2698
2927
  }
2699
2928
 
2700
2929
  // src/runtime/listen-sidecar.ts
2701
2930
  function listenSidecarFile(port, rootDir) {
2702
- return join7(resolveAppPaths({ rootDir }).rootDir, "registry", "listen", `${port}.json`);
2931
+ return join9(resolveAppPaths({ rootDir }).rootDir, "registry", "listen", `${port}.json`);
2703
2932
  }
2704
2933
  function listenLockFile(port, rootDir) {
2705
- return join7(resolveAppPaths({ rootDir }).userLockDir, "listen", `${port}.lock`);
2934
+ return join9(resolveAppPaths({ rootDir }).userLockDir, "listen", `${port}.lock`);
2706
2935
  }
2707
2936
  async function writeListenSidecar(file, record5) {
2708
- await mkdir8(dirname9(file), { recursive: true });
2937
+ await mkdir9(dirname11(file), { recursive: true });
2709
2938
  await writeFileAtomic(file, `${JSON.stringify(record5, null, 2)}
2710
2939
  `, { mode: 384 });
2711
2940
  }
2712
2941
  async function readListenSidecar(file) {
2713
2942
  try {
2714
- const parsed = JSON.parse(await readFile2(file, "utf8"));
2943
+ const parsed = JSON.parse(await readFile3(file, "utf8"));
2715
2944
  if (typeof parsed.pid !== "number" || typeof parsed.port !== "number" || typeof parsed.url !== "string" || typeof parsed.token !== "string") {
2716
2945
  return void 0;
2717
2946
  }
@@ -2721,7 +2950,7 @@ async function readListenSidecar(file) {
2721
2950
  }
2722
2951
  }
2723
2952
  async function removeListenSidecar(file) {
2724
- await rm8(file, { force: true }).catch(
2953
+ await rm9(file, { force: true }).catch(
2725
2954
  (err) => log.warn("listen", "sidecar-remove-failed", { err: String(err) })
2726
2955
  );
2727
2956
  }
@@ -2749,17 +2978,17 @@ async function liveListenSidecar(port, rootDir) {
2749
2978
  return sidecar;
2750
2979
  }
2751
2980
  async function listLiveListenSidecars(rootDir) {
2752
- const dir = join7(resolveAppPaths({ rootDir }).rootDir, "registry", "listen");
2981
+ const dir = join9(resolveAppPaths({ rootDir }).rootDir, "registry", "listen");
2753
2982
  let names = [];
2754
2983
  try {
2755
- names = await readdir2(dir);
2984
+ names = await readdir3(dir);
2756
2985
  } catch {
2757
2986
  return [];
2758
2987
  }
2759
2988
  const live = [];
2760
2989
  for (const name of names) {
2761
2990
  if (!name.endsWith(".json")) continue;
2762
- const file = join7(dir, name);
2991
+ const file = join9(dir, name);
2763
2992
  const sidecar = await readListenSidecar(file);
2764
2993
  if (!sidecar) continue;
2765
2994
  if (!isAlive(sidecar.pid)) {
@@ -2801,9 +3030,9 @@ async function waitForListenOwner(port, host, rootDir, graceMs) {
2801
3030
  }
2802
3031
 
2803
3032
  // src/ui/sidecar.ts
2804
- import { readFile as readFile3, rm as rm9 } from "fs/promises";
2805
- import { dirname as dirname10 } from "path";
2806
- import { mkdir as mkdir9 } from "fs/promises";
3033
+ import { readFile as readFile4, rm as rm10 } from "fs/promises";
3034
+ import { dirname as dirname12 } from "path";
3035
+ import { mkdir as mkdir10 } from "fs/promises";
2807
3036
  async function writeUiSidecar(uiFile, handle2, startedAt) {
2808
3037
  const record5 = {
2809
3038
  url: handle2.url,
@@ -2812,13 +3041,13 @@ async function writeUiSidecar(uiFile, handle2, startedAt) {
2812
3041
  pid: process.pid,
2813
3042
  startedAt
2814
3043
  };
2815
- await mkdir9(dirname10(uiFile), { recursive: true });
3044
+ await mkdir10(dirname12(uiFile), { recursive: true });
2816
3045
  await writeFileAtomic(uiFile, `${JSON.stringify(record5, null, 2)}
2817
3046
  `, { mode: 384 });
2818
3047
  }
2819
3048
  async function readUiSidecar(uiFile) {
2820
3049
  try {
2821
- const parsed = JSON.parse(await readFile3(uiFile, "utf8"));
3050
+ const parsed = JSON.parse(await readFile4(uiFile, "utf8"));
2822
3051
  if (!parsed.url || !parsed.token || typeof parsed.port !== "number") return void 0;
2823
3052
  return parsed;
2824
3053
  } catch {
@@ -2826,7 +3055,7 @@ async function readUiSidecar(uiFile) {
2826
3055
  }
2827
3056
  }
2828
3057
  async function removeUiSidecar(uiFile) {
2829
- await rm9(uiFile, { force: true }).catch(
3058
+ await rm10(uiFile, { force: true }).catch(
2830
3059
  (err) => log.warn("ui", "sidecar-remove-failed", { err: String(err) })
2831
3060
  );
2832
3061
  }
@@ -3016,7 +3245,7 @@ async function packageRoot(entry, name) {
3016
3245
  }
3017
3246
  async function readProcessArgs(pid) {
3018
3247
  if (process.platform === "linux") {
3019
- const args = (await readFile4(`/proc/${pid}/cmdline`, "utf8")).split("\0").filter(Boolean);
3248
+ const args = (await readFile5(`/proc/${pid}/cmdline`, "utf8")).split("\0").filter(Boolean);
3020
3249
  const cwd = await realpath(`/proc/${pid}/cwd`);
3021
3250
  return args.map((arg) => /(?:^|\/)dist\/cli\.js$|(?:^|\/)bin\/xiaojiu-agent-bridge\.mjs$|(?:^|\/)src\/cli\/index\.ts$/.test(arg) ? path2.resolve(cwd, arg) : arg);
3022
3251
  }
@@ -3052,7 +3281,7 @@ function capture(command, args) {
3052
3281
  }
3053
3282
  async function optionalRead(file) {
3054
3283
  try {
3055
- return await readFile4(file, "utf8");
3284
+ return await readFile5(file, "utf8");
3056
3285
  } catch (error) {
3057
3286
  if (error.code === "ENOENT") return void 0;
3058
3287
  throw error;
@@ -3060,7 +3289,7 @@ async function optionalRead(file) {
3060
3289
  }
3061
3290
  async function namesIn(dir) {
3062
3291
  try {
3063
- return await readdir3(dir);
3292
+ return await readdir4(dir);
3064
3293
  } catch (error) {
3065
3294
  if (error.code === "ENOENT") return [];
3066
3295
  throw error;
@@ -3073,191 +3302,10 @@ function unknownState(detail) {
3073
3302
  return new Error(`Cannot safely update: ${detail}. Inspect \`xiaojiu-agent-bridge ps\` and stop the bridge/listen/UI processes before retrying. No files were changed.`);
3074
3303
  }
3075
3304
 
3076
- // src/selfupdate/version-check.ts
3077
- var REGISTRY_URL = "https://registry.npmjs.org";
3078
- var PASSIVE_REQUEST_TIMEOUT_MS = 1500;
3079
- var EXPLICIT_REQUEST_TIMEOUT_MS = 1e4;
3080
- function compareVersions(left, right) {
3081
- const a = parseVersion(left);
3082
- const b = parseVersion(right);
3083
- for (let index = 0; index < 3; index += 1) {
3084
- const difference = (a.numbers[index] ?? 0) - (b.numbers[index] ?? 0);
3085
- if (difference !== 0) return difference;
3086
- }
3087
- if (a.prerelease.length === 0 && b.prerelease.length === 0) return 0;
3088
- if (a.prerelease.length === 0) return 1;
3089
- if (b.prerelease.length === 0) return -1;
3090
- const length = Math.max(a.prerelease.length, b.prerelease.length);
3091
- for (let index = 0; index < length; index += 1) {
3092
- const leftPart = a.prerelease[index];
3093
- const rightPart = b.prerelease[index];
3094
- if (leftPart === void 0) return -1;
3095
- if (rightPart === void 0) return 1;
3096
- if (leftPart === rightPart) continue;
3097
- const leftNumeric = /^\d+$/.test(leftPart);
3098
- const rightNumeric = /^\d+$/.test(rightPart);
3099
- if (leftNumeric && rightNumeric) {
3100
- if (leftPart.length !== rightPart.length) return leftPart.length - rightPart.length;
3101
- return leftPart < rightPart ? -1 : 1;
3102
- }
3103
- if (leftNumeric) return -1;
3104
- if (rightNumeric) return 1;
3105
- return leftPart < rightPart ? -1 : 1;
3106
- }
3107
- return 0;
3108
- }
3109
- function parseUpdateInfo(metadata, currentVersion = version, expectedName = packageName) {
3110
- if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) throw new Error("Invalid npm Registry package metadata");
3111
- const pkg = metadata;
3112
- if (pkg.name !== expectedName || typeof pkg.version !== "string") throw new Error("Invalid npm Registry package identity or version");
3113
- const current = parseVersion(currentVersion);
3114
- const latest = parseVersion(pkg.version);
3115
- if (current.prerelease.length === 0 && latest.prerelease.length > 0) {
3116
- throw new Error("npm Registry latest points to a prerelease; refusing to update a stable installation");
3117
- }
3118
- if (compareVersions(pkg.version, currentVersion) <= 0) return void 0;
3119
- const update = pkg.xiaojiu?.update;
3120
- return {
3121
- currentVersion,
3122
- latestVersion: pkg.version,
3123
- highlights: stringList(update?.highlights),
3124
- breakingChanges: stringList(update?.breakingChanges),
3125
- securityFix: update?.securityFix === true,
3126
- requiresRestart: update?.requiresRestart === true
3127
- };
3128
- }
3129
- async function fetchUpdateInfo(options = {}) {
3130
- const fetchImpl = options.fetchImpl ?? fetch;
3131
- const name = options.packageName ?? packageName;
3132
- const controller = new AbortController();
3133
- const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? PASSIVE_REQUEST_TIMEOUT_MS);
3134
- try {
3135
- const response = await fetchImpl(`${REGISTRY_URL}/${encodeURIComponent(name)}/latest`, {
3136
- headers: { accept: "application/json" },
3137
- signal: controller.signal
3138
- });
3139
- if (!response.ok) {
3140
- if (options.throwOnError) throw new Error(`npm Registry returned ${response.status}`);
3141
- return void 0;
3142
- }
3143
- const metadata = await response.json();
3144
- return parseUpdateInfo(metadata, options.currentVersion ?? version, name);
3145
- } catch (error) {
3146
- if (options.throwOnError) throw error;
3147
- return void 0;
3148
- } finally {
3149
- clearTimeout(timer);
3150
- }
3151
- }
3152
- function parseVersion(value) {
3153
- const match = value.match(
3154
- /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/
3155
- );
3156
- if (!match || match[0] !== value) throw new Error(`invalid semantic version: ${value}`);
3157
- if (![match[1], match[2], match[3]].every((part) => Number.isSafeInteger(Number(part)))) {
3158
- throw new Error(`invalid semantic version: ${value}`);
3159
- }
3160
- return {
3161
- numbers: [Number(match[1]), Number(match[2]), Number(match[3])],
3162
- prerelease: match[4]?.split(".") ?? []
3163
- };
3164
- }
3165
- function stringList(value) {
3166
- if (!Array.isArray(value)) return [];
3167
- return value.filter((item) => typeof item === "string").map((item) => item.replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").trim().slice(0, 200)).filter((item) => item.length > 0).slice(0, 5);
3168
- }
3169
-
3170
3305
  // src/selfupdate/stage.ts
3171
3306
  import { mkdir as mkdir11, mkdtemp, open as open2, readFile as readFile6, rm as rm11 } from "fs/promises";
3172
3307
  import { tmpdir } from "os";
3173
- import { join as join9 } from "path";
3174
-
3175
- // src/selfupdate/store.ts
3176
- import { mkdir as mkdir10, readdir as readdir4, readFile as readFile5, rm as rm10 } from "fs/promises";
3177
- import { dirname as dirname11, join as join8 } from "path";
3178
- function updateLayout(rootDir) {
3179
- return {
3180
- updateDir: join8(rootDir, "update"),
3181
- versionsDir: join8(rootDir, "versions"),
3182
- launcherDir: join8(rootDir, "launcher"),
3183
- launcherFile: join8(rootDir, "launcher", "launcher.mjs"),
3184
- currentVersionFile: join8(rootDir, "update", "current.json"),
3185
- pendingVersionFile: join8(rootDir, "update", "pending.json"),
3186
- bootStateFile: join8(rootDir, "update", "boot.json"),
3187
- badVersionsFile: join8(rootDir, "update", "bad.json"),
3188
- stageLockFile: join8(rootDir, "update", "stage.lock"),
3189
- selfUpdateLogFile: join8(rootDir, "update", "self-update.log")
3190
- };
3191
- }
3192
- function versionDir(layout, version2) {
3193
- return join8(layout.versionsDir, version2);
3194
- }
3195
- function packageDirOf(installRoot, name = packageName) {
3196
- return join8(installRoot, "node_modules", ...name.split("/"));
3197
- }
3198
- async function readJson(file) {
3199
- try {
3200
- return JSON.parse(await readFile5(file, "utf8"));
3201
- } catch {
3202
- return void 0;
3203
- }
3204
- }
3205
- async function writeJson(file, value) {
3206
- await mkdir10(dirname11(file), { recursive: true });
3207
- await writeFileAtomic(file, `${JSON.stringify(value, null, 2)}
3208
- `, { mode: 384 });
3209
- }
3210
- function isPointer(value) {
3211
- if (!value || typeof value !== "object") return false;
3212
- const v = value;
3213
- return typeof v.version === "string" && typeof v.dir === "string";
3214
- }
3215
- function readCurrent(layout) {
3216
- return readJson(layout.currentVersionFile).then((v) => v && isPointer(v) ? v : void 0);
3217
- }
3218
- function writeCurrent(layout, pointer) {
3219
- return writeJson(layout.currentVersionFile, pointer);
3220
- }
3221
- function writePending(layout, pending) {
3222
- return writeJson(layout.pendingVersionFile, pending);
3223
- }
3224
- async function readBadVersions(layout) {
3225
- const bad = await readJson(layout.badVersionsFile);
3226
- return Array.isArray(bad?.versions) ? bad.versions.filter((v) => typeof v === "string") : [];
3227
- }
3228
- async function gcVersions(layout, keep = 3) {
3229
- const current = await readCurrent(layout);
3230
- const protectedDirs = new Set(
3231
- [current?.dir, current?.previous?.dir].filter((d) => typeof d === "string")
3232
- );
3233
- let entries;
3234
- try {
3235
- entries = await readdir4(layout.versionsDir);
3236
- } catch {
3237
- return [];
3238
- }
3239
- const removed = [];
3240
- const valid = [];
3241
- for (const name of entries) {
3242
- const dir = join8(layout.versionsDir, name);
3243
- if (!/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(name)) {
3244
- if (!protectedDirs.has(dir)) {
3245
- await rm10(dir, { recursive: true, force: true, maxRetries: 5 });
3246
- removed.push(dir);
3247
- }
3248
- continue;
3249
- }
3250
- if (!protectedDirs.has(dir)) valid.push({ name, dir });
3251
- }
3252
- const dirs = valid.sort((a, b) => compareVersions(a.name, b.name)).reverse().map((entry) => entry.dir);
3253
- for (const dir of dirs.slice(Math.max(keep - protectedDirs.size, 0))) {
3254
- await rm10(dir, { recursive: true, force: true, maxRetries: 5 });
3255
- removed.push(dir);
3256
- }
3257
- return removed;
3258
- }
3259
-
3260
- // src/selfupdate/stage.ts
3308
+ import { join as join10 } from "path";
3261
3309
  var STAGE_LOCK_STALE_MS = 30 * 60 * 1e3;
3262
3310
  var SMOKE_TIMEOUT_MS = 3e4;
3263
3311
  async function stageVersion(deps) {
@@ -3318,7 +3366,7 @@ async function stageVersion(deps) {
3318
3366
  }
3319
3367
  async function installedVersionMatches(pkgDir, expected) {
3320
3368
  try {
3321
- const manifest2 = JSON.parse(await readFile6(join9(pkgDir, "package.json"), "utf8"));
3369
+ const manifest2 = JSON.parse(await readFile6(join10(pkgDir, "package.json"), "utf8"));
3322
3370
  return typeof manifest2 === "object" && manifest2 !== null && "version" in manifest2 && manifest2.version === expected;
3323
3371
  } catch {
3324
3372
  return false;
@@ -3362,9 +3410,9 @@ function runNpm(args) {
3362
3410
  });
3363
3411
  }
3364
3412
  async function smokeTest(pkgDir, expectedVersion) {
3365
- const fakeHome = await mkdtemp(join9(tmpdir(), "xiaojiu-smoke-"));
3413
+ const fakeHome = await mkdtemp(join10(tmpdir(), "xiaojiu-smoke-"));
3366
3414
  try {
3367
- const bin = join9(pkgDir, "bin", "xiaojiu-agent-bridge.mjs");
3415
+ const bin = join10(pkgDir, "bin", "xiaojiu-agent-bridge.mjs");
3368
3416
  await new Promise((resolve5, reject4) => {
3369
3417
  const child = spawnProcess(process.execPath, [bin, "--version"], {
3370
3418
  stdio: ["ignore", "pipe", "pipe"],
@@ -3407,7 +3455,7 @@ async function maybeShowUpdateNotice() {
3407
3455
  if (Number.isFinite(lastChecked) && Date.now() - lastChecked < CHECK_INTERVAL_MS) return;
3408
3456
  let info;
3409
3457
  try {
3410
- info = await fetchUpdateInfo({ throwOnError: true });
3458
+ info = await fetchUpdateInfo({ throwOnError: true, currentVersion: resolveInstall().version });
3411
3459
  } catch {
3412
3460
  return;
3413
3461
  }
@@ -3419,11 +3467,12 @@ async function maybeShowUpdateNotice() {
3419
3467
  }
3420
3468
  async function runUpdateCheck(options = {}) {
3421
3469
  const name = options.packageName ?? packageName;
3422
- const current = options.currentVersion ?? version;
3423
3470
  const log2 = options.log ?? ((message) => process.stdout.write(`${message}
3424
3471
  `));
3425
3472
  const layout = options.layout ?? updateLayout(paths.rootDir);
3426
- if (!options.checkOnly && await readCurrent(layout)) {
3473
+ const pointer = await readCurrent(layout);
3474
+ const current = options.currentVersion ?? pointer?.version ?? version;
3475
+ if (!options.checkOnly && pointer) {
3427
3476
  const info2 = await fetchUpdateInfo({
3428
3477
  fetchImpl: options.fetchImpl,
3429
3478
  currentVersion: current,
@@ -3531,8 +3580,9 @@ async function runUpdateCheck(options = {}) {
3531
3580
  }
3532
3581
  }
3533
3582
  async function runChangelog(requestedVersion) {
3534
- const changelog = await readFile7(changelogPath(), "utf8");
3535
- const target = requestedVersion ?? version;
3583
+ const install = resolveInstall();
3584
+ const changelog = await readFile7(changelogPath(install.dir), "utf8");
3585
+ const target = requestedVersion ?? install.version;
3536
3586
  const section = extractChangelogSection(changelog, target);
3537
3587
  if (!section) {
3538
3588
  throw new Error(`No changelog entry found for ${target}`);
@@ -3604,15 +3654,16 @@ async function restartLauncherServices() {
3604
3654
  function isUpdateCheckDisabled() {
3605
3655
  return process.env.XIAOJIU_BRIDGE_NO_UPDATE_CHECK === "1" || process.env.CI === "true" || process.env.TERM === "dumb" || !process.stdin.isTTY || !process.stdout.isTTY;
3606
3656
  }
3607
- function changelogPath() {
3608
- const moduleDir = path3.dirname(fileURLToPath2(import.meta.url));
3657
+ function changelogPath(installDir) {
3658
+ const moduleDir = path3.dirname(fileURLToPath3(import.meta.url));
3609
3659
  const candidates = [
3660
+ ...installDir ? [path3.join(installDir, "CHANGELOG.md")] : [],
3610
3661
  path3.resolve(moduleDir, "CHANGELOG.md"),
3611
3662
  path3.resolve(moduleDir, "..", "CHANGELOG.md"),
3612
3663
  path3.resolve(moduleDir, "..", "..", "CHANGELOG.md"),
3613
3664
  path3.resolve(moduleDir, "..", "..", "..", "CHANGELOG.md")
3614
3665
  ];
3615
- const match = candidates.find((candidate) => existsSync7(candidate));
3666
+ const match = candidates.find((candidate) => existsSync8(candidate));
3616
3667
  if (!match) throw new Error("CHANGELOG.md is not included in this installation");
3617
3668
  return match;
3618
3669
  }
@@ -3808,7 +3859,7 @@ async function listSecretIds(storePaths = paths) {
3808
3859
 
3809
3860
  // src/config/profile-store.ts
3810
3861
  import { chmod as chmod3, mkdir as mkdir12, readFile as readFile9, rename as rename2, rm as rm12, rmdir, stat as stat2, writeFile as writeFile7 } from "fs/promises";
3811
- import { dirname as dirname12, join as join10 } from "path";
3862
+ import { dirname as dirname13, join as join11 } from "path";
3812
3863
  import * as lockfile4 from "proper-lockfile";
3813
3864
  async function loadRootConfig(path4) {
3814
3865
  try {
@@ -3880,7 +3931,7 @@ function serializeProfileConfig(profile2) {
3880
3931
  }
3881
3932
  async function withConfigFileLock(configPath, fn) {
3882
3933
  const lockTarget = `${configPath}.lock`;
3883
- await mkdir12(dirname12(lockTarget), { recursive: true });
3934
+ await mkdir12(dirname13(lockTarget), { recursive: true });
3884
3935
  await writeFile7(lockTarget, "", { flag: "a", mode: 384 });
3885
3936
  await chmod3(lockTarget, 384).catch(() => {
3886
3937
  });
@@ -3901,7 +3952,7 @@ async function withConfigFileLock(configPath, fn) {
3901
3952
  }
3902
3953
  }
3903
3954
  async function readActiveProfile(rootDir) {
3904
- const activeProfileFile = join10(
3955
+ const activeProfileFile = join11(
3905
3956
  rootDir ?? process.env.XIAOJIU_BRIDGE_HOME ?? resolveAppPaths().rootDir,
3906
3957
  "active-profile"
3907
3958
  );
@@ -3915,7 +3966,7 @@ async function readActiveProfile(rootDir) {
3915
3966
  }
3916
3967
  }
3917
3968
  async function writeActiveProfile(rootDir, profile2) {
3918
- const activeProfileFile = join10(rootDir, "active-profile");
3969
+ const activeProfileFile = join11(rootDir, "active-profile");
3919
3970
  await writeFileAtomic(activeProfileFile, `${profile2}
3920
3971
  `, { mode: 384 });
3921
3972
  }
@@ -3990,7 +4041,7 @@ async function removeProfile(root, profile2, rootDir, opts = {}) {
3990
4041
  const profileDir = resolveAppPaths({ rootDir, profile: profile2 }).profileDir;
3991
4042
  if (opts.purge) {
3992
4043
  if (!await pathExists(profileDir)) return { root: next, purged: true };
3993
- const trashDir2 = join10(rootDir, ".trash");
4044
+ const trashDir2 = join11(rootDir, ".trash");
3994
4045
  await mkdir12(trashDir2, { recursive: true });
3995
4046
  const stagedTo = await nextArchivePath(trashDir2, profile2, opts.now?.() ?? /* @__PURE__ */ new Date());
3996
4047
  await rename2(profileDir, stagedTo);
@@ -4008,7 +4059,7 @@ async function removeProfile(root, profile2, rootDir, opts = {}) {
4008
4059
  }
4009
4060
  };
4010
4061
  }
4011
- const trashDir = join10(rootDir, ".trash");
4062
+ const trashDir = join11(rootDir, ".trash");
4012
4063
  await mkdir12(trashDir, { recursive: true });
4013
4064
  const archivedTo = await nextArchivePath(trashDir, profile2, opts.now?.() ?? /* @__PURE__ */ new Date());
4014
4065
  await rename2(profileDir, archivedTo);
@@ -4021,7 +4072,7 @@ async function removeProfile(root, profile2, rootDir, opts = {}) {
4021
4072
  };
4022
4073
  }
4023
4074
  async function nextArchivePath(trashDir, profile2, now) {
4024
- const base = join10(trashDir, `${profile2}-${archiveTimestamp(now)}`);
4075
+ const base = join11(trashDir, `${profile2}-${archiveTimestamp(now)}`);
4025
4076
  for (let suffix = 0; ; suffix++) {
4026
4077
  const candidate = suffix === 0 ? base : `${base}-${suffix}`;
4027
4078
  if (!await pathExists(candidate)) return candidate;
@@ -4047,7 +4098,7 @@ function agentKindFromString(value) {
4047
4098
 
4048
4099
  // src/runtime/profile-discovery.ts
4049
4100
  import { readdir as readdir5 } from "fs/promises";
4050
- import { join as join11 } from "path";
4101
+ import { join as join12 } from "path";
4051
4102
  async function listAllProfiles(rootDir) {
4052
4103
  const rootPaths = resolveAppPaths({ rootDir });
4053
4104
  const root = await loadRootConfig(rootPaths.configFile);
@@ -4085,7 +4136,7 @@ async function listAllProfiles(rootDir) {
4085
4136
  });
4086
4137
  }
4087
4138
  async function readProfileStateDirs(rootDir) {
4088
- const profilesDir = join11(rootDir, "profiles");
4139
+ const profilesDir = join12(rootDir, "profiles");
4089
4140
  try {
4090
4141
  const entries = await readdir5(profilesDir, { withFileTypes: true });
4091
4142
  return entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name);
@@ -4096,7 +4147,7 @@ async function readProfileStateDirs(rootDir) {
4096
4147
  }
4097
4148
  async function isLogOnlyProfileState(rootDir, profile2) {
4098
4149
  try {
4099
- const entries = await readdir5(join11(rootDir, "profiles", profile2), { withFileTypes: true });
4150
+ const entries = await readdir5(join12(rootDir, "profiles", profile2), { withFileTypes: true });
4100
4151
  return entries.length === 1 && entries[0]?.isDirectory() === true && entries[0].name === "logs";
4101
4152
  } catch {
4102
4153
  return false;
@@ -4265,12 +4316,12 @@ async function readAllStdin() {
4265
4316
  }
4266
4317
 
4267
4318
  // src/cli/commands/profile.ts
4268
- import { existsSync as existsSync8 } from "fs";
4319
+ import { existsSync as existsSync9 } from "fs";
4269
4320
  import { rm as rm13 } from "fs/promises";
4270
4321
 
4271
4322
  // src/config/secret-resolver.ts
4272
4323
  import { readFile as readFile10 } from "fs/promises";
4273
- import { join as join12, resolve as resolve2 } from "path";
4324
+ import { join as join13, resolve as resolve2 } from "path";
4274
4325
  var ENV_TEMPLATE_RE = /^\$\{([A-Z][A-Z0-9_]{0,127})\}$/;
4275
4326
  var DEFAULT_PROVIDER = "default";
4276
4327
  var DEFAULT_EXEC_TIMEOUT_MS = 5e3;
@@ -4326,7 +4377,7 @@ function resolveEnvRef(ref, pc) {
4326
4377
  return v;
4327
4378
  }
4328
4379
  async function resolveFileRef(ref, pc) {
4329
- const path4 = pc?.path ? join12(pc.path, ref.id) : ref.id;
4380
+ const path4 = pc?.path ? join13(pc.path, ref.id) : ref.id;
4330
4381
  const text2 = await readFile10(path4, "utf8");
4331
4382
  return text2.trim();
4332
4383
  }
@@ -4444,13 +4495,13 @@ async function spawnExecProvider(pc, ref) {
4444
4495
 
4445
4496
  // src/runtime/profile-runtime.ts
4446
4497
  import { mkdir as mkdir14, realpath as realpath4 } from "fs/promises";
4447
- import { dirname as dirname15 } from "path";
4498
+ import { dirname as dirname16 } from "path";
4448
4499
  import * as p2 from "@clack/prompts";
4449
4500
 
4450
4501
  // src/cli/agent-detection.ts
4451
4502
  import { constants } from "fs";
4452
4503
  import { access } from "fs/promises";
4453
- import { delimiter, extname, isAbsolute, join as join13 } from "path";
4504
+ import { delimiter, extname, isAbsolute, join as join14 } from "path";
4454
4505
  async function resolveExecutablePath(command) {
4455
4506
  if (isAbsolute(command)) {
4456
4507
  await access(command, constants.X_OK);
@@ -4469,10 +4520,10 @@ async function resolveExecutablePath(command) {
4469
4520
  throw new Error(`executable not found: ${command}`);
4470
4521
  }
4471
4522
  function executableCandidates(dir, command) {
4472
- const candidates = [join13(dir, command)];
4523
+ const candidates = [join14(dir, command)];
4473
4524
  if (extname(command)) return candidates;
4474
4525
  for (const ext of pathExts()) {
4475
- candidates.push(join13(dir, `${command}${ext}`));
4526
+ candidates.push(join14(dir, `${command}${ext}`));
4476
4527
  }
4477
4528
  return candidates;
4478
4529
  }
@@ -4502,12 +4553,12 @@ async function detectInstalledAgents() {
4502
4553
 
4503
4554
  // src/cli/profile-bootstrap.ts
4504
4555
  import { mkdir as mkdir13, realpath as realpath3 } from "fs/promises";
4505
- import { join as join14 } from "path";
4556
+ import { join as join15 } from "path";
4506
4557
 
4507
4558
  // src/policy/workspace.ts
4508
4559
  import { realpath as realpath2, stat as stat3 } from "fs/promises";
4509
4560
  import { homedir as homedir3, tmpdir as tmpdir2 } from "os";
4510
- import { basename as basename3, dirname as dirname13, resolve as resolve3 } from "path";
4561
+ import { basename as basename3, dirname as dirname14, resolve as resolve3 } from "path";
4511
4562
  async function resolveWorkingDirectory(requestedCwd) {
4512
4563
  const trimmed = requestedCwd.trim();
4513
4564
  if (!trimmed) {
@@ -4537,17 +4588,17 @@ function reject(reason, requestedCwd, userVisible) {
4537
4588
  return { ok: false, reason, requestedCwd, userVisible };
4538
4589
  }
4539
4590
  function classifyHighRiskWorkingDirectory(real, requestedCwd, tempRealpath, homeRealpath) {
4540
- if (real === dirname13(real)) {
4591
+ if (real === dirname14(real)) {
4541
4592
  return reject("filesystem-root", requestedCwd, "\u4E0D\u80FD\u628A\u6587\u4EF6\u7CFB\u7EDF\u6839\u76EE\u5F55\u8BBE\u4E3A\u5DE5\u4F5C\u76EE\u5F55\u3002");
4542
4593
  }
4543
4594
  const home = homeRealpath;
4544
4595
  if (real === home) {
4545
4596
  return reject("home-root", requestedCwd, "\u4E0D\u80FD\u628A Home \u6839\u76EE\u5F55\u8BBE\u4E3A\u5DE5\u4F5C\u76EE\u5F55\uFF0C\u8BF7\u9009\u62E9\u66F4\u5177\u4F53\u7684\u5B50\u76EE\u5F55\u3002");
4546
4597
  }
4547
- if (real === dirname13(home)) {
4598
+ if (real === dirname14(home)) {
4548
4599
  return reject("user-root", requestedCwd, "\u4E0D\u80FD\u628A\u7528\u6237\u76EE\u5F55\u6839\u8BBE\u4E3A\u5DE5\u4F5C\u76EE\u5F55\uFF0C\u8BF7\u9009\u62E9\u66F4\u5177\u4F53\u7684\u5B50\u76EE\u5F55\u3002");
4549
4600
  }
4550
- if (dirname13(real) === home && (/* @__PURE__ */ new Set(["Desktop", "Downloads"])).has(basename3(real))) {
4601
+ if (dirname14(real) === home && (/* @__PURE__ */ new Set(["Desktop", "Downloads"])).has(basename3(real))) {
4551
4602
  return reject("broad-user-folder", requestedCwd, "\u8FD9\u4E2A\u76EE\u5F55\u8303\u56F4\u8FC7\u5927\uFF0C\u8BF7\u9009\u62E9\u66F4\u5177\u4F53\u7684\u5B50\u76EE\u5F55\u3002");
4552
4603
  }
4553
4604
  const temp = resolve3(tmpdir2());
@@ -4568,7 +4619,7 @@ function classifyHighRiskWorkingDirectory(real, requestedCwd, tempRealpath, home
4568
4619
  if (systemRoots.has(real)) {
4569
4620
  return reject("system-root", requestedCwd, "\u4E0D\u80FD\u628A\u7CFB\u7EDF\u76EE\u5F55\u8BBE\u4E3A\u5DE5\u4F5C\u76EE\u5F55\u3002");
4570
4621
  }
4571
- if (real === "/Volumes" || dirname13(real) === "/Volumes") {
4622
+ if (real === "/Volumes" || dirname14(real) === "/Volumes") {
4572
4623
  return reject("volume-root", requestedCwd, "\u4E0D\u80FD\u628A\u78C1\u76D8\u5377\u6839\u76EE\u5F55\u8BBE\u4E3A\u5DE5\u4F5C\u76EE\u5F55\uFF0C\u8BF7\u9009\u62E9\u66F4\u5177\u4F53\u7684\u5B50\u76EE\u5F55\u3002");
4573
4624
  }
4574
4625
  return void 0;
@@ -4598,7 +4649,7 @@ async function createBootstrapProfileConfig(input) {
4598
4649
  };
4599
4650
  }
4600
4651
  if (input.profileDir && profile2.codex?.inheritCodexHome === false) {
4601
- await mkdir13(join14(input.profileDir, "codex-home"), { recursive: true });
4652
+ await mkdir13(join15(input.profileDir, "codex-home"), { recursive: true });
4602
4653
  }
4603
4654
  return profile2;
4604
4655
  }
@@ -4821,7 +4872,7 @@ function cancel2() {
4821
4872
 
4822
4873
  // src/config/store.ts
4823
4874
  import { readFile as readFile11 } from "fs/promises";
4824
- import { dirname as dirname14, resolve as resolve4 } from "path";
4875
+ import { dirname as dirname15, resolve as resolve4 } from "path";
4825
4876
  async function loadConfig(path4 = paths.configFile) {
4826
4877
  try {
4827
4878
  const text2 = await readFile11(path4, "utf8");
@@ -4866,7 +4917,7 @@ async function ensureSecretsGetterWrapper(appPaths2 = paths, opts = {}) {
4866
4917
  const node = opts.nodePath ?? process.execPath;
4867
4918
  const bridgeEntry = opts.bridgeEntry ?? resolveDaemonEntryPath(process.argv[1]);
4868
4919
  const quotedBridgeEntry = platform2 === "win32" ? bridgeEntry : resolveDaemonEntryPath(bridgeEntry);
4869
- const rootDir = resolve4(appPaths2.rootDir ?? dirname14(appPaths2.secretsGetterScript));
4920
+ const rootDir = resolve4(appPaths2.rootDir ?? dirname15(appPaths2.secretsGetterScript));
4870
4921
  if (platform2 === "win32") {
4871
4922
  const dq = (s) => `"${s.replace(/"/g, '""')}"`;
4872
4923
  const content2 = `@echo off\r
@@ -5003,8 +5054,8 @@ var DEFAULT_RATE_LIMIT_RETRIES = 3;
5003
5054
  var DEFAULT_BACKOFF_MS = 200;
5004
5055
  var DEFAULT_MAX_BACKOFF_MS = 2e3;
5005
5056
  var DEFAULT_SEND_MESSAGE_API_VERSION2 = "v2";
5006
- function sendMessagePath(version2 = DEFAULT_SEND_MESSAGE_API_VERSION2) {
5007
- return `/open/im/${version2}/messages`;
5057
+ function sendMessagePath(version3 = DEFAULT_SEND_MESSAGE_API_VERSION2) {
5058
+ return `/open/im/${version3}/messages`;
5008
5059
  }
5009
5060
  var XiaojiuApiError = class extends Error {
5010
5061
  code;
@@ -5424,7 +5475,7 @@ function createRuntimeProfileConfig(input) {
5424
5475
  });
5425
5476
  }
5426
5477
  async function resolveProfileRuntime(opts) {
5427
- const rootDir = opts.config ? dirname15(opts.config) : void 0;
5478
+ const rootDir = opts.config ? dirname16(opts.config) : void 0;
5428
5479
  const requestedAgent = agentKindFromString(opts.agent);
5429
5480
  const explicitProfile = opts.profile;
5430
5481
  const activeProfile = explicitProfile ?? await readActiveProfile(rootDir);
@@ -5824,7 +5875,7 @@ function assertBootstrapAppMatchesExistingConfig(opts, profile2, cfg) {
5824
5875
  );
5825
5876
  }
5826
5877
  async function materializeEnvSecretForService(opts = {}) {
5827
- const rootDir = opts.config ? dirname15(opts.config) : void 0;
5878
+ const rootDir = opts.config ? dirname16(opts.config) : void 0;
5828
5879
  const explicitProfile = opts.profile;
5829
5880
  const activeProfile = explicitProfile ?? await readActiveProfile(rootDir);
5830
5881
  let profile2 = activeProfile ?? "claude";
@@ -6237,7 +6288,7 @@ async function runProfileExport(name, opts = {}) {
6237
6288
  console.log(body.trimEnd());
6238
6289
  return;
6239
6290
  }
6240
- if (existsSync8(opts.output) && !opts.force) {
6291
+ if (existsSync9(opts.output) && !opts.force) {
6241
6292
  throw new Error("output already exists; use --force");
6242
6293
  }
6243
6294
  await writeFileAtomic(opts.output, body, { mode: 384 });
@@ -6248,10 +6299,10 @@ function cloneJson(value) {
6248
6299
  }
6249
6300
 
6250
6301
  // src/selfupdate/runtime.ts
6251
- import { existsSync as existsSync9, readFileSync as readFileSync3, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "fs";
6302
+ import { existsSync as existsSync10, readFileSync as readFileSync5, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "fs";
6252
6303
  import { copyFile, mkdir as mkdir15 } from "fs/promises";
6253
- import { dirname as dirname16 } from "path";
6254
- import { fileURLToPath as fileURLToPath3 } from "url";
6304
+ import { dirname as dirname17 } from "path";
6305
+ import { fileURLToPath as fileURLToPath4 } from "url";
6255
6306
 
6256
6307
  // src/selfupdate/protocol.ts
6257
6308
  var SWITCH_EXIT_CODE = 75;
@@ -6267,7 +6318,7 @@ function launcherPidFromEnv(env = process.env) {
6267
6318
  const file = env[ENV_BOOT_FILE];
6268
6319
  if (!file) return void 0;
6269
6320
  try {
6270
- const parsed = JSON.parse(readFileSync3(file, "utf8"));
6321
+ const parsed = JSON.parse(readFileSync5(file, "utf8"));
6271
6322
  if (typeof parsed !== "object" || parsed === null || !("pid" in parsed)) return void 0;
6272
6323
  const pid = parsed.pid;
6273
6324
  return typeof pid === "number" && pid !== process.pid ? pid : void 0;
@@ -6279,7 +6330,7 @@ function markBootReady(env = process.env) {
6279
6330
  const file = env[ENV_BOOT_FILE];
6280
6331
  if (!file) return;
6281
6332
  try {
6282
- const parsed = JSON.parse(readFileSync3(file, "utf8"));
6333
+ const parsed = JSON.parse(readFileSync5(file, "utf8"));
6283
6334
  if (typeof parsed !== "object" || parsed === null) return;
6284
6335
  const tmp = `${file}.ready-${process.pid}`;
6285
6336
  writeFileSync2(tmp, `${JSON.stringify({ ...parsed, ready: true }, null, 2)}
@@ -6289,13 +6340,13 @@ function markBootReady(env = process.env) {
6289
6340
  }
6290
6341
  }
6291
6342
  async function ensureLauncherFresh(layout, bundledLauncherFile = defaultBundledLauncher()) {
6292
- if (!existsSync9(bundledLauncherFile)) return false;
6293
- const bundled = readFileSync3(bundledLauncherFile);
6343
+ if (!existsSync10(bundledLauncherFile)) return false;
6344
+ const bundled = readFileSync5(bundledLauncherFile);
6294
6345
  try {
6295
- if (readFileSync3(layout.launcherFile).equals(bundled)) return true;
6346
+ if (readFileSync5(layout.launcherFile).equals(bundled)) return true;
6296
6347
  } catch {
6297
6348
  }
6298
- await mkdir15(dirname16(layout.launcherFile), { recursive: true });
6349
+ await mkdir15(dirname17(layout.launcherFile), { recursive: true });
6299
6350
  await copyFile(bundledLauncherFile, layout.launcherFile);
6300
6351
  return true;
6301
6352
  }
@@ -6314,7 +6365,7 @@ async function prepareLauncherInstall(layout, runningVersion, deps = {}) {
6314
6365
  return pointer;
6315
6366
  }
6316
6367
  function defaultBundledLauncher() {
6317
- return fileURLToPath3(new URL("./launcher.js", import.meta.url));
6368
+ return fileURLToPath4(new URL("./launcher.js", import.meta.url));
6318
6369
  }
6319
6370
 
6320
6371
  // src/cli/commands/listen-client.ts
@@ -6838,13 +6889,13 @@ function agentDisplay(agentKind) {
6838
6889
  import dns from "dns";
6839
6890
  import os from "os";
6840
6891
  import { readdir as readdir14 } from "fs/promises";
6841
- import { join as join31 } from "path";
6892
+ import { join as join32 } from "path";
6842
6893
  import { createInterface as createInterface11 } from "readline";
6843
6894
 
6844
6895
  // src/agent/claude/adapter.ts
6845
6896
  import { mkdtempSync, rmSync, writeFileSync as writeFileSync3 } from "fs";
6846
6897
  import { tmpdir as tmpdir3 } from "os";
6847
- import { join as join17 } from "path";
6898
+ import { join as join18 } from "path";
6848
6899
  import { createInterface as createInterface4 } from "readline";
6849
6900
 
6850
6901
  // src/agent/system-prompt.ts
@@ -6938,7 +6989,7 @@ var CLAUDE_DEFAULT_PERMISSION_MODE = "bypassPermissions";
6938
6989
  // src/agent/claude/side-query.ts
6939
6990
  import { readdir as readdir7, rm as rm14 } from "fs/promises";
6940
6991
  import { homedir as homedir5 } from "os";
6941
- import { join as join16 } from "path";
6992
+ import { join as join17 } from "path";
6942
6993
 
6943
6994
  // src/agent/btw-prompt.ts
6944
6995
  var BTW_DEFAULT_QUESTION = "\u8BF7\u7528\u51E0\u884C\u8BF4\u660E\u5F53\u524D\u8FDB\u5C55\u3001\u6B63\u5728\u505A\u4EC0\u4E48\u3001\u4E0B\u4E00\u6B65\uFF1B\u4E0D\u8981\u52A8\u624B\u3002";
@@ -7100,9 +7151,9 @@ function isBtwSession(agentKind, sessionId) {
7100
7151
  // src/agent/claude/session-paths.ts
7101
7152
  import { readdir as readdir6, stat as stat4 } from "fs/promises";
7102
7153
  import { homedir as homedir4 } from "os";
7103
- import { join as join15 } from "path";
7104
- function claudeProjectDir(cwd, projectsRoot = join15(homedir4(), ".claude", "projects")) {
7105
- return join15(projectsRoot, cwd.replace(/[^A-Za-z0-9]/g, "-"));
7154
+ import { join as join16 } from "path";
7155
+ function claudeProjectDir(cwd, projectsRoot = join16(homedir4(), ".claude", "projects")) {
7156
+ return join16(projectsRoot, cwd.replace(/[^A-Za-z0-9]/g, "-"));
7106
7157
  }
7107
7158
  async function latestClaudeSessionId(cwd, projectsRoot) {
7108
7159
  const dir = claudeProjectDir(cwd, projectsRoot);
@@ -7115,7 +7166,7 @@ async function latestClaudeSessionId(cwd, projectsRoot) {
7115
7166
  let newest;
7116
7167
  for (const file of files) {
7117
7168
  try {
7118
- const info = await stat4(join15(dir, file));
7169
+ const info = await stat4(join16(dir, file));
7119
7170
  if (!newest || info.mtimeMs > newest.mtime) {
7120
7171
  newest = { id: file.replace(/\.jsonl$/, ""), mtime: info.mtimeMs };
7121
7172
  }
@@ -7442,7 +7493,7 @@ function buildClaudeSideQueryArgs(input) {
7442
7493
  ""
7443
7494
  ];
7444
7495
  }
7445
- async function deleteClaudeSessionFile(sessionId, projectsRoot = join16(homedir5(), ".claude", "projects")) {
7496
+ async function deleteClaudeSessionFile(sessionId, projectsRoot = join17(homedir5(), ".claude", "projects")) {
7446
7497
  let dirs;
7447
7498
  try {
7448
7499
  dirs = await readdir7(projectsRoot, { withFileTypes: true });
@@ -7451,7 +7502,7 @@ async function deleteClaudeSessionFile(sessionId, projectsRoot = join16(homedir5
7451
7502
  }
7452
7503
  for (const dir of dirs) {
7453
7504
  if (!dir.isDirectory()) continue;
7454
- const base = join16(projectsRoot, dir.name, sessionId);
7505
+ const base = join17(projectsRoot, dir.name, sessionId);
7455
7506
  await rm14(`${base}.jsonl`, { force: true, maxRetries: 5, retryDelay: 25 }).catch(() => {
7456
7507
  });
7457
7508
  await rm14(base, { recursive: true, force: true, maxRetries: 5, retryDelay: 25 }).catch(() => {
@@ -7691,8 +7742,8 @@ async function* createEventStream(child, stderrChunks, getError) {
7691
7742
  }
7692
7743
  }
7693
7744
  function writeSystemPromptFile(content) {
7694
- const dir = mkdtempSync(join17(tmpdir3(), "xiaojiu-claude-"));
7695
- const path4 = join17(dir, "append-system-prompt.md");
7745
+ const dir = mkdtempSync(join18(tmpdir3(), "xiaojiu-claude-"));
7746
+ const path4 = join18(dir, "append-system-prompt.md");
7696
7747
  writeFileSync3(path4, content, "utf8");
7697
7748
  return {
7698
7749
  path: path4,
@@ -7710,7 +7761,7 @@ function isWindowsCommandNotFoundLine(line) {
7710
7761
 
7711
7762
  // src/agent/codex/adapter.ts
7712
7763
  import { createInterface as createInterface5 } from "readline";
7713
- import { join as join19 } from "path";
7764
+ import { join as join20 } from "path";
7714
7765
 
7715
7766
  // src/runtime/errors.ts
7716
7767
  var RunRejected = class extends Error {
@@ -7780,7 +7831,7 @@ function buildCodexArgs(input) {
7780
7831
  // src/agent/codex/side-query.ts
7781
7832
  import { readdir as readdir8, rm as rm15 } from "fs/promises";
7782
7833
  import { homedir as homedir6 } from "os";
7783
- import { join as join18 } from "path";
7834
+ import { join as join19 } from "path";
7784
7835
 
7785
7836
  // src/agent/codex/jsonl.ts
7786
7837
  var CodexJsonlTranslator = class {
@@ -8042,8 +8093,8 @@ function buildCodexSideQueryArgs(threadId) {
8042
8093
  "-"
8043
8094
  ];
8044
8095
  }
8045
- async function deleteCodexThreadRollout(threadId, codexHome = process.env.CODEX_HOME || join18(homedir6(), ".codex")) {
8046
- const root = join18(codexHome, "sessions");
8096
+ async function deleteCodexThreadRollout(threadId, codexHome = process.env.CODEX_HOME || join19(homedir6(), ".codex")) {
8097
+ const root = join19(codexHome, "sessions");
8047
8098
  const queue = [{ dir: root, depth: 0 }];
8048
8099
  while (queue.length > 0) {
8049
8100
  const current = queue.pop();
@@ -8055,7 +8106,7 @@ async function deleteCodexThreadRollout(threadId, codexHome = process.env.CODEX_
8055
8106
  continue;
8056
8107
  }
8057
8108
  for (const entry of entries) {
8058
- const path4 = join18(current.dir, entry.name);
8109
+ const path4 = join19(current.dir, entry.name);
8059
8110
  if (entry.isDirectory()) {
8060
8111
  if (current.depth < 4) queue.push({ dir: path4, depth: current.depth + 1 });
8061
8112
  continue;
@@ -8114,7 +8165,7 @@ var CodexAdapter = class {
8114
8165
  this.botIdentity = identity;
8115
8166
  }
8116
8167
  async sideQuery(opts) {
8117
- const codexHome = this.codexHome ?? (this.inheritCodexHome ? void 0 : join19(this.profileStateDir, "codex-home"));
8168
+ const codexHome = this.codexHome ?? (this.inheritCodexHome ? void 0 : join20(this.profileStateDir, "codex-home"));
8118
8169
  return runCodexSideQuery({
8119
8170
  binary: this.binary,
8120
8171
  cwd: opts.cwd,
@@ -8165,7 +8216,7 @@ var CodexAdapter = class {
8165
8216
  if (this.codexHome) {
8166
8217
  envOverrides.CODEX_HOME = this.codexHome;
8167
8218
  } else if (!this.inheritCodexHome) {
8168
- envOverrides.CODEX_HOME = join19(this.profileStateDir, "codex-home");
8219
+ envOverrides.CODEX_HOME = join20(this.profileStateDir, "codex-home");
8169
8220
  }
8170
8221
  const child = spawnProcess(this.binary, args, {
8171
8222
  cwd: opts.cwd,
@@ -8340,10 +8391,10 @@ function isWindowsCommandNotFoundLine2(line) {
8340
8391
  }
8341
8392
 
8342
8393
  // src/bot/channel.ts
8343
- import { dirname as dirname19, join as join26 } from "path";
8394
+ import { dirname as dirname20, join as join27 } from "path";
8344
8395
 
8345
8396
  // src/channel/channel.ts
8346
- import { join as join20 } from "path";
8397
+ import { join as join21 } from "path";
8347
8398
 
8348
8399
  // src/channel/xiaojiu/dedupe-store.ts
8349
8400
  import { readFile as readFile13 } from "fs/promises";
@@ -9052,7 +9103,7 @@ var XiaojiuChannel = class {
9052
9103
  sendMessageApiVersion: options.sendMessageApiVersion
9053
9104
  });
9054
9105
  this.dedupe = new XiaojiuDedupeStore(
9055
- options.dedupeFile ?? join20(process.cwd(), ".xiaojiu-webhook-events.json"),
9106
+ options.dedupeFile ?? join21(process.cwd(), ".xiaojiu-webhook-events.json"),
9056
9107
  options.dedupeTtlMs ? { ttlMs: options.dedupeTtlMs } : {}
9057
9108
  );
9058
9109
  this.throttleMs = Math.max(250, options.streamThrottleMs ?? 250);
@@ -9600,7 +9651,7 @@ function safeJsonStringify(value) {
9600
9651
 
9601
9652
  // src/commands/index.ts
9602
9653
  import { randomUUID } from "crypto";
9603
- import { dirname as dirname18 } from "path";
9654
+ import { dirname as dirname19 } from "path";
9604
9655
 
9605
9656
  // src/commands/mention-text.ts
9606
9657
  function stripMatchedMentions(text2, mentions) {
@@ -10360,7 +10411,7 @@ function deny(reason) {
10360
10411
  }
10361
10412
 
10362
10413
  // src/config/config-ops.ts
10363
- import { dirname as dirname17 } from "path";
10414
+ import { dirname as dirname18 } from "path";
10364
10415
  async function saveAccessConfig(state, mutate) {
10365
10416
  try {
10366
10417
  return await withConfigFileLock(state.configPath, async () => {
@@ -10905,7 +10956,7 @@ function finalizeIfRunning(state) {
10905
10956
  // src/session/history.ts
10906
10957
  import { createReadStream } from "fs";
10907
10958
  import { readdir as readdir9, stat as stat5 } from "fs/promises";
10908
- import { join as join21 } from "path";
10959
+ import { join as join22 } from "path";
10909
10960
  import { createInterface as createInterface6 } from "readline";
10910
10961
 
10911
10962
  // src/session/preview.ts
@@ -10954,7 +11005,7 @@ async function listRecentSessions(cwd, limit = 5) {
10954
11005
  );
10955
11006
  const withStats = await Promise.all(
10956
11007
  jsonls.map(async (f) => {
10957
- const path4 = join21(dir, f);
11008
+ const path4 = join22(dir, f);
10958
11009
  try {
10959
11010
  const st = await stat5(path4);
10960
11011
  return { file: f, path: path4, mtime: st.mtimeMs };
@@ -11025,7 +11076,7 @@ function formatRelTime(mtime) {
11025
11076
 
11026
11077
  // src/session/codex-history.ts
11027
11078
  import { createInterface as createInterface7 } from "readline";
11028
- import { join as join22 } from "path";
11079
+ import { join as join23 } from "path";
11029
11080
  var CodexHistoryError = class extends Error {
11030
11081
  code;
11031
11082
  constructor(code, message, options) {
@@ -11140,7 +11191,7 @@ function spawnCodexAppServer(options) {
11140
11191
  if (options.codexHome) {
11141
11192
  envOverrides.CODEX_HOME = options.codexHome;
11142
11193
  } else if (options.inheritCodexHome === false) {
11143
- envOverrides.CODEX_HOME = join22(options.profileStateDir, "codex-home");
11194
+ envOverrides.CODEX_HOME = join23(options.profileStateDir, "codex-home");
11144
11195
  }
11145
11196
  return spawnProcess(options.binary, ["app-server", "--listen", "stdio://"], {
11146
11197
  env: mergeProcessEnv(process.env, envOverrides),
@@ -13069,7 +13120,7 @@ async function submitConfig(ctx) {
13069
13120
  }
13070
13121
  function commandProfilePaths(ctx) {
13071
13122
  return resolveAppPaths({
13072
- rootDir: dirname18(ctx.controls.configPath),
13123
+ rootDir: dirname19(ctx.controls.configPath),
13073
13124
  profile: ctx.controls.profile
13074
13125
  });
13075
13126
  }
@@ -13513,7 +13564,7 @@ function footerLine(status) {
13513
13564
  import { createHash as createHash4 } from "crypto";
13514
13565
  import { createReadStream as createReadStream2 } from "fs";
13515
13566
  import { mkdir as mkdir16, open as open3, readdir as readdir10, rename as rename3, rm as rm16, stat as stat6, writeFile as writeFile9 } from "fs/promises";
13516
- import { join as join23 } from "path";
13567
+ import { join as join24 } from "path";
13517
13568
 
13518
13569
  // src/media/attachment.ts
13519
13570
  var DEFAULT_POLICY = {
@@ -13649,7 +13700,7 @@ var MediaCache = class {
13649
13700
  return null;
13650
13701
  }
13651
13702
  const kind = r.type;
13652
- const tmpPath = join23(
13703
+ const tmpPath = join24(
13653
13704
  this.rootDir,
13654
13705
  `.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`
13655
13706
  );
@@ -13676,7 +13727,7 @@ var MediaCache = class {
13676
13727
  const hash = await hashFile(tmpPath);
13677
13728
  const mime = await sniffImageMime(tmpPath) ?? contentType ?? defaultMime(kind);
13678
13729
  const ext = safeExtensionForMime(mime);
13679
- const absPath = join23(this.rootDir, `${hash}.${ext}`);
13730
+ const absPath = join24(this.rootDir, `${hash}.${ext}`);
13680
13731
  try {
13681
13732
  await stat6(absPath);
13682
13733
  await rm16(tmpPath, { force: true });
@@ -13737,7 +13788,7 @@ async function listFiles(root) {
13737
13788
  const out = [];
13738
13789
  const entries = await readdir10(root, { withFileTypes: true }).catch(() => []);
13739
13790
  for (const entry of entries) {
13740
- const full = join23(root, entry.name);
13791
+ const full = join24(root, entry.name);
13741
13792
  if (entry.isDirectory()) {
13742
13793
  out.push(...await listFiles(full));
13743
13794
  } else if (entry.isFile()) {
@@ -14281,7 +14332,7 @@ function isTerminalEvent(event) {
14281
14332
  // src/session/context-store.ts
14282
14333
  import { createHash as createHash5 } from "crypto";
14283
14334
  import { readFile as readFile15 } from "fs/promises";
14284
- import { join as join24 } from "path";
14335
+ import { join as join25 } from "path";
14285
14336
  var MAX_MESSAGES = 25;
14286
14337
  var MAX_MESSAGE_CHARS = 8e3;
14287
14338
  var MAX_HISTORY_CHARS = 64e3;
@@ -14346,7 +14397,7 @@ var ConversationContextStore = class {
14346
14397
  identity.cwdRealpath,
14347
14398
  identity.policyFingerprint
14348
14399
  ])).digest("hex");
14349
- return join24(this.profileDir, "context", `${hash}.json`);
14400
+ return join25(this.profileDir, "context", `${hash}.json`);
14350
14401
  }
14351
14402
  async load(identity) {
14352
14403
  const path4 = this.path(identity);
@@ -14382,7 +14433,7 @@ var ConversationContextStore = class {
14382
14433
  // src/memory/store.ts
14383
14434
  import { createHash as createHash6, randomUUID as randomUUID3 } from "crypto";
14384
14435
  import { mkdir as mkdir17, readdir as readdir11, realpath as realpath5, stat as stat7, writeFile as writeFile10 } from "fs/promises";
14385
- import { join as join25 } from "path";
14436
+ import { join as join26 } from "path";
14386
14437
  import * as lockfile5 from "proper-lockfile";
14387
14438
  var initializations = /* @__PURE__ */ new Map();
14388
14439
  var README_NAME = "README.md";
@@ -14412,7 +14463,7 @@ var WorkspaceMemoryStore = class {
14412
14463
  maxNotes;
14413
14464
  maxBytes;
14414
14465
  constructor(profileDir, limits = {}) {
14415
- this.root = join25(profileDir, "memory");
14466
+ this.root = join26(profileDir, "memory");
14416
14467
  this.maxNotes = limits.maxNotes ?? 200;
14417
14468
  this.maxBytes = limits.maxBytes ?? 1024 * 1024;
14418
14469
  }
@@ -14423,7 +14474,7 @@ var WorkspaceMemoryStore = class {
14423
14474
  for (const entry of await readdir11(directory, { withFileTypes: true })) {
14424
14475
  if (entry.name === README_NAME || !entry.isFile() || entry.name.startsWith(".README.md.tmp-")) continue;
14425
14476
  try {
14426
- const info = await stat7(join25(directory, entry.name));
14477
+ const info = await stat7(join26(directory, entry.name));
14427
14478
  noteCount += 1;
14428
14479
  totalBytes += info.size;
14429
14480
  } catch (err) {
@@ -14444,7 +14495,7 @@ var WorkspaceMemoryStore = class {
14444
14495
  /** Creates a new note; capacity reporting is advisory, not a concurrent hard quota. */
14445
14496
  async appendNote(cwdRealpath, content) {
14446
14497
  const directory = await this.ensureDirectory(cwdRealpath);
14447
- const path4 = join25(directory, `${randomUUID3()}.md`);
14498
+ const path4 = join26(directory, `${randomUUID3()}.md`);
14448
14499
  await writeFile10(path4, content, { encoding: "utf8", flag: "wx", mode: 384 });
14449
14500
  return path4;
14450
14501
  }
@@ -14452,9 +14503,9 @@ var WorkspaceMemoryStore = class {
14452
14503
  const resolved = await realpath5(cwdRealpath);
14453
14504
  const canonical = process.platform === "win32" ? resolved.toLowerCase() : resolved;
14454
14505
  const hash = createHash6("sha256").update(canonical).digest("hex");
14455
- const directory = join25(this.root, hash);
14506
+ const directory = join26(this.root, hash);
14456
14507
  await mkdir17(directory, { recursive: true, mode: 448 });
14457
- const readmePath = join25(directory, README_NAME);
14508
+ const readmePath = join26(directory, README_NAME);
14458
14509
  try {
14459
14510
  await stat7(readmePath);
14460
14511
  } catch (err) {
@@ -15609,11 +15660,11 @@ async function startChannel(deps) {
15609
15660
  const pool = new ProcessPool(() => getMaxConcurrentRuns(controls.cfg));
15610
15661
  const progress = new RunProgressRegistry();
15611
15662
  const executor = new RunExecutor({ agent, pool, activeRuns, progress });
15612
- const profileDir = deps.appPaths?.mediaDir ? dirname19(deps.appPaths.mediaDir) : void 0;
15663
+ const profileDir = deps.appPaths?.mediaDir ? dirname20(deps.appPaths.mediaDir) : void 0;
15613
15664
  const contextStore = profileDir ? new ConversationContextStore(profileDir) : void 0;
15614
15665
  const memory = profileDir ? new WorkspaceMemoryStore(profileDir) : void 0;
15615
15666
  const appSecret = await resolveAppSecret(cfg, deps.appPaths);
15616
- const callbackNonceStore = deps.appPaths?.mediaDir ? new CallbackNonceStore(join26(dirname19(deps.appPaths.mediaDir), "callback-nonces.json")) : void 0;
15667
+ const callbackNonceStore = deps.appPaths?.mediaDir ? new CallbackNonceStore(join27(dirname20(deps.appPaths.mediaDir), "callback-nonces.json")) : void 0;
15617
15668
  await callbackNonceStore?.load();
15618
15669
  const callbackAuth = callbackNonceStore ? new CallbackAuth({
15619
15670
  keys: [{ version: 1, secret: appSecret }],
@@ -15642,7 +15693,7 @@ async function startChannel(deps) {
15642
15693
  webhookServer,
15643
15694
  webhookBodyLimitBytes: cfg.webhook.bodyLimitBytes,
15644
15695
  dedupeTtlMs: cfg.webhook.dedupeTtlMs,
15645
- dedupeFile: deps.appPaths?.mediaDir ? join26(dirname19(deps.appPaths.mediaDir), "webhook-events.json") : void 0,
15696
+ dedupeFile: deps.appPaths?.mediaDir ? join27(dirname20(deps.appPaths.mediaDir), "webhook-events.json") : void 0,
15646
15697
  streamThrottleMs: 250,
15647
15698
  sendMessageApiVersion: () => getSendMessageApiVersion(controls.cfg)
15648
15699
  });
@@ -17043,9 +17094,55 @@ function startAutoUpdateScheduler(deps) {
17043
17094
  };
17044
17095
  }
17045
17096
 
17097
+ // src/selfupdate/launcher-capabilities.ts
17098
+ import { readFileSync as readFileSync6 } from "fs";
17099
+ var REQUIRED_LAUNCHER_CAPABILITIES = [];
17100
+ function inspectLauncherCapabilities(bootFile, required = REQUIRED_LAUNCHER_CAPABILITIES) {
17101
+ const boot = readBootRecord(bootFile);
17102
+ const reported = boot?.launcher !== void 0;
17103
+ const capabilities = boot?.launcher?.capabilities ?? [];
17104
+ return {
17105
+ reported,
17106
+ capabilities,
17107
+ missing: required.filter((capability) => !capabilities.includes(capability)),
17108
+ ...typeof boot?.version === "string" ? { bootVersion: boot.version } : {}
17109
+ };
17110
+ }
17111
+ function formatLauncherCapabilityWarning(diagnostics, options) {
17112
+ if (diagnostics.missing.length === 0) return void 0;
17113
+ const legacy = diagnostics.reported ? "" : "\uFF08\u65E7 launcher \u672A\u4E0A\u62A5\u80FD\u529B\uFF09";
17114
+ const fix = options.refreshed ? "\u5DF2\u5237\u65B0 launcher \u526F\u672C\uFF0C\u91CD\u542F\u540E\u53F0\u670D\u52A1\u540E\u751F\u6548\uFF1A`xiaojiu-agent-bridge restart`\u3002" : `\u65E0\u6CD5\u5237\u65B0 launcher \u526F\u672C\uFF1A\u91CD\u65B0\u5B89\u88C5\u540E\u518D\u91CD\u542F\u670D\u52A1\uFF1A${manualLauncherUpdateCommand()}`;
17115
+ return `\u26A0 launcher \u7F3A\u5C11\u80FD\u529B ${diagnostics.missing.join(", ")}${legacy}\u3002${fix}`;
17116
+ }
17117
+ function manualLauncherUpdateCommand() {
17118
+ return `npm install -g ${packageName}@latest --registry=${REGISTRY_URL}`;
17119
+ }
17120
+ function launcherCapabilitiesLine(diagnostics) {
17121
+ if (!diagnostics.reported) return "legacy (boot.json has no launcher field)";
17122
+ return diagnostics.capabilities.length > 0 ? diagnostics.capabilities.join(", ") : "(none)";
17123
+ }
17124
+ function readBootRecord(file) {
17125
+ try {
17126
+ const parsed = JSON.parse(readFileSync6(file, "utf8"));
17127
+ if (typeof parsed !== "object" || parsed === null) return void 0;
17128
+ const version3 = "version" in parsed ? parsed.version : void 0;
17129
+ const record5 = {};
17130
+ if (typeof version3 === "string") record5.version = version3;
17131
+ if ("launcher" in parsed && typeof parsed.launcher === "object" && parsed.launcher !== null) {
17132
+ const raw = "capabilities" in parsed.launcher ? parsed.launcher.capabilities : void 0;
17133
+ record5.launcher = {
17134
+ capabilities: Array.isArray(raw) ? raw.filter((item) => typeof item === "string") : []
17135
+ };
17136
+ }
17137
+ return record5;
17138
+ } catch {
17139
+ return void 0;
17140
+ }
17141
+ }
17142
+
17046
17143
  // src/cli/commands/migrate-launcher.ts
17047
17144
  import { readFile as readFile16 } from "fs/promises";
17048
- import { join as join27 } from "path";
17145
+ import { join as join28 } from "path";
17049
17146
  var RETRY_AFTER_MS = 24 * 60 * 60 * 1e3;
17050
17147
  async function maybeMigrateServiceToLauncher(opts) {
17051
17148
  const env = opts.env ?? process.env;
@@ -17053,7 +17150,7 @@ async function maybeMigrateServiceToLauncher(opts) {
17053
17150
  if (!getAutoUpdateEnabled(opts.cfg)) return { migrated: false, reason: "auto-update disabled" };
17054
17151
  if (isAutoUpdateEnvDisabled(env)) return { migrated: false, reason: "update checks disabled" };
17055
17152
  const layout = updateLayout(opts.rootDir);
17056
- const markerFile = join27(layout.updateDir, "launcher-migration.json");
17153
+ const markerFile = join28(layout.updateDir, "launcher-migration.json");
17057
17154
  const lastAttempt = await readFile16(markerFile, "utf8").then((text2) => {
17058
17155
  const parsed = JSON.parse(text2);
17059
17156
  return typeof parsed === "object" && parsed !== null && "attemptedAt" in parsed && typeof parsed.attemptedAt === "string" ? Date.parse(parsed.attemptedAt) : Number.NaN;
@@ -18050,7 +18147,7 @@ function asRecord4(body) {
18050
18147
  }
18051
18148
 
18052
18149
  // src/ui/fleet.ts
18053
- function listBots(supervisor, version2, now) {
18150
+ function listBots(supervisor, version3, now) {
18054
18151
  return supervisor.list().map((s) => ({
18055
18152
  id: s.profile,
18056
18153
  profileName: s.profile,
@@ -18058,7 +18155,7 @@ function listBots(supervisor, version2, now) {
18058
18155
  botName: s.botName,
18059
18156
  appId: s.appId,
18060
18157
  pid: s.pid,
18061
- version: version2,
18158
+ version: version3,
18062
18159
  startedAt: s.startedAt,
18063
18160
  uptimeMs: s.startedAt ? Math.max(0, now - Date.parse(s.startedAt)) : 0
18064
18161
  }));
@@ -18292,7 +18389,10 @@ async function route(req, res, deps, url) {
18292
18389
  hosted: true,
18293
18390
  version: deps.version,
18294
18391
  activeProfile: await readActiveProfile(deps.rootDir),
18295
- online: sup.list().length
18392
+ online: sup.list().length,
18393
+ // Launcher ↔ child handshake; a legacy boot record reports
18394
+ // `reported: false` instead of failing the console.
18395
+ launcher: inspectLauncherCapabilities(updateLayout(deps.rootDir ?? paths.rootDir).bootStateFile)
18296
18396
  });
18297
18397
  return;
18298
18398
  }
@@ -18547,7 +18647,7 @@ var WebhookRequestError2 = class extends Error {
18547
18647
 
18548
18648
  // src/agent/model-discovery.ts
18549
18649
  import { createInterface as createInterface8 } from "readline";
18550
- import { join as join28 } from "path";
18650
+ import { join as join29 } from "path";
18551
18651
  var DEFAULT_TIMEOUT_MS3 = 5e3;
18552
18652
  async function discoverModels(agentKind, options) {
18553
18653
  if (!options) return supportedModels(agentKind);
@@ -18720,7 +18820,7 @@ ${JSON.stringify({ method: "model/list", id: 2, params: { includeHidden: false,
18720
18820
  function spawnCodexAppServer2(options) {
18721
18821
  const envOverrides = {};
18722
18822
  if (options.codexHome) envOverrides.CODEX_HOME = options.codexHome;
18723
- else if (options.inheritCodexHome === false) envOverrides.CODEX_HOME = join28(options.profileStateDir, "codex-home");
18823
+ else if (options.inheritCodexHome === false) envOverrides.CODEX_HOME = join29(options.profileStateDir, "codex-home");
18724
18824
  return spawnProcess(options.binary, ["app-server", "--listen", "stdio://"], {
18725
18825
  env: mergeProcessEnv(process.env, envOverrides),
18726
18826
  stdio: ["pipe", "pipe", "pipe"]
@@ -19020,7 +19120,7 @@ function* translateEvent2(raw) {
19020
19120
  // src/agent/pi/side-query.ts
19021
19121
  import { mkdtemp as mkdtemp2, readdir as readdir12, readFile as readFile21, rm as rm17, stat as stat8 } from "fs/promises";
19022
19122
  import { homedir as homedir8, tmpdir as tmpdir4 } from "os";
19023
- import { join as join29 } from "path";
19123
+ import { join as join30 } from "path";
19024
19124
  function buildPiSideQueryArgs(input) {
19025
19125
  return [
19026
19126
  "-p",
@@ -19033,7 +19133,7 @@ function buildPiSideQueryArgs(input) {
19033
19133
  "--no-tools"
19034
19134
  ];
19035
19135
  }
19036
- async function findPiSessionFile(sessionId, sessionsRoot = join29(homedir8(), ".pi", "agent", "sessions")) {
19136
+ async function findPiSessionFile(sessionId, sessionsRoot = join30(homedir8(), ".pi", "agent", "sessions")) {
19037
19137
  let dirs;
19038
19138
  try {
19039
19139
  dirs = await readdir12(sessionsRoot, { withFileTypes: true });
@@ -19042,7 +19142,7 @@ async function findPiSessionFile(sessionId, sessionsRoot = join29(homedir8(), ".
19042
19142
  }
19043
19143
  for (const dir of dirs) {
19044
19144
  if (!dir.isDirectory()) continue;
19045
- const cwdDir = join29(sessionsRoot, dir.name);
19145
+ const cwdDir = join30(sessionsRoot, dir.name);
19046
19146
  let files;
19047
19147
  try {
19048
19148
  files = await readdir12(cwdDir);
@@ -19050,11 +19150,11 @@ async function findPiSessionFile(sessionId, sessionsRoot = join29(homedir8(), ".
19050
19150
  continue;
19051
19151
  }
19052
19152
  const hit = files.find((file) => file.endsWith(".jsonl") && file.includes(sessionId));
19053
- if (hit) return join29(cwdDir, hit);
19153
+ if (hit) return join30(cwdDir, hit);
19054
19154
  }
19055
19155
  return void 0;
19056
19156
  }
19057
- async function findLatestPiSessionFile(cwd, sessionsRoot = join29(homedir8(), ".pi", "agent", "sessions")) {
19157
+ async function findLatestPiSessionFile(cwd, sessionsRoot = join30(homedir8(), ".pi", "agent", "sessions")) {
19058
19158
  const candidates = [];
19059
19159
  let dirs;
19060
19160
  try {
@@ -19064,7 +19164,7 @@ async function findLatestPiSessionFile(cwd, sessionsRoot = join29(homedir8(), ".
19064
19164
  }
19065
19165
  for (const dir of dirs) {
19066
19166
  if (!dir.isDirectory()) continue;
19067
- const base = join29(sessionsRoot, dir.name);
19167
+ const base = join30(sessionsRoot, dir.name);
19068
19168
  let files;
19069
19169
  try {
19070
19170
  files = await readdir12(base);
@@ -19073,7 +19173,7 @@ async function findLatestPiSessionFile(cwd, sessionsRoot = join29(homedir8(), ".
19073
19173
  }
19074
19174
  for (const file of files) {
19075
19175
  if (!file.endsWith(".jsonl")) continue;
19076
- const path4 = join29(base, file);
19176
+ const path4 = join30(base, file);
19077
19177
  try {
19078
19178
  candidates.push({ file: path4, mtime: (await stat8(path4)).mtimeMs });
19079
19179
  } catch {
@@ -19117,7 +19217,7 @@ async function runPiSideQuery(input) {
19117
19217
  error: input.sessionId ? `\u627E\u4E0D\u5230 Pi \u4F1A\u8BDD ${input.sessionId.slice(0, 8)}\u2026` : "\u4F1A\u8BDD\u5C1A\u672A\u5EFA\u7ACB"
19118
19218
  };
19119
19219
  }
19120
- const sessionDir = await mkdtemp2(join29(tmpdir4(), "xiaojiu-pi-btw-"));
19220
+ const sessionDir = await mkdtemp2(join30(tmpdir4(), "xiaojiu-pi-btw-"));
19121
19221
  try {
19122
19222
  const result = await runJsonlSideQuery({
19123
19223
  agent: "pi",
@@ -19502,14 +19602,14 @@ function* translateEvent4(raw) {
19502
19602
  // src/agent/omp/side-query.ts
19503
19603
  import { readFile as readFile22, readdir as readdir13, stat as stat9 } from "fs/promises";
19504
19604
  import { homedir as homedir9 } from "os";
19505
- import { join as join30 } from "path";
19605
+ import { join as join31 } from "path";
19506
19606
  import { createInterface as createInterface10 } from "readline";
19507
19607
  var ANSWER_MAX2 = 8e3;
19508
19608
  var READY_TIMEOUT_MS2 = 2e4;
19509
19609
  function buildOmpRpcArgs(input) {
19510
19610
  return ["--mode", "rpc", "--resume=" + input.sessionId, "--cwd", input.cwd, "--no-ui"];
19511
19611
  }
19512
- async function findLatestOmpSessionId(cwd, sessionsRoot = join30(homedir9(), ".omp", "agent", "sessions")) {
19612
+ async function findLatestOmpSessionId(cwd, sessionsRoot = join31(homedir9(), ".omp", "agent", "sessions")) {
19513
19613
  let dirs;
19514
19614
  try {
19515
19615
  dirs = await readdir13(sessionsRoot, { withFileTypes: true });
@@ -19519,7 +19619,7 @@ async function findLatestOmpSessionId(cwd, sessionsRoot = join30(homedir9(), ".o
19519
19619
  const candidates = [];
19520
19620
  for (const dir of dirs) {
19521
19621
  if (!dir.isDirectory()) continue;
19522
- const base = join30(sessionsRoot, dir.name);
19622
+ const base = join31(sessionsRoot, dir.name);
19523
19623
  let files;
19524
19624
  try {
19525
19625
  files = await readdir13(base);
@@ -19528,7 +19628,7 @@ async function findLatestOmpSessionId(cwd, sessionsRoot = join30(homedir9(), ".o
19528
19628
  }
19529
19629
  for (const file of files) {
19530
19630
  if (!file.endsWith(".jsonl")) continue;
19531
- const path4 = join30(base, file);
19631
+ const path4 = join31(base, file);
19532
19632
  try {
19533
19633
  candidates.push({ file: path4, mtime: (await stat9(path4)).mtimeMs });
19534
19634
  } catch {
@@ -20277,6 +20377,7 @@ async function runStart(opts) {
20277
20377
  console.log(`${stdoutTsPrefix()}\u2713 profile\u300C${appPaths2.profile}\u300D\u5DF2\u4E0A\u7EBF${mode}`);
20278
20378
  console.log(` \u8FDB\u7A0B: ${process.pid}${uid ? ` uid: ${uid}` : ""} webhook: ${webhook}`);
20279
20379
  markBootReady();
20380
+ if (isUnderLauncher()) void refreshLauncherOnBoot(updateLayout(appPaths2.rootDir));
20280
20381
  await parkWithShutdown(supervisor, appPaths2, uiServer, listenLock, port, (requestExit) => {
20281
20382
  if (!isUnderLauncher() || !getAutoUpdateEnabled(cfg) || isAutoUpdateEnvDisabled()) return;
20282
20383
  startAutoUpdateScheduler({
@@ -20288,17 +20389,34 @@ async function runStart(opts) {
20288
20389
  log.info("self-update", "scheduler-started", { profile: appPaths2.profile });
20289
20390
  });
20290
20391
  }
20392
+ async function refreshLauncherOnBoot(layout) {
20393
+ let refreshed = false;
20394
+ try {
20395
+ refreshed = await ensureLauncherFresh(layout);
20396
+ } catch (err) {
20397
+ log.warn("self-update", "launcher-refresh-failed", { err: err instanceof Error ? err.message : String(err) });
20398
+ }
20399
+ const diagnostics = inspectLauncherCapabilities(layout.bootStateFile);
20400
+ if (diagnostics.missing.length === 0) return;
20401
+ log.warn("self-update", "launcher-capabilities-missing", {
20402
+ missing: diagnostics.missing,
20403
+ reported: diagnostics.reported,
20404
+ refreshed
20405
+ });
20406
+ const warning = formatLauncherCapabilityWarning(diagnostics, { refreshed });
20407
+ if (warning) console.warn(`${stdoutTsPrefix()}${warning}`);
20408
+ }
20291
20409
  async function collectProfileLogDirs(rootDir) {
20292
20410
  const dirs = [];
20293
20411
  let profiles;
20294
20412
  try {
20295
- profiles = await readdir14(join31(rootDir, "profiles"));
20413
+ profiles = await readdir14(join32(rootDir, "profiles"));
20296
20414
  } catch {
20297
20415
  return dirs;
20298
20416
  }
20299
20417
  for (const profile2 of profiles) {
20300
- dirs.push(join31(rootDir, "profiles", profile2, "logs"));
20301
- dirs.push(join31(rootDir, "profiles", profile2, "logs", "daemon"));
20418
+ dirs.push(join32(rootDir, "profiles", profile2, "logs"));
20419
+ dirs.push(join32(rootDir, "profiles", profile2, "logs", "daemon"));
20302
20420
  }
20303
20421
  return dirs;
20304
20422
  }
@@ -20452,15 +20570,62 @@ function openBrowser(url) {
20452
20570
  }
20453
20571
  }
20454
20572
 
20573
+ // src/cli/commands/doctor.ts
20574
+ import { existsSync as existsSync11 } from "fs";
20575
+ import { join as join33 } from "path";
20576
+ async function runDoctor(options = {}) {
20577
+ const log2 = options.log ?? ((message) => process.stdout.write(`${message}
20578
+ `));
20579
+ const rootDir = options.rootDir ?? paths.rootDir;
20580
+ const layout = updateLayout(rootDir);
20581
+ const running = resolveInstall({ rootDir, ...options.pkgDir ? { pkgDir: options.pkgDir } : {} });
20582
+ const diagnostics = inspectLauncherCapabilities(
20583
+ options.bootFile ?? layout.bootStateFile,
20584
+ options.required
20585
+ );
20586
+ const pointer = await readCurrent(layout);
20587
+ log2(`bootstrap (npm global): ${version}`);
20588
+ log2(`running (pointer): ${running.version}`);
20589
+ log2(`launcher capabilities: ${launcherCapabilitiesLine(diagnostics)}`);
20590
+ log2(`missing for running: ${diagnostics.missing.length > 0 ? diagnostics.missing.join(", ") : "(none)"}`);
20591
+ if (!pointer) {
20592
+ log2("pointer: absent (using the invoked package)");
20593
+ } else if (running.source === "checkout") {
20594
+ log2(`pointer: ignored (git checkout runs its own tree; pointer=${pointer.version})`);
20595
+ } else if (running.source === "pointer") {
20596
+ log2(`pointer: ok (${pointer.dir})`);
20597
+ } else {
20598
+ log2(`pointer: broken \u2192 falls back to bootstrap (${pointer.version} at ${pointer.dir})`);
20599
+ }
20600
+ const target = pointer ? packageDirOf(pointer.dir) : void 0;
20601
+ if (target && !existsSync11(join33(target, "package.json")) && running.source !== "checkout") {
20602
+ log2(" \u6307\u9488\u76EE\u6807\u7F3A\u5C11 package.json\uFF0Clauncher \u4F1A\u56DE\u9000\u5230\u81EA\u8EAB\u5B89\u88C5");
20603
+ }
20604
+ if (!diagnostics.reported) {
20605
+ log2(" launcher \u526F\u672C\u5C1A\u672A\u4E0A\u62A5\u80FD\u529B\uFF1B`xiaojiu-agent-bridge restart` \u540E\u5237\u65B0");
20606
+ }
20607
+ if (diagnostics.missing.length > 0) {
20608
+ const warning = formatLauncherCapabilityWarning(diagnostics, { refreshed: true });
20609
+ if (warning) log2(` ${warning}`);
20610
+ log2(` \u82E5\u91CD\u542F\u540E\u4ECD\u7F3A\u5931\uFF1A${manualLauncherUpdateCommand()}`);
20611
+ }
20612
+ if (running.source === "bootstrap" && pointer && pointer.version !== running.version) {
20613
+ log2(` \u6307\u9488 ${pointer.version} \u4E0D\u53EF\u542F\u52A8\uFF0C\u5F53\u524D\u5B9E\u9645\u8FD0\u884C bootstrap ${running.version}\uFF08${packageName}\uFF09`);
20614
+ }
20615
+ }
20616
+
20455
20617
  // src/cli/index.ts
20456
20618
  var program = new Command();
20457
- program.name("xiaojiu-agent-bridge").description(`Bridge Xiaojiu IM with local CLI coding agents (${packageName})`).version(version, "-v, --version");
20619
+ program.name("xiaojiu-agent-bridge").description(`Bridge Xiaojiu IM with local CLI coding agents (${packageName})`).version(resolveInstall().version, "-v, --version");
20458
20620
  program.command("update").description("Check npm for a newer version, show highlights, and install it").option("--check", "only print the available update; do not run npm install").action(async (opts) => {
20459
20621
  await runUpdateCheck({ checkOnly: opts.check === true });
20460
20622
  });
20461
20623
  program.command("changelog [version]").description("Show release notes for the installed version").action(async (requestedVersion) => {
20462
20624
  await runChangelog(requestedVersion);
20463
20625
  });
20626
+ program.command("doctor").description("Show bootstrap, launcher, and running version state (read-only)").action(async () => {
20627
+ await runDoctor();
20628
+ });
20464
20629
  program.command("run").description("Run the bridge in the foreground").option("-c, --config <path>", "path to config file").option("--profile <name>", "profile name to run").option("--web-ui", "open the local web console on this bot listen process").option("--agent <kind>", "agent kind for a new profile (claude, codex, pi, opencode, or omp)").option("--workspace <path>", "initial working directory for first-run profile bootstrap").option("--app-id <id>", "Xiaojiu App ID").option("--app-secret <secret>", "Xiaojiu App Secret; prefer interactive input on shared machines").option("--owner <staffNo>", "Bot Owner staff number (GZ + 4 digits, e.g. GZ1133)").option("-H, --host <host>", "Webhook listen host (default: 0.0.0.0)").option("-p, --port <port>", "Webhook listen port (default: 9699)", parsePort).option("--path-secret <secret>", "Webhook path secret; a random value is generated when omitted").option("--public-path <path>", "shared callback path for all profiles (routes by appId)", normalizeWebhookPath).action(async (opts) => {
20465
20630
  await runStart(opts);
20466
20631
  });