@saltpub/xiaojiu-agent-bridge 0.1.6 → 0.1.7

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
@@ -439,6 +439,9 @@ function getMessageReplyMode(cfg) {
439
439
  function getShowToolCalls(cfg) {
440
440
  return cfg.preferences?.showToolCalls === true;
441
441
  }
442
+ function getAutoUpdateEnabled(cfg) {
443
+ return cfg.update?.autoUpdate !== false;
444
+ }
442
445
  function getThinkingLevel(preferences) {
443
446
  const raw = preferences?.thinking;
444
447
  return raw && isThinkingLevel(raw) ? raw : "off";
@@ -481,8 +484,8 @@ function getRunIdleTimeoutMs(cfg) {
481
484
  }
482
485
 
483
486
  // src/cli/commands/update.ts
484
- import { existsSync as existsSync3 } from "fs";
485
- import { readFile as readFile5 } from "fs/promises";
487
+ import { existsSync as existsSync7 } from "fs";
488
+ import { readFile as readFile7 } from "fs/promises";
486
489
  import path3 from "path";
487
490
  import { fileURLToPath as fileURLToPath2 } from "url";
488
491
 
@@ -516,6 +519,16 @@ function resolveAppPaths(opts = {}) {
516
519
  hostLogsDir: join2(rootDir, "logs"),
517
520
  hostLockFile: join2(userLockDir, "supervisor.lock"),
518
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"),
519
532
  registryDir,
520
533
  userRegistryFile: join2(registryDir, "processes.json"),
521
534
  userLockDir,
@@ -2405,11 +2418,10 @@ function unknownState(detail) {
2405
2418
  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.`);
2406
2419
  }
2407
2420
 
2408
- // src/cli/commands/update.ts
2409
- var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
2421
+ // src/selfupdate/version-check.ts
2422
+ var REGISTRY_URL = "https://registry.npmjs.org";
2410
2423
  var PASSIVE_REQUEST_TIMEOUT_MS = 1500;
2411
2424
  var EXPLICIT_REQUEST_TIMEOUT_MS = 1e4;
2412
- var REGISTRY_URL = "https://registry.npmjs.org";
2413
2425
  function compareVersions(left, right) {
2414
2426
  const a = parseVersion(left);
2415
2427
  const b = parseVersion(right);
@@ -2482,152 +2494,6 @@ async function fetchUpdateInfo(options = {}) {
2482
2494
  clearTimeout(timer);
2483
2495
  }
2484
2496
  }
2485
- async function maybeShowUpdateNotice() {
2486
- if (isUpdateCheckDisabled()) return;
2487
- const state = await readState();
2488
- const lastChecked = Date.parse(state.lastCheckedAt ?? "");
2489
- if (Number.isFinite(lastChecked) && Date.now() - lastChecked < CHECK_INTERVAL_MS) return;
2490
- let info;
2491
- try {
2492
- info = await fetchUpdateInfo({ throwOnError: true });
2493
- } catch {
2494
- return;
2495
- }
2496
- const checkedAt = (/* @__PURE__ */ new Date()).toISOString();
2497
- await writeState({ ...state, lastCheckedAt: checkedAt });
2498
- if (!info || info.latestVersion === state.lastNotifiedVersion) return;
2499
- await writeState({ ...state, lastCheckedAt: checkedAt, lastNotifiedVersion: info.latestVersion });
2500
- printUpdateNotice(info, process.stderr);
2501
- }
2502
- async function runUpdateCheck(options = {}) {
2503
- const name = options.packageName ?? packageName;
2504
- const current = options.currentVersion ?? version;
2505
- const log2 = options.log ?? ((message) => process.stdout.write(`${message}
2506
- `));
2507
- const installation = options.checkOnly ? void 0 : await (options.installation ?? (() => resolveUpdateInstallation({ name })))();
2508
- if (installation?.kind === "npx") {
2509
- const registryArgs = `--registry=${REGISTRY_URL}${name.startsWith("@") ? ` --${name.split("/")[0]}:registry=${REGISTRY_URL}` : ""}`;
2510
- throw new Error(`This command is running from an npx cache. No global installation was changed. Run \`npx ${registryArgs} ${name}@latest\` to use the latest version, or add \`update --check\` to check only.`);
2511
- }
2512
- if (installation?.kind === "source") {
2513
- throw new Error("This command is running from a source checkout or local installation, not the current npm global package. For a checkout, update it with Git and run `pnpm install --frozen-lockfile` (prepare rebuilds the CLI); for a local dependency, use its owning package manager. Use `update --check` to check only. No global installation was changed.");
2514
- }
2515
- const info = await fetchUpdateInfo({
2516
- fetchImpl: options.fetchImpl,
2517
- currentVersion: current,
2518
- packageName: name,
2519
- throwOnError: true,
2520
- timeoutMs: EXPLICIT_REQUEST_TIMEOUT_MS
2521
- });
2522
- if (!info) {
2523
- log2(`${name} ${current} is up to date.`);
2524
- return;
2525
- }
2526
- if (options.checkOnly) {
2527
- log2(formatUpdateNotice(info, { packageName: name, checkOnly: true }));
2528
- return;
2529
- }
2530
- await (options.assertIdle ?? ((installationRoot) => assertUpdateInstallationIdle({
2531
- installationRoot,
2532
- name
2533
- })))(installation.root);
2534
- log2(formatUpdateNotice(info, { packageName: name }));
2535
- const args = ["install", "-g", `${name}@${info.latestVersion}`, `--registry=${REGISTRY_URL}`];
2536
- if (name.startsWith("@")) args.push(`--${name.split("/")[0]}:registry=${REGISTRY_URL}`);
2537
- const result = await (options.spawn ?? spawnNpmInstall)("npm", args);
2538
- if (result.code !== 0) {
2539
- throw new Error(`npm ${args.join(" ")} failed with ${result.code}`);
2540
- }
2541
- log2(`Updated to ${info.latestVersion}. Start the bridge again when ready.`);
2542
- }
2543
- async function runChangelog(requestedVersion) {
2544
- const changelog = await readFile5(changelogPath(), "utf8");
2545
- const target = requestedVersion ?? version;
2546
- const section = extractChangelogSection(changelog, target);
2547
- if (!section) {
2548
- throw new Error(`No changelog entry found for ${target}`);
2549
- }
2550
- process.stdout.write(`${section.trim()}
2551
- `);
2552
- }
2553
- function extractChangelogSection(markdown, requestedVersion) {
2554
- const escapedVersion = requestedVersion.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2555
- const match = new RegExp(`^## ${escapedVersion}\\s*$`, "m").exec(markdown);
2556
- if (!match || match.index === void 0) return void 0;
2557
- const start = match.index;
2558
- const after = markdown.slice(start + match[0].length);
2559
- const next = after.search(/\n## /);
2560
- const body = next < 0 ? after : after.slice(0, next);
2561
- return `${match[0]}${body}`.trim();
2562
- }
2563
- function formatUpdateNotice(info, options = {}) {
2564
- const name = options.packageName ?? packageName;
2565
- const lines = [`A new version of ${name} is available: ${info.currentVersion} -> ${info.latestVersion}`];
2566
- if (info.securityFix) lines.push("", "Security update: updating promptly is recommended.");
2567
- if (info.requiresRestart) lines.push("", "Restart the bridge after updating: `xiaojiu-agent-bridge restart`");
2568
- if (info.breakingChanges.length > 0) lines.push("", "Breaking changes:", ...info.breakingChanges.map((item) => ` - ${item}`));
2569
- if (info.highlights.length > 0) lines.push("", "What's new:", ...info.highlights.map((item) => ` - ${item}`));
2570
- if (options.checkOnly) {
2571
- lines.push("", "Install with:", ` ${cliName()} update`);
2572
- } else {
2573
- lines.push("", `Installing ${name}@${info.latestVersion} with npm ...`);
2574
- }
2575
- lines.push("", "View details with:", ` ${cliName()} changelog ${info.latestVersion}`);
2576
- return lines.join("\n");
2577
- }
2578
- function printUpdateNotice(info, stream2) {
2579
- stream2.write(`${formatUpdateNotice(info, { checkOnly: true })}
2580
- `);
2581
- }
2582
- function cliName() {
2583
- return "xiaojiu-agent-bridge";
2584
- }
2585
- function spawnNpmInstall(command, args) {
2586
- return new Promise((resolve5, reject4) => {
2587
- const child = spawnProcess(command, args, { stdio: "inherit" });
2588
- child.on("error", reject4);
2589
- child.on("exit", (code, signal) => {
2590
- if (signal !== null) reject4(new Error(`${command} ${args.join(" ")} signal ${signal}`));
2591
- else resolve5({ code: code ?? 1 });
2592
- });
2593
- });
2594
- }
2595
- function isUpdateCheckDisabled() {
2596
- return process.env.XIAOJIU_BRIDGE_NO_UPDATE_CHECK === "1" || process.env.CI === "true" || process.env.TERM === "dumb" || !process.stdin.isTTY || !process.stdout.isTTY;
2597
- }
2598
- function changelogPath() {
2599
- const moduleDir = path3.dirname(fileURLToPath2(import.meta.url));
2600
- const candidates = [
2601
- path3.resolve(moduleDir, "CHANGELOG.md"),
2602
- path3.resolve(moduleDir, "..", "CHANGELOG.md"),
2603
- path3.resolve(moduleDir, "..", "..", "CHANGELOG.md"),
2604
- path3.resolve(moduleDir, "..", "..", "..", "CHANGELOG.md")
2605
- ];
2606
- const match = candidates.find((candidate) => existsSync3(candidate));
2607
- if (!match) throw new Error("CHANGELOG.md is not included in this installation");
2608
- return match;
2609
- }
2610
- function statePath() {
2611
- return paths.updateStateFile;
2612
- }
2613
- async function readState() {
2614
- try {
2615
- const state = JSON.parse(await readFile5(statePath(), "utf8"));
2616
- return {
2617
- ...typeof state?.lastCheckedAt === "string" ? { lastCheckedAt: state.lastCheckedAt } : {},
2618
- ...typeof state?.lastNotifiedVersion === "string" ? { lastNotifiedVersion: state.lastNotifiedVersion } : {}
2619
- };
2620
- } catch {
2621
- return {};
2622
- }
2623
- }
2624
- async function writeState(state) {
2625
- try {
2626
- await writeFileAtomic(statePath(), `${JSON.stringify(state, null, 2)}
2627
- `, { mode: 384 });
2628
- } catch {
2629
- }
2630
- }
2631
2497
  function parseVersion(value) {
2632
2498
  const match = value.match(
2633
2499
  /^(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-]+)*)?$/
@@ -2646,74 +2512,12 @@ function stringList(value) {
2646
2512
  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);
2647
2513
  }
2648
2514
 
2649
- // src/cli/commands/listen-client.ts
2650
- var ListenApiError = class extends Error {
2651
- constructor(message, status) {
2652
- super(message);
2653
- this.status = status;
2654
- }
2655
- status;
2656
- };
2657
- function apiUrl(sidecar, path4) {
2658
- const url = new URL(sidecar.url);
2659
- url.pathname = path4;
2660
- url.search = "";
2661
- url.searchParams.set("token", sidecar.token);
2662
- return url.toString();
2663
- }
2664
- function errorMessage(parsed, fallback) {
2665
- if (parsed && typeof parsed === "object" && "error" in parsed) {
2666
- const error = parsed.error;
2667
- if (typeof error === "string" && error.trim()) return error;
2668
- }
2669
- return fallback;
2670
- }
2671
- async function postJson(sidecar, path4, body) {
2672
- const response = await fetch(apiUrl(sidecar, path4), {
2673
- method: "POST",
2674
- headers: {
2675
- "content-type": "application/json",
2676
- "x-ui-token": sidecar.token
2677
- },
2678
- body: JSON.stringify(body)
2679
- });
2680
- const text2 = await response.text();
2681
- let parsed = {};
2682
- if (text2) {
2683
- try {
2684
- parsed = JSON.parse(text2);
2685
- } catch {
2686
- parsed = { error: text2 };
2687
- }
2688
- }
2689
- if (!response.ok) {
2690
- throw new ListenApiError(errorMessage(parsed, `HTTP ${response.status}`), response.status);
2691
- }
2692
- return parsed;
2693
- }
2694
- async function joinListenProfile(sidecar, profile2) {
2695
- await postJson(sidecar, "/api/profiles/start", { profile: profile2 });
2696
- }
2697
- async function leaveListenProfile(sidecar, profile2) {
2698
- await postJson(sidecar, "/api/profiles/stop", { profile: profile2 });
2699
- }
2700
- async function listListenBots(sidecar) {
2701
- const response = await fetch(apiUrl(sidecar, "/api/bots"), {
2702
- headers: { "x-ui-token": sidecar.token }
2703
- });
2704
- if (!response.ok) throw new ListenApiError(`HTTP ${response.status}`, response.status);
2705
- const parsed = await response.json();
2706
- if (!parsed || typeof parsed !== "object" || !("bots" in parsed) || !Array.isArray(parsed.bots)) {
2707
- return [];
2708
- }
2709
- const names = [];
2710
- for (const bot of parsed.bots) {
2711
- if (bot && typeof bot === "object" && "profileName" in bot && typeof bot.profileName === "string") {
2712
- names.push({ profileName: bot.profileName });
2713
- }
2714
- }
2715
- return names;
2716
- }
2515
+ // src/daemon/launchd.ts
2516
+ import { spawnSync } from "child_process";
2517
+ import { existsSync as existsSync4 } from "fs";
2518
+ import { mkdir as mkdir7, rm as rm6, writeFile as writeFile4 } from "fs/promises";
2519
+ import { userInfo } from "os";
2520
+ import { dirname as dirname8 } from "path";
2717
2521
 
2718
2522
  // src/daemon/paths.ts
2719
2523
  import { homedir as homedir2 } from "os";
@@ -2771,19 +2575,13 @@ function daemonStderrPath(profile2 = paths.profile) {
2771
2575
  return join7(daemonLogDir(profile2), "daemon-stderr.log");
2772
2576
  }
2773
2577
 
2774
- // src/daemon/launchd.ts
2775
- import { spawnSync } from "child_process";
2776
- import { existsSync as existsSync5 } from "fs";
2777
- import { mkdir as mkdir7, rm as rm6, writeFile as writeFile4 } from "fs/promises";
2778
- import { userInfo } from "os";
2779
- import { dirname as dirname8 } from "path";
2780
-
2781
2578
  // src/daemon/launch-spec.ts
2782
- import { existsSync as existsSync4 } from "fs";
2579
+ import { existsSync as existsSync3 } from "fs";
2783
2580
  import { createRequire } from "module";
2784
2581
  import { dirname as dirname7, resolve } from "path";
2785
2582
  import { pathToFileURL } from "url";
2786
- function resolveDaemonLaunch(argv1 = process.argv[1]) {
2583
+ function resolveDaemonLaunch(argv1 = process.argv[1], override) {
2584
+ if (override) return override;
2787
2585
  if (!argv1) {
2788
2586
  throw new Error("cannot determine bridge entry path (process.argv[1] is empty)");
2789
2587
  }
@@ -2792,7 +2590,7 @@ function resolveDaemonLaunch(argv1 = process.argv[1]) {
2792
2590
  return { importArgs: [], entryPath };
2793
2591
  }
2794
2592
  const registerHtml = resolve(dirname7(entryPath), "register-html.mjs");
2795
- if (!existsSync4(registerHtml)) {
2593
+ if (!existsSync3(registerHtml)) {
2796
2594
  throw new Error(
2797
2595
  `cannot install a daemon from TypeScript sources (${entryPath}); missing ${registerHtml}`
2798
2596
  );
@@ -2854,12 +2652,12 @@ ${programArgs}
2854
2652
  </plist>
2855
2653
  `;
2856
2654
  }
2857
- async function writePlist(profile2, runArgs = ["run"]) {
2858
- const launch = resolveDaemonLaunch();
2655
+ async function writePlist(profile2, runArgs = ["run"], launch) {
2656
+ const resolved = resolveDaemonLaunch(void 0, launch);
2859
2657
  const content = buildPlist({
2860
2658
  nodePath: process.execPath,
2861
- importArgs: launch.importArgs,
2862
- bridgeEntryPath: launch.entryPath,
2659
+ importArgs: resolved.importArgs,
2660
+ bridgeEntryPath: resolved.entryPath,
2863
2661
  envPath: process.env.PATH ?? "",
2864
2662
  profile: profile2,
2865
2663
  runArgs,
@@ -2871,7 +2669,7 @@ async function writePlist(profile2, runArgs = ["run"]) {
2871
2669
  await writeFile4(plistPath, content, "utf8");
2872
2670
  }
2873
2671
  function plistExists(profile2) {
2874
- return existsSync5(launchAgentPlistPath(profile2));
2672
+ return existsSync4(launchAgentPlistPath(profile2));
2875
2673
  }
2876
2674
  function userTarget() {
2877
2675
  return `gui/${userInfo().uid}`;
@@ -2926,7 +2724,7 @@ async function deletePlist(profile2) {
2926
2724
 
2927
2725
  // src/daemon/schtasks.ts
2928
2726
  import { spawnSync as spawnSync2 } from "child_process";
2929
- import { existsSync as existsSync6 } from "fs";
2727
+ import { existsSync as existsSync5 } from "fs";
2930
2728
  import { mkdir as mkdir8, rm as rm7, writeFile as writeFile5 } from "fs/promises";
2931
2729
  import { dirname as dirname9 } from "path";
2932
2730
  function buildLauncherCmd(inputs) {
@@ -2999,15 +2797,15 @@ function buildTaskXml(profile2, vbsPath) {
2999
2797
  </Task>
3000
2798
  `;
3001
2799
  }
3002
- async function writeLauncherScripts(profile2, runArgs = ["run"]) {
2800
+ async function writeLauncherScripts(profile2, runArgs = ["run"], launch) {
3003
2801
  const cmdPath = windowsLauncherCmdPath(profile2);
3004
2802
  const vbsPath = windowsLauncherVbsPath(profile2);
3005
2803
  const xmlPath = windowsTaskXmlPath(profile2);
3006
- const launch = resolveDaemonLaunch();
2804
+ const resolved = resolveDaemonLaunch(void 0, launch);
3007
2805
  const content = buildLauncherCmd({
3008
2806
  nodePath: process.execPath,
3009
- importArgs: launch.importArgs,
3010
- bridgeEntryPath: launch.entryPath,
2807
+ importArgs: resolved.importArgs,
2808
+ bridgeEntryPath: resolved.entryPath,
3011
2809
  envPath: process.env.PATH ?? "",
3012
2810
  profile: profile2,
3013
2811
  runArgs,
@@ -3038,8 +2836,8 @@ function runSchtasks(args) {
3038
2836
  stdout: decodeWindowsConsole(r.stdout)
3039
2837
  };
3040
2838
  }
3041
- async function installTask(profile2, runArgs = ["run"]) {
3042
- const xmlPath = await writeLauncherScripts(profile2, runArgs);
2839
+ async function installTask(profile2, runArgs = ["run"], launch) {
2840
+ const xmlPath = await writeLauncherScripts(profile2, runArgs, launch);
3043
2841
  return runSchtasks(["/Create", "/F", "/TN", windowsTaskName(profile2), "/XML", xmlPath]);
3044
2842
  }
3045
2843
  function runTask(profile2) {
@@ -3107,14 +2905,14 @@ async function deleteTask(profile2) {
3107
2905
  windowsLauncherVbsPath(profile2),
3108
2906
  windowsTaskXmlPath(profile2)
3109
2907
  ]) {
3110
- if (existsSync6(path4)) await rm7(path4, { force: true });
2908
+ if (existsSync5(path4)) await rm7(path4, { force: true });
3111
2909
  }
3112
2910
  return r;
3113
2911
  }
3114
2912
 
3115
2913
  // src/daemon/systemd.ts
3116
2914
  import { spawnSync as spawnSync3 } from "child_process";
3117
- import { existsSync as existsSync7 } from "fs";
2915
+ import { existsSync as existsSync6 } from "fs";
3118
2916
  import { mkdir as mkdir9, rm as rm8, writeFile as writeFile6 } from "fs/promises";
3119
2917
  import { dirname as dirname10 } from "path";
3120
2918
  function buildUnit(inputs) {
@@ -3141,12 +2939,12 @@ Environment="XIAOJIU_BRIDGE_HOME=${escape(inputs.channelHome)}"
3141
2939
  WantedBy=default.target
3142
2940
  `;
3143
2941
  }
3144
- async function writeUnit(profile2, runArgs = ["run"]) {
3145
- const launch = resolveDaemonLaunch();
2942
+ async function writeUnit(profile2, runArgs = ["run"], launch) {
2943
+ const resolved = resolveDaemonLaunch(void 0, launch);
3146
2944
  const content = buildUnit({
3147
2945
  nodePath: process.execPath,
3148
- importArgs: launch.importArgs,
3149
- bridgeEntryPath: launch.entryPath,
2946
+ importArgs: resolved.importArgs,
2947
+ bridgeEntryPath: resolved.entryPath,
3150
2948
  envPath: process.env.PATH ?? "",
3151
2949
  profile: profile2,
3152
2950
  runArgs,
@@ -3158,7 +2956,7 @@ async function writeUnit(profile2, runArgs = ["run"]) {
3158
2956
  await writeFile6(unitPath, content, "utf8");
3159
2957
  }
3160
2958
  function unitExists(profile2) {
3161
- return existsSync7(systemdUnitPath(profile2));
2959
+ return existsSync6(systemdUnitPath(profile2));
3162
2960
  }
3163
2961
  function runSystemctl(args) {
3164
2962
  const r = spawnSync3("systemctl", ["--user", ...args], { encoding: "utf8" });
@@ -3202,117 +3000,609 @@ async function waitUntilInactive(profile2, timeoutMs = 5e3) {
3202
3000
  if (!isActive(profile2)) return true;
3203
3001
  await new Promise((r) => setTimeout(r, 200));
3204
3002
  }
3205
- return false;
3206
- }
3207
- async function deleteUnit(profile2) {
3208
- await rm8(systemdUnitPath(profile2), { force: true });
3003
+ return false;
3004
+ }
3005
+ async function deleteUnit(profile2) {
3006
+ await rm8(systemdUnitPath(profile2), { force: true });
3007
+ }
3008
+
3009
+ // src/daemon/service-adapter.ts
3010
+ function makeLaunchdAdapter(profile2, runArgs, launch) {
3011
+ return {
3012
+ platformName: "launchd (macOS)",
3013
+ fileExists: () => plistExists(profile2),
3014
+ isRunning: () => isLoaded(profile2),
3015
+ servicePath: () => launchAgentPlistPath(profile2),
3016
+ install: () => writePlist(profile2, runArgs, launch),
3017
+ // A previous `stop` may have left the job disabled in launchd's override
3018
+ // DB, where it would stay dead through bootstrap. Always enable first.
3019
+ start: () => {
3020
+ enable(profile2);
3021
+ return bootstrap(profile2);
3022
+ },
3023
+ stop: () => bootout(profile2),
3024
+ // bootout alone is session-scoped: the plist keeps RunAtLoad=true, so
3025
+ // launchd re-bootstraps the job at the next login. Pair it with an
3026
+ // explicit `disable` to actually match systemd's `disable --now`.
3027
+ stopAndDisableAutostart: () => {
3028
+ const out = bootout(profile2);
3029
+ const disabled = disable(profile2);
3030
+ return out.ok ? disabled : out;
3031
+ },
3032
+ disableAutostart: () => disable(profile2),
3033
+ restart: () => kickstart(profile2),
3034
+ waitUntilStopped: (timeoutMs) => waitUntilUnloaded(profile2, timeoutMs),
3035
+ deleteFile: () => deletePlist(profile2),
3036
+ describeStatus: () => describeService(profile2),
3037
+ parseStatus: (text2) => ({
3038
+ pid: text2.match(/pid\s*=\s*(\d+)/)?.[1],
3039
+ lastExit: text2.match(/last exit code\s*=\s*(-?\d+)/i)?.[1]
3040
+ })
3041
+ };
3042
+ }
3043
+ function makeSystemdAdapter(profile2, runArgs, launch) {
3044
+ return {
3045
+ platformName: "systemd (Linux user)",
3046
+ fileExists: () => unitExists(profile2),
3047
+ isRunning: () => isActive(profile2),
3048
+ servicePath: () => systemdUnitPath(profile2),
3049
+ install: async () => {
3050
+ await writeUnit(profile2, runArgs, launch);
3051
+ daemonReload();
3052
+ },
3053
+ start: () => enableAndStart(profile2),
3054
+ stop: () => stop(profile2),
3055
+ stopAndDisableAutostart: () => disableAndStop(profile2),
3056
+ disableAutostart: () => disable2(profile2),
3057
+ restart: () => restart(profile2),
3058
+ waitUntilStopped: (timeoutMs) => waitUntilInactive(profile2, timeoutMs),
3059
+ deleteFile: async () => {
3060
+ await deleteUnit(profile2);
3061
+ daemonReload();
3062
+ },
3063
+ describeStatus: () => describeService2(profile2),
3064
+ // `systemctl status` includes a "Main PID:" line and an "Active:"
3065
+ // line. There's no single "last exit code" field in the standard
3066
+ // output but the "Process: <pid> ExecStart=... status=<n>" line on
3067
+ // an inactive service exposes it.
3068
+ parseStatus: (text2) => ({
3069
+ pid: text2.match(/Main PID:\s*(\d+)/)?.[1],
3070
+ lastExit: text2.match(/Process:\s+\d+\s+ExecStart=.*status=(\d+)/)?.[1]
3071
+ })
3072
+ };
3073
+ }
3074
+ function makeSchtasksAdapter(profile2, runArgs, launch) {
3075
+ return {
3076
+ platformName: "Task Scheduler (Windows)",
3077
+ fileExists: () => isTaskRegistered(profile2),
3078
+ isRunning: () => isTaskRunning(profile2),
3079
+ // Windows doesn't have a single "service file" — there's the task
3080
+ // registration (queryable via schtasks) and the hidden launcher we wrote.
3081
+ // The task name is what the user would search for in Task Scheduler UI.
3082
+ servicePath: () => windowsTaskName(profile2),
3083
+ install: async () => {
3084
+ const r = await installTask(profile2, runArgs, launch);
3085
+ if (!r.ok) throw new Error(r.stderr || "schtasks /Create failed");
3086
+ },
3087
+ // Mirror launchd: a previous `stop` disabled the task, and a disabled
3088
+ // task refuses to run. Re-enable before starting it.
3089
+ start: () => {
3090
+ enableTask(profile2);
3091
+ return runTask(profile2);
3092
+ },
3093
+ stop: () => endTask(profile2),
3094
+ stopAndDisableAutostart: () => endAndDisable(profile2),
3095
+ disableAutostart: () => disableTask(profile2),
3096
+ // schtasks has no native /Restart — adapter awaits end+wait+run.
3097
+ restart: () => restartTask(profile2),
3098
+ waitUntilStopped: (timeoutMs) => waitUntilStopped(profile2, timeoutMs),
3099
+ deleteFile: async () => {
3100
+ await deleteTask(profile2);
3101
+ },
3102
+ describeStatus: () => describeTask(profile2),
3103
+ parseStatus: (text2) => {
3104
+ const parsed = parseTaskListFields(text2);
3105
+ return { pid: parsed.pid, lastExit: parsed.lastExit };
3106
+ }
3107
+ };
3108
+ }
3109
+ function getServiceAdapter(profile2 = "claude", runArgs = ["run"], launch) {
3110
+ if (process.platform === "darwin") return makeLaunchdAdapter(profile2, runArgs, launch);
3111
+ if (process.platform === "linux") return makeSystemdAdapter(profile2, runArgs, launch);
3112
+ if (process.platform === "win32") return makeSchtasksAdapter(profile2, runArgs, launch);
3113
+ return null;
3114
+ }
3115
+
3116
+ // src/selfupdate/stage.ts
3117
+ import { mkdir as mkdir11, mkdtemp, open as open2, readFile as readFile6, rm as rm10 } from "fs/promises";
3118
+ import { tmpdir } from "os";
3119
+ import { join as join9 } from "path";
3120
+
3121
+ // src/selfupdate/store.ts
3122
+ import { mkdir as mkdir10, readdir as readdir4, readFile as readFile5, rm as rm9 } from "fs/promises";
3123
+ import { dirname as dirname11, join as join8 } from "path";
3124
+ function updateLayout(rootDir) {
3125
+ return {
3126
+ updateDir: join8(rootDir, "update"),
3127
+ versionsDir: join8(rootDir, "versions"),
3128
+ launcherDir: join8(rootDir, "launcher"),
3129
+ launcherFile: join8(rootDir, "launcher", "launcher.mjs"),
3130
+ currentVersionFile: join8(rootDir, "update", "current.json"),
3131
+ pendingVersionFile: join8(rootDir, "update", "pending.json"),
3132
+ bootStateFile: join8(rootDir, "update", "boot.json"),
3133
+ badVersionsFile: join8(rootDir, "update", "bad.json"),
3134
+ stageLockFile: join8(rootDir, "update", "stage.lock"),
3135
+ selfUpdateLogFile: join8(rootDir, "update", "self-update.log")
3136
+ };
3137
+ }
3138
+ function versionDir(layout, version2) {
3139
+ return join8(layout.versionsDir, version2);
3140
+ }
3141
+ function packageDirOf(installRoot, name = packageName) {
3142
+ return join8(installRoot, "node_modules", ...name.split("/"));
3143
+ }
3144
+ async function readJson(file) {
3145
+ try {
3146
+ return JSON.parse(await readFile5(file, "utf8"));
3147
+ } catch {
3148
+ return void 0;
3149
+ }
3150
+ }
3151
+ async function writeJson(file, value) {
3152
+ await mkdir10(dirname11(file), { recursive: true });
3153
+ await writeFileAtomic(file, `${JSON.stringify(value, null, 2)}
3154
+ `, { mode: 384 });
3155
+ }
3156
+ function isPointer(value) {
3157
+ if (!value || typeof value !== "object") return false;
3158
+ const v = value;
3159
+ return typeof v.version === "string" && typeof v.dir === "string";
3160
+ }
3161
+ function readCurrent(layout) {
3162
+ return readJson(layout.currentVersionFile).then((v) => v && isPointer(v) ? v : void 0);
3163
+ }
3164
+ function writeCurrent(layout, pointer) {
3165
+ return writeJson(layout.currentVersionFile, pointer);
3166
+ }
3167
+ function writePending(layout, pending) {
3168
+ return writeJson(layout.pendingVersionFile, pending);
3169
+ }
3170
+ async function readBadVersions(layout) {
3171
+ const bad = await readJson(layout.badVersionsFile);
3172
+ return Array.isArray(bad?.versions) ? bad.versions.filter((v) => typeof v === "string") : [];
3173
+ }
3174
+ async function gcVersions(layout, keep = 3) {
3175
+ const current = await readCurrent(layout);
3176
+ const protectedDirs = new Set(
3177
+ [current?.dir, current?.previous?.dir].filter((d) => typeof d === "string")
3178
+ );
3179
+ let entries;
3180
+ try {
3181
+ entries = await readdir4(layout.versionsDir);
3182
+ } catch {
3183
+ return [];
3184
+ }
3185
+ const removed = [];
3186
+ const valid = [];
3187
+ for (const name of entries) {
3188
+ const dir = join8(layout.versionsDir, name);
3189
+ if (!/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(name)) {
3190
+ if (!protectedDirs.has(dir)) {
3191
+ await rm9(dir, { recursive: true, force: true, maxRetries: 5 });
3192
+ removed.push(dir);
3193
+ }
3194
+ continue;
3195
+ }
3196
+ if (!protectedDirs.has(dir)) valid.push({ name, dir });
3197
+ }
3198
+ const dirs = valid.sort((a, b) => compareVersions(a.name, b.name)).reverse().map((entry) => entry.dir);
3199
+ for (const dir of dirs.slice(Math.max(keep - protectedDirs.size, 0))) {
3200
+ await rm9(dir, { recursive: true, force: true, maxRetries: 5 });
3201
+ removed.push(dir);
3202
+ }
3203
+ return removed;
3204
+ }
3205
+
3206
+ // src/selfupdate/stage.ts
3207
+ var STAGE_LOCK_STALE_MS = 30 * 60 * 1e3;
3208
+ var SMOKE_TIMEOUT_MS = 3e4;
3209
+ async function stageVersion(deps) {
3210
+ const { layout, targetVersion } = deps;
3211
+ const name = deps.name ?? packageName;
3212
+ const log2 = deps.log ?? (() => {
3213
+ });
3214
+ if ((await readBadVersions(layout)).includes(targetVersion)) {
3215
+ return { ok: false, error: `version ${targetVersion} previously failed its health check; not restaging` };
3216
+ }
3217
+ const current = await readCurrent(layout);
3218
+ if (current?.version === targetVersion) {
3219
+ return { ok: true, dir: current.dir, reused: true };
3220
+ }
3221
+ const release = await acquireStageLock(layout);
3222
+ if (!release) return { ok: false, error: "another stage is in progress" };
3223
+ const dir = versionDir(layout, targetVersion);
3224
+ try {
3225
+ const pkgDir = packageDirOf(dir, name);
3226
+ if (await installedVersionMatches(pkgDir, targetVersion)) {
3227
+ log2("stage.reuse", { version: targetVersion, dir });
3228
+ return { ok: true, dir, reused: true };
3229
+ }
3230
+ await rm10(dir, { recursive: true, force: true, maxRetries: 5 });
3231
+ const registryArgs = [`--registry=${REGISTRY_URL}`];
3232
+ if (name.startsWith("@")) registryArgs.push(`--${name.split("/")[0]}:registry=${REGISTRY_URL}`);
3233
+ const result = await (deps.runNpm ?? runNpm)([
3234
+ "install",
3235
+ "--prefix",
3236
+ dir,
3237
+ "--no-save",
3238
+ "--no-audit",
3239
+ "--no-fund",
3240
+ `${name}@${targetVersion}`,
3241
+ ...registryArgs
3242
+ ]);
3243
+ if (result.code !== 0) {
3244
+ await rm10(dir, { recursive: true, force: true, maxRetries: 5 });
3245
+ return { ok: false, error: `npm install failed (${result.code}): ${(result.stderr ?? "").trim().slice(0, 300)}` };
3246
+ }
3247
+ if (!await installedVersionMatches(pkgDir, targetVersion)) {
3248
+ await rm10(dir, { recursive: true, force: true, maxRetries: 5 });
3249
+ return { ok: false, error: `staged package.json does not report ${targetVersion}` };
3250
+ }
3251
+ try {
3252
+ await (deps.runSmoke ?? smokeTest)(pkgDir, targetVersion);
3253
+ } catch (err) {
3254
+ await rm10(dir, { recursive: true, force: true, maxRetries: 5 });
3255
+ return { ok: false, error: `smoke test failed: ${err instanceof Error ? err.message : String(err)}` };
3256
+ }
3257
+ log2("stage.installed", { version: targetVersion, dir });
3258
+ await gcVersions(layout).catch(() => {
3259
+ });
3260
+ return { ok: true, dir, reused: false };
3261
+ } finally {
3262
+ await release();
3263
+ }
3264
+ }
3265
+ async function installedVersionMatches(pkgDir, expected) {
3266
+ try {
3267
+ const manifest2 = JSON.parse(await readFile6(join9(pkgDir, "package.json"), "utf8"));
3268
+ return typeof manifest2 === "object" && manifest2 !== null && "version" in manifest2 && manifest2.version === expected;
3269
+ } catch {
3270
+ return false;
3271
+ }
3272
+ }
3273
+ async function acquireStageLock(layout) {
3274
+ await mkdir11(layout.updateDir, { recursive: true });
3275
+ for (let attempt = 0; attempt < 2; attempt += 1) {
3276
+ try {
3277
+ const handle2 = await open2(layout.stageLockFile, "wx");
3278
+ await handle2.writeFile(JSON.stringify({ pid: process.pid, at: (/* @__PURE__ */ new Date()).toISOString() }));
3279
+ await handle2.close();
3280
+ return async () => {
3281
+ await rm10(layout.stageLockFile, { force: true });
3282
+ };
3283
+ } catch (err) {
3284
+ if (err.code !== "EEXIST") throw err;
3285
+ const stale = await readFile6(layout.stageLockFile, "utf8").then((text2) => {
3286
+ const parsed = JSON.parse(text2);
3287
+ const at = typeof parsed === "object" && parsed !== null && "at" in parsed && typeof parsed.at === "string" ? Date.parse(parsed.at) : Number.NaN;
3288
+ return !Number.isFinite(at) || Date.now() - at > STAGE_LOCK_STALE_MS;
3289
+ }).catch(() => true);
3290
+ if (!stale) return void 0;
3291
+ await rm10(layout.stageLockFile, { force: true });
3292
+ }
3293
+ }
3294
+ return void 0;
3295
+ }
3296
+ function runNpm(args) {
3297
+ return new Promise((resolve5, reject4) => {
3298
+ const child = spawnProcess("npm", args, { stdio: ["ignore", "ignore", "pipe"] });
3299
+ let stderr = "";
3300
+ child.stderr?.on("data", (chunk) => {
3301
+ stderr += chunk.toString("utf8");
3302
+ });
3303
+ child.on("error", reject4);
3304
+ child.on("exit", (code, signal) => {
3305
+ if (signal !== null) reject4(new Error(`npm ${args.join(" ")} signal ${signal}`));
3306
+ else resolve5({ code: code ?? 1, stderr });
3307
+ });
3308
+ });
3309
+ }
3310
+ async function smokeTest(pkgDir, expectedVersion) {
3311
+ const fakeHome = await mkdtemp(join9(tmpdir(), "xiaojiu-smoke-"));
3312
+ try {
3313
+ const bin = join9(pkgDir, "bin", "xiaojiu-agent-bridge.mjs");
3314
+ await new Promise((resolve5, reject4) => {
3315
+ const child = spawnProcess(process.execPath, [bin, "--version"], {
3316
+ stdio: ["ignore", "pipe", "pipe"],
3317
+ env: {
3318
+ ...process.env,
3319
+ XIAOJIU_BRIDGE_HOME: fakeHome,
3320
+ XIAOJIU_BRIDGE_NO_UPDATE_CHECK: "1"
3321
+ }
3322
+ });
3323
+ let out = "";
3324
+ child.stdout?.on("data", (chunk) => {
3325
+ out += chunk.toString("utf8");
3326
+ });
3327
+ const timer = setTimeout(() => {
3328
+ child.kill("SIGKILL");
3329
+ reject4(new Error(`--version timed out after ${SMOKE_TIMEOUT_MS}ms`));
3330
+ }, SMOKE_TIMEOUT_MS);
3331
+ child.on("error", (err) => {
3332
+ clearTimeout(timer);
3333
+ reject4(err);
3334
+ });
3335
+ child.on("exit", (code) => {
3336
+ clearTimeout(timer);
3337
+ if (code !== 0) reject4(new Error(`--version exited with ${code}`));
3338
+ else if (!out.includes(expectedVersion)) reject4(new Error(`--version output ${JSON.stringify(out.trim())} does not contain ${expectedVersion}`));
3339
+ else resolve5();
3340
+ });
3341
+ });
3342
+ } finally {
3343
+ await rm10(fakeHome, { recursive: true, force: true, maxRetries: 5 });
3344
+ }
3345
+ }
3346
+
3347
+ // src/cli/commands/update.ts
3348
+ var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
3349
+ async function maybeShowUpdateNotice() {
3350
+ if (isUpdateCheckDisabled()) return;
3351
+ const state = await readState();
3352
+ const lastChecked = Date.parse(state.lastCheckedAt ?? "");
3353
+ if (Number.isFinite(lastChecked) && Date.now() - lastChecked < CHECK_INTERVAL_MS) return;
3354
+ let info;
3355
+ try {
3356
+ info = await fetchUpdateInfo({ throwOnError: true });
3357
+ } catch {
3358
+ return;
3359
+ }
3360
+ const checkedAt = (/* @__PURE__ */ new Date()).toISOString();
3361
+ await writeState({ ...state, lastCheckedAt: checkedAt });
3362
+ if (!info || info.latestVersion === state.lastNotifiedVersion) return;
3363
+ await writeState({ ...state, lastCheckedAt: checkedAt, lastNotifiedVersion: info.latestVersion });
3364
+ printUpdateNotice(info, process.stderr);
3365
+ }
3366
+ async function runUpdateCheck(options = {}) {
3367
+ const name = options.packageName ?? packageName;
3368
+ const current = options.currentVersion ?? version;
3369
+ const log2 = options.log ?? ((message) => process.stdout.write(`${message}
3370
+ `));
3371
+ const layout = options.layout ?? updateLayout(paths.rootDir);
3372
+ if (!options.checkOnly && await readCurrent(layout)) {
3373
+ const info2 = await fetchUpdateInfo({
3374
+ fetchImpl: options.fetchImpl,
3375
+ currentVersion: current,
3376
+ packageName: name,
3377
+ throwOnError: true,
3378
+ timeoutMs: EXPLICIT_REQUEST_TIMEOUT_MS
3379
+ });
3380
+ if (!info2) {
3381
+ log2(`${name} ${current} is up to date.`);
3382
+ return;
3383
+ }
3384
+ log2(formatUpdateNotice(info2, { packageName: name }));
3385
+ const staged = await (options.stage ?? stageVersion)({ layout, targetVersion: info2.latestVersion });
3386
+ if (!staged.ok) throw new Error(`Failed to stage ${info2.latestVersion}: ${staged.error}`);
3387
+ await writePending(layout, {
3388
+ version: info2.latestVersion,
3389
+ dir: staged.dir,
3390
+ stagedAt: (/* @__PURE__ */ new Date()).toISOString()
3391
+ });
3392
+ const restarted = await (options.restartServices ?? restartLauncherServices)();
3393
+ if (restarted > 0) {
3394
+ log2(`Staged ${info2.latestVersion}; restarted ${restarted} daemon service(s) \u2014 the launcher brings the new version up. Active runs were interrupted; the automatic scheduler would have waited for an idle window.`);
3395
+ } else {
3396
+ log2(`Staged ${info2.latestVersion}. It goes live on the next service start (\`xiaojiu-agent-bridge restart\` to apply now).`);
3397
+ }
3398
+ return;
3399
+ }
3400
+ const installation = options.checkOnly ? void 0 : await (options.installation ?? (() => resolveUpdateInstallation({ name })))();
3401
+ if (installation?.kind === "npx") {
3402
+ const registryArgs = `--registry=${REGISTRY_URL}${name.startsWith("@") ? ` --${name.split("/")[0]}:registry=${REGISTRY_URL}` : ""}`;
3403
+ throw new Error(`This command is running from an npx cache. No global installation was changed. Run \`npx ${registryArgs} ${name}@latest\` to use the latest version, or add \`update --check\` to check only.`);
3404
+ }
3405
+ if (installation?.kind === "source") {
3406
+ throw new Error("This command is running from a source checkout or local installation, not the current npm global package. For a checkout, update it with Git and run `pnpm install --frozen-lockfile` (prepare rebuilds the CLI); for a local dependency, use its owning package manager. Use `update --check` to check only. No global installation was changed.");
3407
+ }
3408
+ const info = await fetchUpdateInfo({
3409
+ fetchImpl: options.fetchImpl,
3410
+ currentVersion: current,
3411
+ packageName: name,
3412
+ throwOnError: true,
3413
+ timeoutMs: EXPLICIT_REQUEST_TIMEOUT_MS
3414
+ });
3415
+ if (!info) {
3416
+ log2(`${name} ${current} is up to date.`);
3417
+ return;
3418
+ }
3419
+ if (options.checkOnly) {
3420
+ log2(formatUpdateNotice(info, { packageName: name, checkOnly: true }));
3421
+ return;
3422
+ }
3423
+ await (options.assertIdle ?? ((installationRoot) => assertUpdateInstallationIdle({
3424
+ installationRoot,
3425
+ name
3426
+ })))(installation.root);
3427
+ log2(formatUpdateNotice(info, { packageName: name }));
3428
+ const args = ["install", "-g", `${name}@${info.latestVersion}`, `--registry=${REGISTRY_URL}`];
3429
+ if (name.startsWith("@")) args.push(`--${name.split("/")[0]}:registry=${REGISTRY_URL}`);
3430
+ const result = await (options.spawn ?? spawnNpmInstall)("npm", args);
3431
+ if (result.code !== 0) {
3432
+ throw new Error(`npm ${args.join(" ")} failed with ${result.code}`);
3433
+ }
3434
+ log2(`Updated to ${info.latestVersion}. Start the bridge again when ready.`);
3435
+ }
3436
+ async function runChangelog(requestedVersion) {
3437
+ const changelog = await readFile7(changelogPath(), "utf8");
3438
+ const target = requestedVersion ?? version;
3439
+ const section = extractChangelogSection(changelog, target);
3440
+ if (!section) {
3441
+ throw new Error(`No changelog entry found for ${target}`);
3442
+ }
3443
+ process.stdout.write(`${section.trim()}
3444
+ `);
3445
+ }
3446
+ function extractChangelogSection(markdown, requestedVersion) {
3447
+ const escapedVersion = requestedVersion.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3448
+ const match = new RegExp(`^## ${escapedVersion}\\s*$`, "m").exec(markdown);
3449
+ if (!match || match.index === void 0) return void 0;
3450
+ const start = match.index;
3451
+ const after = markdown.slice(start + match[0].length);
3452
+ const next = after.search(/\n## /);
3453
+ const body = next < 0 ? after : after.slice(0, next);
3454
+ return `${match[0]}${body}`.trim();
3455
+ }
3456
+ function formatUpdateNotice(info, options = {}) {
3457
+ const name = options.packageName ?? packageName;
3458
+ const lines = [`A new version of ${name} is available: ${info.currentVersion} -> ${info.latestVersion}`];
3459
+ if (info.securityFix) lines.push("", "Security update: updating promptly is recommended.");
3460
+ if (info.requiresRestart) lines.push("", "Restart the bridge after updating: `xiaojiu-agent-bridge restart`");
3461
+ if (info.breakingChanges.length > 0) lines.push("", "Breaking changes:", ...info.breakingChanges.map((item) => ` - ${item}`));
3462
+ if (info.highlights.length > 0) lines.push("", "What's new:", ...info.highlights.map((item) => ` - ${item}`));
3463
+ if (options.checkOnly) {
3464
+ lines.push("", "Install with:", ` ${cliName()} update`);
3465
+ } else {
3466
+ lines.push("", `Installing ${name}@${info.latestVersion} with npm ...`);
3467
+ }
3468
+ lines.push("", "View details with:", ` ${cliName()} changelog ${info.latestVersion}`);
3469
+ return lines.join("\n");
3470
+ }
3471
+ function printUpdateNotice(info, stream2) {
3472
+ stream2.write(`${formatUpdateNotice(info, { checkOnly: true })}
3473
+ `);
3474
+ }
3475
+ function cliName() {
3476
+ return "xiaojiu-agent-bridge";
3477
+ }
3478
+ function spawnNpmInstall(command, args) {
3479
+ return new Promise((resolve5, reject4) => {
3480
+ const child = spawnProcess(command, args, { stdio: "inherit" });
3481
+ child.on("error", reject4);
3482
+ child.on("exit", (code, signal) => {
3483
+ if (signal !== null) reject4(new Error(`${command} ${args.join(" ")} signal ${signal}`));
3484
+ else resolve5({ code: code ?? 1 });
3485
+ });
3486
+ });
3487
+ }
3488
+ async function restartLauncherServices() {
3489
+ const ports = /* @__PURE__ */ new Set();
3490
+ for (const entry of readAndPrune()) {
3491
+ if (typeof entry.webhookPort === "number") ports.add(entry.webhookPort);
3492
+ }
3493
+ let restarted = 0;
3494
+ for (const port of ports) {
3495
+ const adapter = getServiceAdapter(`port-${port}`);
3496
+ if (!adapter?.fileExists() || !adapter.isRunning()) continue;
3497
+ const result = await adapter.restart();
3498
+ if (result.ok) restarted += 1;
3499
+ }
3500
+ return restarted;
3501
+ }
3502
+ function isUpdateCheckDisabled() {
3503
+ return process.env.XIAOJIU_BRIDGE_NO_UPDATE_CHECK === "1" || process.env.CI === "true" || process.env.TERM === "dumb" || !process.stdin.isTTY || !process.stdout.isTTY;
3504
+ }
3505
+ function changelogPath() {
3506
+ const moduleDir = path3.dirname(fileURLToPath2(import.meta.url));
3507
+ const candidates = [
3508
+ path3.resolve(moduleDir, "CHANGELOG.md"),
3509
+ path3.resolve(moduleDir, "..", "CHANGELOG.md"),
3510
+ path3.resolve(moduleDir, "..", "..", "CHANGELOG.md"),
3511
+ path3.resolve(moduleDir, "..", "..", "..", "CHANGELOG.md")
3512
+ ];
3513
+ const match = candidates.find((candidate) => existsSync7(candidate));
3514
+ if (!match) throw new Error("CHANGELOG.md is not included in this installation");
3515
+ return match;
3516
+ }
3517
+ function statePath() {
3518
+ return paths.updateStateFile;
3519
+ }
3520
+ async function readState() {
3521
+ try {
3522
+ const state = JSON.parse(await readFile7(statePath(), "utf8"));
3523
+ return {
3524
+ ...typeof state?.lastCheckedAt === "string" ? { lastCheckedAt: state.lastCheckedAt } : {},
3525
+ ...typeof state?.lastNotifiedVersion === "string" ? { lastNotifiedVersion: state.lastNotifiedVersion } : {}
3526
+ };
3527
+ } catch {
3528
+ return {};
3529
+ }
3530
+ }
3531
+ async function writeState(state) {
3532
+ try {
3533
+ await writeFileAtomic(statePath(), `${JSON.stringify(state, null, 2)}
3534
+ `, { mode: 384 });
3535
+ } catch {
3536
+ }
3537
+ }
3538
+
3539
+ // src/cli/commands/listen-client.ts
3540
+ var ListenApiError = class extends Error {
3541
+ constructor(message, status) {
3542
+ super(message);
3543
+ this.status = status;
3544
+ }
3545
+ status;
3546
+ };
3547
+ function apiUrl(sidecar, path4) {
3548
+ const url = new URL(sidecar.url);
3549
+ url.pathname = path4;
3550
+ url.search = "";
3551
+ url.searchParams.set("token", sidecar.token);
3552
+ return url.toString();
3553
+ }
3554
+ function errorMessage(parsed, fallback) {
3555
+ if (parsed && typeof parsed === "object" && "error" in parsed) {
3556
+ const error = parsed.error;
3557
+ if (typeof error === "string" && error.trim()) return error;
3558
+ }
3559
+ return fallback;
3209
3560
  }
3210
-
3211
- // src/daemon/service-adapter.ts
3212
- function makeLaunchdAdapter(profile2, runArgs) {
3213
- return {
3214
- platformName: "launchd (macOS)",
3215
- fileExists: () => plistExists(profile2),
3216
- isRunning: () => isLoaded(profile2),
3217
- servicePath: () => launchAgentPlistPath(profile2),
3218
- install: () => writePlist(profile2, runArgs),
3219
- // A previous `stop` may have left the job disabled in launchd's override
3220
- // DB, where it would stay dead through bootstrap. Always enable first.
3221
- start: () => {
3222
- enable(profile2);
3223
- return bootstrap(profile2);
3224
- },
3225
- stop: () => bootout(profile2),
3226
- // bootout alone is session-scoped: the plist keeps RunAtLoad=true, so
3227
- // launchd re-bootstraps the job at the next login. Pair it with an
3228
- // explicit `disable` to actually match systemd's `disable --now`.
3229
- stopAndDisableAutostart: () => {
3230
- const out = bootout(profile2);
3231
- const disabled = disable(profile2);
3232
- return out.ok ? disabled : out;
3561
+ async function postJson(sidecar, path4, body) {
3562
+ const response = await fetch(apiUrl(sidecar, path4), {
3563
+ method: "POST",
3564
+ headers: {
3565
+ "content-type": "application/json",
3566
+ "x-ui-token": sidecar.token
3233
3567
  },
3234
- disableAutostart: () => disable(profile2),
3235
- restart: () => kickstart(profile2),
3236
- waitUntilStopped: (timeoutMs) => waitUntilUnloaded(profile2, timeoutMs),
3237
- deleteFile: () => deletePlist(profile2),
3238
- describeStatus: () => describeService(profile2),
3239
- parseStatus: (text2) => ({
3240
- pid: text2.match(/pid\s*=\s*(\d+)/)?.[1],
3241
- lastExit: text2.match(/last exit code\s*=\s*(-?\d+)/i)?.[1]
3242
- })
3243
- };
3568
+ body: JSON.stringify(body)
3569
+ });
3570
+ const text2 = await response.text();
3571
+ let parsed = {};
3572
+ if (text2) {
3573
+ try {
3574
+ parsed = JSON.parse(text2);
3575
+ } catch {
3576
+ parsed = { error: text2 };
3577
+ }
3578
+ }
3579
+ if (!response.ok) {
3580
+ throw new ListenApiError(errorMessage(parsed, `HTTP ${response.status}`), response.status);
3581
+ }
3582
+ return parsed;
3244
3583
  }
3245
- function makeSystemdAdapter(profile2, runArgs) {
3246
- return {
3247
- platformName: "systemd (Linux user)",
3248
- fileExists: () => unitExists(profile2),
3249
- isRunning: () => isActive(profile2),
3250
- servicePath: () => systemdUnitPath(profile2),
3251
- install: async () => {
3252
- await writeUnit(profile2, runArgs);
3253
- daemonReload();
3254
- },
3255
- start: () => enableAndStart(profile2),
3256
- stop: () => stop(profile2),
3257
- stopAndDisableAutostart: () => disableAndStop(profile2),
3258
- disableAutostart: () => disable2(profile2),
3259
- restart: () => restart(profile2),
3260
- waitUntilStopped: (timeoutMs) => waitUntilInactive(profile2, timeoutMs),
3261
- deleteFile: async () => {
3262
- await deleteUnit(profile2);
3263
- daemonReload();
3264
- },
3265
- describeStatus: () => describeService2(profile2),
3266
- // `systemctl status` includes a "Main PID:" line and an "Active:"
3267
- // line. There's no single "last exit code" field in the standard
3268
- // output but the "Process: <pid> ExecStart=... status=<n>" line on
3269
- // an inactive service exposes it.
3270
- parseStatus: (text2) => ({
3271
- pid: text2.match(/Main PID:\s*(\d+)/)?.[1],
3272
- lastExit: text2.match(/Process:\s+\d+\s+ExecStart=.*status=(\d+)/)?.[1]
3273
- })
3274
- };
3584
+ async function joinListenProfile(sidecar, profile2) {
3585
+ await postJson(sidecar, "/api/profiles/start", { profile: profile2 });
3275
3586
  }
3276
- function makeSchtasksAdapter(profile2, runArgs) {
3277
- return {
3278
- platformName: "Task Scheduler (Windows)",
3279
- fileExists: () => isTaskRegistered(profile2),
3280
- isRunning: () => isTaskRunning(profile2),
3281
- // Windows doesn't have a single "service file" — there's the task
3282
- // registration (queryable via schtasks) and the hidden launcher we wrote.
3283
- // The task name is what the user would search for in Task Scheduler UI.
3284
- servicePath: () => windowsTaskName(profile2),
3285
- install: async () => {
3286
- const r = await installTask(profile2, runArgs);
3287
- if (!r.ok) throw new Error(r.stderr || "schtasks /Create failed");
3288
- },
3289
- // Mirror launchd: a previous `stop` disabled the task, and a disabled
3290
- // task refuses to run. Re-enable before starting it.
3291
- start: () => {
3292
- enableTask(profile2);
3293
- return runTask(profile2);
3294
- },
3295
- stop: () => endTask(profile2),
3296
- stopAndDisableAutostart: () => endAndDisable(profile2),
3297
- disableAutostart: () => disableTask(profile2),
3298
- // schtasks has no native /Restart — adapter awaits end+wait+run.
3299
- restart: () => restartTask(profile2),
3300
- waitUntilStopped: (timeoutMs) => waitUntilStopped(profile2, timeoutMs),
3301
- deleteFile: async () => {
3302
- await deleteTask(profile2);
3303
- },
3304
- describeStatus: () => describeTask(profile2),
3305
- parseStatus: (text2) => {
3306
- const parsed = parseTaskListFields(text2);
3307
- return { pid: parsed.pid, lastExit: parsed.lastExit };
3308
- }
3309
- };
3587
+ async function leaveListenProfile(sidecar, profile2) {
3588
+ await postJson(sidecar, "/api/profiles/stop", { profile: profile2 });
3310
3589
  }
3311
- function getServiceAdapter(profile2 = "claude", runArgs = ["run"]) {
3312
- if (process.platform === "darwin") return makeLaunchdAdapter(profile2, runArgs);
3313
- if (process.platform === "linux") return makeSystemdAdapter(profile2, runArgs);
3314
- if (process.platform === "win32") return makeSchtasksAdapter(profile2, runArgs);
3315
- return null;
3590
+ async function listListenBots(sidecar) {
3591
+ const response = await fetch(apiUrl(sidecar, "/api/bots"), {
3592
+ headers: { "x-ui-token": sidecar.token }
3593
+ });
3594
+ if (!response.ok) throw new ListenApiError(`HTTP ${response.status}`, response.status);
3595
+ const parsed = await response.json();
3596
+ if (!parsed || typeof parsed !== "object" || !("bots" in parsed) || !Array.isArray(parsed.bots)) {
3597
+ return [];
3598
+ }
3599
+ const names = [];
3600
+ for (const bot of parsed.bots) {
3601
+ if (bot && typeof bot === "object" && "profileName" in bot && typeof bot.profileName === "string") {
3602
+ names.push({ profileName: bot.profileName });
3603
+ }
3604
+ }
3605
+ return names;
3316
3606
  }
3317
3607
 
3318
3608
  // src/cli/commands/ps.ts
@@ -3479,7 +3769,7 @@ function padEndDisplay(s, target) {
3479
3769
 
3480
3770
  // src/config/keystore.ts
3481
3771
  import { createCipheriv, createDecipheriv, pbkdf2Sync, randomBytes as randomBytes3 } from "crypto";
3482
- import { readFile as readFile6 } from "fs/promises";
3772
+ import { readFile as readFile8 } from "fs/promises";
3483
3773
  import { hostname, userInfo as userInfo2 } from "os";
3484
3774
  var KEY_LEN = 32;
3485
3775
  var IV_LEN = 12;
@@ -3489,7 +3779,7 @@ var FILE_VERSION = 1;
3489
3779
  var derivedKeyCache = /* @__PURE__ */ new Map();
3490
3780
  async function readStore(storePaths = paths) {
3491
3781
  try {
3492
- const text2 = await readFile6(storePaths.secretsFile, "utf8");
3782
+ const text2 = await readFile8(storePaths.secretsFile, "utf8");
3493
3783
  const parsed = JSON.parse(text2);
3494
3784
  if (parsed?.version !== FILE_VERSION || !parsed.entries) return emptyStore();
3495
3785
  return { version: parsed.version, entries: { ...parsed.entries } };
@@ -3509,7 +3799,7 @@ async function writeStore(store, storePaths = paths) {
3509
3799
  }
3510
3800
  async function loadOrCreateSalt(storePaths = paths) {
3511
3801
  try {
3512
- const buf = await readFile6(storePaths.keystoreSaltFile);
3802
+ const buf = await readFile8(storePaths.keystoreSaltFile);
3513
3803
  if (buf.length === KEY_LEN) return buf;
3514
3804
  } catch (err) {
3515
3805
  if (err.code !== "ENOENT") throw err;
@@ -3577,12 +3867,12 @@ async function listSecretIds(storePaths = paths) {
3577
3867
  }
3578
3868
 
3579
3869
  // src/config/profile-store.ts
3580
- import { chmod as chmod3, mkdir as mkdir10, readFile as readFile7, rename as rename2, rm as rm9, rmdir, stat as stat2, writeFile as writeFile7 } from "fs/promises";
3581
- import { dirname as dirname11, join as join8 } from "path";
3870
+ import { chmod as chmod3, mkdir as mkdir12, readFile as readFile9, rename as rename2, rm as rm11, rmdir, stat as stat2, writeFile as writeFile7 } from "fs/promises";
3871
+ import { dirname as dirname12, join as join10 } from "path";
3582
3872
  import * as lockfile4 from "proper-lockfile";
3583
3873
  async function loadRootConfig(path4) {
3584
3874
  try {
3585
- const parsed = JSON.parse(await readFile7(path4, "utf8"));
3875
+ const parsed = JSON.parse(await readFile9(path4, "utf8"));
3586
3876
  return isRootConfig(parsed) ? normalizeRootConfig(parsed) : void 0;
3587
3877
  } catch (err) {
3588
3878
  if (err.code === "ENOENT") return void 0;
@@ -3650,7 +3940,7 @@ function serializeProfileConfig(profile2) {
3650
3940
  }
3651
3941
  async function withConfigFileLock(configPath, fn) {
3652
3942
  const lockTarget = `${configPath}.lock`;
3653
- await mkdir10(dirname11(lockTarget), { recursive: true });
3943
+ await mkdir12(dirname12(lockTarget), { recursive: true });
3654
3944
  await writeFile7(lockTarget, "", { flag: "a", mode: 384 });
3655
3945
  await chmod3(lockTarget, 384).catch(() => {
3656
3946
  });
@@ -3671,12 +3961,12 @@ async function withConfigFileLock(configPath, fn) {
3671
3961
  }
3672
3962
  }
3673
3963
  async function readActiveProfile(rootDir) {
3674
- const activeProfileFile = join8(
3964
+ const activeProfileFile = join10(
3675
3965
  rootDir ?? process.env.XIAOJIU_BRIDGE_HOME ?? resolveAppPaths().rootDir,
3676
3966
  "active-profile"
3677
3967
  );
3678
3968
  try {
3679
- const text2 = await readFile7(activeProfileFile, "utf8");
3969
+ const text2 = await readFile9(activeProfileFile, "utf8");
3680
3970
  const profile2 = text2.trim();
3681
3971
  return profile2 || void 0;
3682
3972
  } catch (err) {
@@ -3685,7 +3975,7 @@ async function readActiveProfile(rootDir) {
3685
3975
  }
3686
3976
  }
3687
3977
  async function writeActiveProfile(rootDir, profile2) {
3688
- const activeProfileFile = join8(rootDir, "active-profile");
3978
+ const activeProfileFile = join10(rootDir, "active-profile");
3689
3979
  await writeFileAtomic(activeProfileFile, `${profile2}
3690
3980
  `, { mode: 384 });
3691
3981
  }
@@ -3760,8 +4050,8 @@ async function removeProfile(root, profile2, rootDir, opts = {}) {
3760
4050
  const profileDir = resolveAppPaths({ rootDir, profile: profile2 }).profileDir;
3761
4051
  if (opts.purge) {
3762
4052
  if (!await pathExists(profileDir)) return { root: next, purged: true };
3763
- const trashDir2 = join8(rootDir, ".trash");
3764
- await mkdir10(trashDir2, { recursive: true });
4053
+ const trashDir2 = join10(rootDir, ".trash");
4054
+ await mkdir12(trashDir2, { recursive: true });
3765
4055
  const stagedTo = await nextArchivePath(trashDir2, profile2, opts.now?.() ?? /* @__PURE__ */ new Date());
3766
4056
  await rename2(profileDir, stagedTo);
3767
4057
  return {
@@ -3772,14 +4062,14 @@ async function removeProfile(root, profile2, rootDir, opts = {}) {
3772
4062
  await rename2(stagedTo, profileDir);
3773
4063
  },
3774
4064
  cleanup: async () => {
3775
- await rm9(stagedTo, { recursive: true, force: true });
4065
+ await rm11(stagedTo, { recursive: true, force: true });
3776
4066
  await rmdir(trashDir2).catch(() => {
3777
4067
  });
3778
4068
  }
3779
4069
  };
3780
4070
  }
3781
- const trashDir = join8(rootDir, ".trash");
3782
- await mkdir10(trashDir, { recursive: true });
4071
+ const trashDir = join10(rootDir, ".trash");
4072
+ await mkdir12(trashDir, { recursive: true });
3783
4073
  const archivedTo = await nextArchivePath(trashDir, profile2, opts.now?.() ?? /* @__PURE__ */ new Date());
3784
4074
  await rename2(profileDir, archivedTo);
3785
4075
  return {
@@ -3791,7 +4081,7 @@ async function removeProfile(root, profile2, rootDir, opts = {}) {
3791
4081
  };
3792
4082
  }
3793
4083
  async function nextArchivePath(trashDir, profile2, now) {
3794
- const base = join8(trashDir, `${profile2}-${archiveTimestamp(now)}`);
4084
+ const base = join10(trashDir, `${profile2}-${archiveTimestamp(now)}`);
3795
4085
  for (let suffix = 0; ; suffix++) {
3796
4086
  const candidate = suffix === 0 ? base : `${base}-${suffix}`;
3797
4087
  if (!await pathExists(candidate)) return candidate;
@@ -3816,8 +4106,8 @@ function agentKindFromString(value) {
3816
4106
  }
3817
4107
 
3818
4108
  // src/runtime/profile-discovery.ts
3819
- import { readdir as readdir4 } from "fs/promises";
3820
- import { join as join9 } from "path";
4109
+ import { readdir as readdir5 } from "fs/promises";
4110
+ import { join as join11 } from "path";
3821
4111
  async function listAllProfiles(rootDir) {
3822
4112
  const rootPaths = resolveAppPaths({ rootDir });
3823
4113
  const root = await loadRootConfig(rootPaths.configFile);
@@ -3855,9 +4145,9 @@ async function listAllProfiles(rootDir) {
3855
4145
  });
3856
4146
  }
3857
4147
  async function readProfileStateDirs(rootDir) {
3858
- const profilesDir = join9(rootDir, "profiles");
4148
+ const profilesDir = join11(rootDir, "profiles");
3859
4149
  try {
3860
- const entries = await readdir4(profilesDir, { withFileTypes: true });
4150
+ const entries = await readdir5(profilesDir, { withFileTypes: true });
3861
4151
  return entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name);
3862
4152
  } catch (err) {
3863
4153
  if (err.code === "ENOENT") return [];
@@ -3866,7 +4156,7 @@ async function readProfileStateDirs(rootDir) {
3866
4156
  }
3867
4157
  async function isLogOnlyProfileState(rootDir, profile2) {
3868
4158
  try {
3869
- const entries = await readdir4(join9(rootDir, "profiles", profile2), { withFileTypes: true });
4159
+ const entries = await readdir5(join11(rootDir, "profiles", profile2), { withFileTypes: true });
3870
4160
  return entries.length === 1 && entries[0]?.isDirectory() === true && entries[0].name === "logs";
3871
4161
  } catch {
3872
4162
  return false;
@@ -4036,11 +4326,11 @@ async function readAllStdin() {
4036
4326
 
4037
4327
  // src/cli/commands/profile.ts
4038
4328
  import { existsSync as existsSync8 } from "fs";
4039
- import { rm as rm10 } from "fs/promises";
4329
+ import { rm as rm12 } from "fs/promises";
4040
4330
 
4041
4331
  // src/config/secret-resolver.ts
4042
- import { readFile as readFile8 } from "fs/promises";
4043
- import { join as join10, resolve as resolve2 } from "path";
4332
+ import { readFile as readFile10 } from "fs/promises";
4333
+ import { join as join12, resolve as resolve2 } from "path";
4044
4334
  var ENV_TEMPLATE_RE = /^\$\{([A-Z][A-Z0-9_]{0,127})\}$/;
4045
4335
  var DEFAULT_PROVIDER = "default";
4046
4336
  var DEFAULT_EXEC_TIMEOUT_MS = 5e3;
@@ -4096,8 +4386,8 @@ function resolveEnvRef(ref, pc) {
4096
4386
  return v;
4097
4387
  }
4098
4388
  async function resolveFileRef(ref, pc) {
4099
- const path4 = pc?.path ? join10(pc.path, ref.id) : ref.id;
4100
- const text2 = await readFile8(path4, "utf8");
4389
+ const path4 = pc?.path ? join12(pc.path, ref.id) : ref.id;
4390
+ const text2 = await readFile10(path4, "utf8");
4101
4391
  return text2.trim();
4102
4392
  }
4103
4393
  async function resolveExecRef(ref, pc, appId, secretPaths) {
@@ -4213,14 +4503,14 @@ async function spawnExecProvider(pc, ref) {
4213
4503
  }
4214
4504
 
4215
4505
  // src/runtime/profile-runtime.ts
4216
- import { mkdir as mkdir12, realpath as realpath4 } from "fs/promises";
4217
- import { dirname as dirname14 } from "path";
4506
+ import { mkdir as mkdir14, realpath as realpath4 } from "fs/promises";
4507
+ import { dirname as dirname15 } from "path";
4218
4508
  import * as p2 from "@clack/prompts";
4219
4509
 
4220
4510
  // src/cli/agent-detection.ts
4221
4511
  import { constants } from "fs";
4222
4512
  import { access } from "fs/promises";
4223
- import { delimiter, extname, isAbsolute, join as join11 } from "path";
4513
+ import { delimiter, extname, isAbsolute, join as join13 } from "path";
4224
4514
  async function resolveExecutablePath(command) {
4225
4515
  if (isAbsolute(command)) {
4226
4516
  await access(command, constants.X_OK);
@@ -4239,10 +4529,10 @@ async function resolveExecutablePath(command) {
4239
4529
  throw new Error(`executable not found: ${command}`);
4240
4530
  }
4241
4531
  function executableCandidates(dir, command) {
4242
- const candidates = [join11(dir, command)];
4532
+ const candidates = [join13(dir, command)];
4243
4533
  if (extname(command)) return candidates;
4244
4534
  for (const ext of pathExts()) {
4245
- candidates.push(join11(dir, `${command}${ext}`));
4535
+ candidates.push(join13(dir, `${command}${ext}`));
4246
4536
  }
4247
4537
  return candidates;
4248
4538
  }
@@ -4271,13 +4561,13 @@ async function detectInstalledAgents() {
4271
4561
  }
4272
4562
 
4273
4563
  // src/cli/profile-bootstrap.ts
4274
- import { mkdir as mkdir11, realpath as realpath3 } from "fs/promises";
4275
- import { join as join12 } from "path";
4564
+ import { mkdir as mkdir13, realpath as realpath3 } from "fs/promises";
4565
+ import { join as join14 } from "path";
4276
4566
 
4277
4567
  // src/policy/workspace.ts
4278
4568
  import { realpath as realpath2, stat as stat3 } from "fs/promises";
4279
- import { homedir as homedir3, tmpdir } from "os";
4280
- import { basename as basename3, dirname as dirname12, resolve as resolve3 } from "path";
4569
+ import { homedir as homedir3, tmpdir as tmpdir2 } from "os";
4570
+ import { basename as basename3, dirname as dirname13, resolve as resolve3 } from "path";
4281
4571
  async function resolveWorkingDirectory(requestedCwd) {
4282
4572
  const trimmed = requestedCwd.trim();
4283
4573
  if (!trimmed) {
@@ -4293,7 +4583,7 @@ async function resolveWorkingDirectory(requestedCwd) {
4293
4583
  if (!info?.isDirectory()) {
4294
4584
  return reject("not-directory", requestedCwd, `\u8DEF\u5F84\u4E0D\u662F\u76EE\u5F55\uFF1A${resolved}`);
4295
4585
  }
4296
- const tempRealpath = await realpath2(tmpdir()).catch(() => resolve3(tmpdir()));
4586
+ const tempRealpath = await realpath2(tmpdir2()).catch(() => resolve3(tmpdir2()));
4297
4587
  const homeRealpath = await realpath2(homedir3()).catch(() => resolve3(homedir3()));
4298
4588
  const broad = classifyHighRiskWorkingDirectory(resolved, requestedCwd, tempRealpath, homeRealpath);
4299
4589
  if (broad) return broad;
@@ -4307,20 +4597,20 @@ function reject(reason, requestedCwd, userVisible) {
4307
4597
  return { ok: false, reason, requestedCwd, userVisible };
4308
4598
  }
4309
4599
  function classifyHighRiskWorkingDirectory(real, requestedCwd, tempRealpath, homeRealpath) {
4310
- if (real === dirname12(real)) {
4600
+ if (real === dirname13(real)) {
4311
4601
  return reject("filesystem-root", requestedCwd, "\u4E0D\u80FD\u628A\u6587\u4EF6\u7CFB\u7EDF\u6839\u76EE\u5F55\u8BBE\u4E3A\u5DE5\u4F5C\u76EE\u5F55\u3002");
4312
4602
  }
4313
4603
  const home = homeRealpath;
4314
4604
  if (real === home) {
4315
4605
  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");
4316
4606
  }
4317
- if (real === dirname12(home)) {
4607
+ if (real === dirname13(home)) {
4318
4608
  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");
4319
4609
  }
4320
- if (dirname12(real) === home && (/* @__PURE__ */ new Set(["Desktop", "Downloads"])).has(basename3(real))) {
4610
+ if (dirname13(real) === home && (/* @__PURE__ */ new Set(["Desktop", "Downloads"])).has(basename3(real))) {
4321
4611
  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");
4322
4612
  }
4323
- const temp = resolve3(tmpdir());
4613
+ const temp = resolve3(tmpdir2());
4324
4614
  if (real === temp || real === tempRealpath || real === "/tmp" || real === "/private/tmp") {
4325
4615
  return reject("temp-root", requestedCwd, "\u4E0D\u80FD\u628A\u4E34\u65F6\u76EE\u5F55\u6839\u8BBE\u4E3A\u5DE5\u4F5C\u76EE\u5F55\uFF0C\u8BF7\u9009\u62E9\u66F4\u5177\u4F53\u7684\u5B50\u76EE\u5F55\u3002");
4326
4616
  }
@@ -4338,7 +4628,7 @@ function classifyHighRiskWorkingDirectory(real, requestedCwd, tempRealpath, home
4338
4628
  if (systemRoots.has(real)) {
4339
4629
  return reject("system-root", requestedCwd, "\u4E0D\u80FD\u628A\u7CFB\u7EDF\u76EE\u5F55\u8BBE\u4E3A\u5DE5\u4F5C\u76EE\u5F55\u3002");
4340
4630
  }
4341
- if (real === "/Volumes" || dirname12(real) === "/Volumes") {
4631
+ if (real === "/Volumes" || dirname13(real) === "/Volumes") {
4342
4632
  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");
4343
4633
  }
4344
4634
  return void 0;
@@ -4368,7 +4658,7 @@ async function createBootstrapProfileConfig(input) {
4368
4658
  };
4369
4659
  }
4370
4660
  if (input.profileDir && profile2.codex?.inheritCodexHome === false) {
4371
- await mkdir11(join12(input.profileDir, "codex-home"), { recursive: true });
4661
+ await mkdir13(join14(input.profileDir, "codex-home"), { recursive: true });
4372
4662
  }
4373
4663
  return profile2;
4374
4664
  }
@@ -4378,7 +4668,7 @@ async function resolveBootstrapWorkspace(workspace) {
4378
4668
  return resolved.cwdRealpath;
4379
4669
  }
4380
4670
  async function ensureManagedDefaultWorkspace(path4) {
4381
- await mkdir11(path4, { recursive: true, mode: 448 });
4671
+ await mkdir13(path4, { recursive: true, mode: 448 });
4382
4672
  return realpath3(path4);
4383
4673
  }
4384
4674
  async function createBootstrapCodexConfig(binaryPath) {
@@ -4590,11 +4880,11 @@ function cancel2() {
4590
4880
  }
4591
4881
 
4592
4882
  // src/config/store.ts
4593
- import { readFile as readFile9 } from "fs/promises";
4594
- import { dirname as dirname13, resolve as resolve4 } from "path";
4883
+ import { readFile as readFile11 } from "fs/promises";
4884
+ import { dirname as dirname14, resolve as resolve4 } from "path";
4595
4885
  async function loadConfig(path4 = paths.configFile) {
4596
4886
  try {
4597
- const text2 = await readFile9(path4, "utf8");
4887
+ const text2 = await readFile11(path4, "utf8");
4598
4888
  return JSON.parse(text2);
4599
4889
  } catch (err) {
4600
4890
  if (err.code === "ENOENT") return {};
@@ -4636,7 +4926,7 @@ async function ensureSecretsGetterWrapper(appPaths2 = paths, opts = {}) {
4636
4926
  const node = opts.nodePath ?? process.execPath;
4637
4927
  const bridgeEntry = opts.bridgeEntry ?? resolveDaemonEntryPath(process.argv[1]);
4638
4928
  const quotedBridgeEntry = platform2 === "win32" ? bridgeEntry : resolveDaemonEntryPath(bridgeEntry);
4639
- const rootDir = resolve4(appPaths2.rootDir ?? dirname13(appPaths2.secretsGetterScript));
4929
+ const rootDir = resolve4(appPaths2.rootDir ?? dirname14(appPaths2.secretsGetterScript));
4640
4930
  if (platform2 === "win32") {
4641
4931
  const dq = (s) => `"${s.replace(/"/g, '""')}"`;
4642
4932
  const content2 = `@echo off\r
@@ -5194,7 +5484,7 @@ function createRuntimeProfileConfig(input) {
5194
5484
  });
5195
5485
  }
5196
5486
  async function resolveProfileRuntime(opts) {
5197
- const rootDir = opts.config ? dirname14(opts.config) : void 0;
5487
+ const rootDir = opts.config ? dirname15(opts.config) : void 0;
5198
5488
  const requestedAgent = agentKindFromString(opts.agent);
5199
5489
  const explicitProfile = opts.profile;
5200
5490
  const activeProfile = explicitProfile ?? await readActiveProfile(rootDir);
@@ -5458,7 +5748,7 @@ async function ensureProfileDefaultWorkspace(rootConfig, profile2, appPaths2) {
5458
5748
  if (!profileConfig || profileConfig.workspaces.default) {
5459
5749
  return { rootConfig, changed: false };
5460
5750
  }
5461
- await mkdir12(appPaths2.defaultWorkspaceDir, { recursive: true, mode: 448 });
5751
+ await mkdir14(appPaths2.defaultWorkspaceDir, { recursive: true, mode: 448 });
5462
5752
  const defaultWorkspace = await realpath4(appPaths2.defaultWorkspaceDir);
5463
5753
  const nextProfile = {
5464
5754
  ...profileConfig,
@@ -5480,7 +5770,7 @@ async function ensureProfileDefaultWorkspace(rootConfig, profile2, appPaths2) {
5480
5770
  }
5481
5771
  async function resolveConvertedLegacyDefaultWorkspace(opts, appPaths2) {
5482
5772
  if (opts.workspace) return resolveBootstrapWorkspace(opts.workspace);
5483
- await mkdir12(appPaths2.defaultWorkspaceDir, { recursive: true, mode: 448 });
5773
+ await mkdir14(appPaths2.defaultWorkspaceDir, { recursive: true, mode: 448 });
5484
5774
  return realpath4(appPaths2.defaultWorkspaceDir);
5485
5775
  }
5486
5776
  function resolveBootstrapAgent(requestedAgent, profile2) {
@@ -5594,7 +5884,7 @@ function assertBootstrapAppMatchesExistingConfig(opts, profile2, cfg) {
5594
5884
  );
5595
5885
  }
5596
5886
  async function materializeEnvSecretForService(opts = {}) {
5597
- const rootDir = opts.config ? dirname14(opts.config) : void 0;
5887
+ const rootDir = opts.config ? dirname15(opts.config) : void 0;
5598
5888
  const explicitProfile = opts.profile;
5599
5889
  const activeProfile = explicitProfile ?? await readActiveProfile(rootDir);
5600
5890
  let profile2 = activeProfile ?? "claude";
@@ -5937,8 +6227,8 @@ async function runProfileRemove(name, opts = {}) {
5937
6227
  });
5938
6228
  try {
5939
6229
  if (Object.keys(result.root.profiles).length === 0) {
5940
- await rm10(configFile, { force: true });
5941
- await rm10(resolveAppPaths({ rootDir }).activeProfileFile, { force: true });
6230
+ await rm12(configFile, { force: true });
6231
+ await rm12(resolveAppPaths({ rootDir }).activeProfileFile, { force: true });
5942
6232
  } else {
5943
6233
  await saveRootConfig(result.root, configFile);
5944
6234
  await writeActiveProfile(rootDir, result.root.activeProfile);
@@ -6014,6 +6304,63 @@ function cloneJson(value) {
6014
6304
  return JSON.parse(JSON.stringify(value));
6015
6305
  }
6016
6306
 
6307
+ // src/selfupdate/runtime.ts
6308
+ import { existsSync as existsSync9, readFileSync as readFileSync3, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "fs";
6309
+ import { copyFile, mkdir as mkdir15 } from "fs/promises";
6310
+ import { dirname as dirname16 } from "path";
6311
+ import { fileURLToPath as fileURLToPath3 } from "url";
6312
+
6313
+ // src/selfupdate/protocol.ts
6314
+ var SWITCH_EXIT_CODE = 75;
6315
+ var ENV_LAUNCHER = "XIAOJIU_BRIDGE_LAUNCHER";
6316
+ var ENV_BOOT_FILE = "XIAOJIU_BRIDGE_BOOT_FILE";
6317
+
6318
+ // src/selfupdate/runtime.ts
6319
+ function isUnderLauncher(env = process.env) {
6320
+ return env[ENV_LAUNCHER] === "1";
6321
+ }
6322
+ function markBootReady(env = process.env) {
6323
+ const file = env[ENV_BOOT_FILE];
6324
+ if (!file) return;
6325
+ try {
6326
+ const parsed = JSON.parse(readFileSync3(file, "utf8"));
6327
+ if (typeof parsed !== "object" || parsed === null) return;
6328
+ const tmp = `${file}.ready-${process.pid}`;
6329
+ writeFileSync2(tmp, `${JSON.stringify({ ...parsed, ready: true }, null, 2)}
6330
+ `, { mode: 384 });
6331
+ renameSync2(tmp, file);
6332
+ } catch {
6333
+ }
6334
+ }
6335
+ async function ensureLauncherFresh(layout, bundledLauncherFile = defaultBundledLauncher()) {
6336
+ if (!existsSync9(bundledLauncherFile)) return false;
6337
+ const bundled = readFileSync3(bundledLauncherFile);
6338
+ try {
6339
+ if (readFileSync3(layout.launcherFile).equals(bundled)) return true;
6340
+ } catch {
6341
+ }
6342
+ await mkdir15(dirname16(layout.launcherFile), { recursive: true });
6343
+ await copyFile(bundledLauncherFile, layout.launcherFile);
6344
+ return true;
6345
+ }
6346
+ async function prepareLauncherInstall(layout, runningVersion, deps = {}) {
6347
+ const existing = await readCurrent(layout);
6348
+ if (existing && await ensureLauncherFresh(layout)) return existing;
6349
+ const staged = await (deps.stage ?? stageVersion)({ layout, targetVersion: runningVersion });
6350
+ if (!staged.ok) throw new Error(`failed to seed versions store: ${staged.error}`);
6351
+ if (!existing) {
6352
+ await writeCurrent(layout, { version: runningVersion, dir: staged.dir });
6353
+ }
6354
+ const ok = await ensureLauncherFresh(layout);
6355
+ if (!ok) throw new Error("bundled dist/launcher.js not found; cannot adopt launcher mode");
6356
+ const pointer = await readCurrent(layout);
6357
+ if (!pointer) throw new Error("version pointer missing after seeding");
6358
+ return pointer;
6359
+ }
6360
+ function defaultBundledLauncher() {
6361
+ return fileURLToPath3(new URL("./launcher.js", import.meta.url));
6362
+ }
6363
+
6017
6364
  // src/cli/commands/service.ts
6018
6365
  function listenServiceId(port) {
6019
6366
  return `port-${port}`;
@@ -6049,8 +6396,8 @@ async function waitForProfileEntry(profile2, timeoutMs = 2e3) {
6049
6396
  await new Promise((r) => setTimeout(r, 100));
6050
6397
  }
6051
6398
  }
6052
- function requireAdapter(cmdName, serviceId, runArgs) {
6053
- const adapter = getServiceAdapter(serviceId, runArgs);
6399
+ function requireAdapter(cmdName, serviceId, runArgs, launch) {
6400
+ const adapter = getServiceAdapter(serviceId, runArgs ?? ["run"], launch);
6054
6401
  if (!adapter) {
6055
6402
  console.error(
6056
6403
  `${cmdName}: \u5F53\u524D\u7CFB\u7EDF\u4E0D\u652F\u6301\u540E\u53F0\u8FD0\u884C\u3002`
@@ -6060,6 +6407,19 @@ function requireAdapter(cmdName, serviceId, runArgs) {
6060
6407
  }
6061
6408
  return adapter;
6062
6409
  }
6410
+ async function tryLauncherLaunchSpec(rootDir) {
6411
+ try {
6412
+ const installation = await resolveUpdateInstallation({ name: packageName });
6413
+ if (installation.kind !== "global") return void 0;
6414
+ const layout = updateLayout(rootDir);
6415
+ await prepareLauncherInstall(layout, version);
6416
+ log.info("service", "launcher-adopted", { version, launcher: layout.launcherFile });
6417
+ return { importArgs: [], entryPath: layout.launcherFile };
6418
+ } catch (err) {
6419
+ log.warn("service", "launcher-adopt-failed", { err: err instanceof Error ? err.message : String(err) });
6420
+ return void 0;
6421
+ }
6422
+ }
6063
6423
  function formatServiceStderr(stderr) {
6064
6424
  return stderr.split("\n").filter((line) => !/re-running the command as root/i.test(line)).join("\n").trim();
6065
6425
  }
@@ -6255,7 +6615,9 @@ async function runServiceStart(opts = {}) {
6255
6615
  return;
6256
6616
  }
6257
6617
  const serviceId = listenServiceId(port);
6258
- const adapter = requireAdapter("start", serviceId, listenRunArgs(profile2, opts.webUi));
6618
+ const runArgs = listenRunArgs(profile2, opts.webUi);
6619
+ const launch = await tryLauncherLaunchSpec(appPaths2.rootDir);
6620
+ const adapter = requireAdapter("start", serviceId, runArgs, launch);
6259
6621
  if (adapter.isRunning()) {
6260
6622
  const stopped = await adapter.stop();
6261
6623
  if (!stopped.ok) {
@@ -6412,14 +6774,14 @@ function agentDisplay(agentKind) {
6412
6774
  // src/cli/commands/start.ts
6413
6775
  import dns from "dns";
6414
6776
  import os from "os";
6415
- import { readdir as readdir8 } from "fs/promises";
6416
- import { join as join23 } from "path";
6777
+ import { readdir as readdir9 } from "fs/promises";
6778
+ import { join as join26 } from "path";
6417
6779
  import { createInterface as createInterface8 } from "readline";
6418
6780
 
6419
6781
  // src/agent/claude/adapter.ts
6420
- import { mkdtempSync, rmSync, writeFileSync as writeFileSync2 } from "fs";
6421
- import { tmpdir as tmpdir2 } from "os";
6422
- import { join as join13 } from "path";
6782
+ import { mkdtempSync, rmSync, writeFileSync as writeFileSync3 } from "fs";
6783
+ import { tmpdir as tmpdir3 } from "os";
6784
+ import { join as join15 } from "path";
6423
6785
  import { createInterface as createInterface3 } from "readline";
6424
6786
 
6425
6787
  // src/agent/system-prompt.ts
@@ -7015,9 +7377,9 @@ async function* createEventStream(child, stderrChunks, getError) {
7015
7377
  }
7016
7378
  }
7017
7379
  function writeSystemPromptFile(content) {
7018
- const dir = mkdtempSync(join13(tmpdir2(), "xiaojiu-claude-"));
7019
- const path4 = join13(dir, "append-system-prompt.md");
7020
- writeFileSync2(path4, content, "utf8");
7380
+ const dir = mkdtempSync(join15(tmpdir3(), "xiaojiu-claude-"));
7381
+ const path4 = join15(dir, "append-system-prompt.md");
7382
+ writeFileSync3(path4, content, "utf8");
7021
7383
  return {
7022
7384
  path: path4,
7023
7385
  cleanup: () => {
@@ -7034,7 +7396,7 @@ function isWindowsCommandNotFoundLine(line) {
7034
7396
 
7035
7397
  // src/agent/codex/adapter.ts
7036
7398
  import { createInterface as createInterface4 } from "readline";
7037
- import { join as join14 } from "path";
7399
+ import { join as join16 } from "path";
7038
7400
 
7039
7401
  // src/runtime/errors.ts
7040
7402
  var RunRejected = class extends Error {
@@ -7413,7 +7775,7 @@ var CodexAdapter = class {
7413
7775
  if (this.codexHome) {
7414
7776
  envOverrides.CODEX_HOME = this.codexHome;
7415
7777
  } else if (!this.inheritCodexHome) {
7416
- envOverrides.CODEX_HOME = join14(this.profileStateDir, "codex-home");
7778
+ envOverrides.CODEX_HOME = join16(this.profileStateDir, "codex-home");
7417
7779
  }
7418
7780
  const child = spawnProcess(this.binary, args, {
7419
7781
  cwd: opts.cwd,
@@ -7588,13 +7950,13 @@ function isWindowsCommandNotFoundLine2(line) {
7588
7950
  }
7589
7951
 
7590
7952
  // src/bot/channel.ts
7591
- import { dirname as dirname17, join as join21 } from "path";
7953
+ import { dirname as dirname19, join as join23 } from "path";
7592
7954
 
7593
7955
  // src/channel/channel.ts
7594
- import { join as join15 } from "path";
7956
+ import { join as join17 } from "path";
7595
7957
 
7596
7958
  // src/channel/xiaojiu/dedupe-store.ts
7597
- import { readFile as readFile11 } from "fs/promises";
7959
+ import { readFile as readFile13 } from "fs/promises";
7598
7960
  var XIAOJIU_DEDUPE_TTL_MS = 24 * 60 * 60 * 1e3;
7599
7961
  var XiaojiuDedupeStore = class {
7600
7962
  constructor(path4, options = {}) {
@@ -7645,7 +8007,7 @@ var XiaojiuDedupeStore = class {
7645
8007
  if (this.loaded) return;
7646
8008
  let parsed;
7647
8009
  try {
7648
- parsed = JSON.parse(await readFile11(this.path, "utf8"));
8010
+ parsed = JSON.parse(await readFile13(this.path, "utf8"));
7649
8011
  } catch (error) {
7650
8012
  if (error.code === "ENOENT") {
7651
8013
  this.loaded = true;
@@ -8185,7 +8547,7 @@ function formatP2pSessionName(info) {
8185
8547
  }
8186
8548
  function p2pPerson(info) {
8187
8549
  const single = record(info.singleInfo);
8188
- const sources = [
8550
+ const sources2 = [
8189
8551
  record(single?.subUser),
8190
8552
  record(single?.user),
8191
8553
  record(single?.peer),
@@ -8196,7 +8558,7 @@ function p2pPerson(info) {
8196
8558
  info
8197
8559
  ];
8198
8560
  const nested = [];
8199
- for (const source of sources) {
8561
+ for (const source of sources2) {
8200
8562
  if (!source) continue;
8201
8563
  nested.push(
8202
8564
  record(source.userId),
@@ -8205,22 +8567,22 @@ function p2pPerson(info) {
8205
8567
  record(source.subUser)
8206
8568
  );
8207
8569
  }
8208
- const name = firstPersonName([...sources, ...nested]);
8209
- const staffNo = firstStringAcross([...sources, ...nested], STAFF_NO_KEYS);
8570
+ const name = firstPersonName([...sources2, ...nested]);
8571
+ const staffNo = firstStringAcross([...sources2, ...nested], STAFF_NO_KEYS);
8210
8572
  return {
8211
8573
  ...name ? { name } : {},
8212
8574
  ...staffNo ? { staffNo: staffNo.toLowerCase() } : {}
8213
8575
  };
8214
8576
  }
8215
- function firstPersonName(sources) {
8216
- for (const source of sources) {
8577
+ function firstPersonName(sources2) {
8578
+ for (const source of sources2) {
8217
8579
  const found = firstString(source, STAFF_NAME_KEYS);
8218
8580
  if (found && !P2P_LABEL.test(found)) return found;
8219
8581
  }
8220
8582
  return void 0;
8221
8583
  }
8222
- function firstStringAcross(sources, keys) {
8223
- for (const source of sources) {
8584
+ function firstStringAcross(sources2, keys) {
8585
+ for (const source of sources2) {
8224
8586
  const found = firstString(source, keys);
8225
8587
  if (found) return found;
8226
8588
  }
@@ -8300,7 +8662,7 @@ var XiaojiuChannel = class {
8300
8662
  sendMessageApiVersion: options.sendMessageApiVersion
8301
8663
  });
8302
8664
  this.dedupe = new XiaojiuDedupeStore(
8303
- options.dedupeFile ?? join15(process.cwd(), ".xiaojiu-webhook-events.json"),
8665
+ options.dedupeFile ?? join17(process.cwd(), ".xiaojiu-webhook-events.json"),
8304
8666
  options.dedupeTtlMs ? { ttlMs: options.dedupeTtlMs } : {}
8305
8667
  );
8306
8668
  this.throttleMs = Math.max(250, options.streamThrottleMs ?? 250);
@@ -8848,7 +9210,7 @@ function safeJsonStringify(value) {
8848
9210
 
8849
9211
  // src/commands/index.ts
8850
9212
  import { randomUUID } from "crypto";
8851
- import { dirname as dirname16 } from "path";
9213
+ import { dirname as dirname18 } from "path";
8852
9214
 
8853
9215
  // src/commands/mention-text.ts
8854
9216
  function stripMatchedMentions(text2, mentions) {
@@ -9515,7 +9877,7 @@ function deny(reason) {
9515
9877
  }
9516
9878
 
9517
9879
  // src/config/config-ops.ts
9518
- import { dirname as dirname15 } from "path";
9880
+ import { dirname as dirname17 } from "path";
9519
9881
  async function saveAccessConfig(state, mutate) {
9520
9882
  try {
9521
9883
  return await withConfigFileLock(state.configPath, async () => {
@@ -10059,9 +10421,9 @@ function finalizeIfRunning(state) {
10059
10421
 
10060
10422
  // src/session/history.ts
10061
10423
  import { createReadStream } from "fs";
10062
- import { readdir as readdir5, stat as stat4 } from "fs/promises";
10424
+ import { readdir as readdir6, stat as stat4 } from "fs/promises";
10063
10425
  import { homedir as homedir4 } from "os";
10064
- import { join as join16 } from "path";
10426
+ import { join as join18 } from "path";
10065
10427
  import { createInterface as createInterface5 } from "readline";
10066
10428
 
10067
10429
  // src/session/preview.ts
@@ -10100,13 +10462,13 @@ function encodeCwd(cwd) {
10100
10462
  return cwd.replace(/[^A-Za-z0-9]/g, "-");
10101
10463
  }
10102
10464
  function claudeProjectDir(cwd) {
10103
- return join16(homedir4(), ".claude", "projects", encodeCwd(cwd));
10465
+ return join18(homedir4(), ".claude", "projects", encodeCwd(cwd));
10104
10466
  }
10105
10467
  async function listRecentSessions(cwd, limit = 5) {
10106
10468
  const dir = claudeProjectDir(cwd);
10107
10469
  let files;
10108
10470
  try {
10109
- files = await readdir5(dir);
10471
+ files = await readdir6(dir);
10110
10472
  } catch (err) {
10111
10473
  if (err.code === "ENOENT") return [];
10112
10474
  throw err;
@@ -10114,7 +10476,7 @@ async function listRecentSessions(cwd, limit = 5) {
10114
10476
  const jsonls = files.filter((f) => f.endsWith(".jsonl"));
10115
10477
  const withStats = await Promise.all(
10116
10478
  jsonls.map(async (f) => {
10117
- const path4 = join16(dir, f);
10479
+ const path4 = join18(dir, f);
10118
10480
  try {
10119
10481
  const st = await stat4(path4);
10120
10482
  return { file: f, path: path4, mtime: st.mtimeMs };
@@ -10185,7 +10547,7 @@ function formatRelTime(mtime) {
10185
10547
 
10186
10548
  // src/session/codex-history.ts
10187
10549
  import { createInterface as createInterface6 } from "readline";
10188
- import { join as join17 } from "path";
10550
+ import { join as join19 } from "path";
10189
10551
  var CodexHistoryError = class extends Error {
10190
10552
  code;
10191
10553
  constructor(code, message, options) {
@@ -10300,7 +10662,7 @@ function spawnCodexAppServer(options) {
10300
10662
  if (options.codexHome) {
10301
10663
  envOverrides.CODEX_HOME = options.codexHome;
10302
10664
  } else if (options.inheritCodexHome === false) {
10303
- envOverrides.CODEX_HOME = join17(options.profileStateDir, "codex-home");
10665
+ envOverrides.CODEX_HOME = join19(options.profileStateDir, "codex-home");
10304
10666
  }
10305
10667
  return spawnProcess(options.binary, ["app-server", "--listen", "stdio://"], {
10306
10668
  env: mergeProcessEnv(process.env, envOverrides),
@@ -12152,7 +12514,7 @@ async function submitConfig(ctx) {
12152
12514
  }
12153
12515
  function commandProfilePaths(ctx) {
12154
12516
  return resolveAppPaths({
12155
- rootDir: dirname16(ctx.controls.configPath),
12517
+ rootDir: dirname18(ctx.controls.configPath),
12156
12518
  profile: ctx.controls.profile
12157
12519
  });
12158
12520
  }
@@ -12506,7 +12868,7 @@ function signatureMatches(actual, expected) {
12506
12868
  }
12507
12869
 
12508
12870
  // src/card/callback-store.ts
12509
- import { readFile as readFile12 } from "fs/promises";
12871
+ import { readFile as readFile14 } from "fs/promises";
12510
12872
  var CallbackNonceStore = class {
12511
12873
  path;
12512
12874
  nonces = /* @__PURE__ */ new Map();
@@ -12516,7 +12878,7 @@ var CallbackNonceStore = class {
12516
12878
  }
12517
12879
  async load() {
12518
12880
  try {
12519
- const raw = JSON.parse(await readFile12(this.path, "utf8"));
12881
+ const raw = JSON.parse(await readFile14(this.path, "utf8"));
12520
12882
  if (!raw || typeof raw !== "object") return;
12521
12883
  this.nonces.clear();
12522
12884
  for (const [nonce, state] of Object.entries(raw)) {
@@ -12594,8 +12956,8 @@ function footerLine(status) {
12594
12956
  // src/media/cache.ts
12595
12957
  import { createHash as createHash4 } from "crypto";
12596
12958
  import { createReadStream as createReadStream2 } from "fs";
12597
- import { mkdir as mkdir13, open as open2, readdir as readdir6, rename as rename3, rm as rm11, stat as stat5, writeFile as writeFile9 } from "fs/promises";
12598
- import { join as join18 } from "path";
12959
+ import { mkdir as mkdir16, open as open3, readdir as readdir7, rename as rename3, rm as rm13, stat as stat5, writeFile as writeFile9 } from "fs/promises";
12960
+ import { join as join20 } from "path";
12599
12961
 
12600
12962
  // src/media/attachment.ts
12601
12963
  var DEFAULT_POLICY = {
@@ -12701,7 +13063,7 @@ var MediaCache = class {
12701
13063
  }
12702
13064
  async resolve(items, options = {}) {
12703
13065
  if (items.length === 0) return [];
12704
- await mkdir13(this.rootDir, { recursive: true });
13066
+ await mkdir16(this.rootDir, { recursive: true });
12705
13067
  const candidates = [];
12706
13068
  for (const item of items) {
12707
13069
  try {
@@ -12731,7 +13093,7 @@ var MediaCache = class {
12731
13093
  return null;
12732
13094
  }
12733
13095
  const kind = r.type;
12734
- const tmpPath = join18(
13096
+ const tmpPath = join20(
12735
13097
  this.rootDir,
12736
13098
  `.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`
12737
13099
  );
@@ -12758,10 +13120,10 @@ var MediaCache = class {
12758
13120
  const hash = await hashFile(tmpPath);
12759
13121
  const mime = await sniffImageMime(tmpPath) ?? contentType ?? defaultMime(kind);
12760
13122
  const ext = safeExtensionForMime(mime);
12761
- const absPath = join18(this.rootDir, `${hash}.${ext}`);
13123
+ const absPath = join20(this.rootDir, `${hash}.${ext}`);
12762
13124
  try {
12763
13125
  await stat5(absPath);
12764
- await rm11(tmpPath, { force: true });
13126
+ await rm13(tmpPath, { force: true });
12765
13127
  log.info("media", "cache-hit", { path: absPath });
12766
13128
  } catch {
12767
13129
  await rename3(tmpPath, absPath);
@@ -12797,7 +13159,7 @@ function defaultMime(kind) {
12797
13159
  }
12798
13160
  }
12799
13161
  async function sniffImageMime(path4) {
12800
- const handle2 = await open2(path4, "r");
13162
+ const handle2 = await open3(path4, "r");
12801
13163
  try {
12802
13164
  const buf = Buffer.alloc(16);
12803
13165
  const { bytesRead } = await handle2.read(buf, 0, 16, 0);
@@ -12817,9 +13179,9 @@ async function sniffImageMime(path4) {
12817
13179
  }
12818
13180
  async function listFiles(root) {
12819
13181
  const out = [];
12820
- const entries = await readdir6(root, { withFileTypes: true }).catch(() => []);
13182
+ const entries = await readdir7(root, { withFileTypes: true }).catch(() => []);
12821
13183
  for (const entry of entries) {
12822
- const full = join18(root, entry.name);
13184
+ const full = join20(root, entry.name);
12823
13185
  if (entry.isDirectory()) {
12824
13186
  out.push(...await listFiles(full));
12825
13187
  } else if (entry.isFile()) {
@@ -12846,13 +13208,13 @@ async function enforceCacheMaxBytes(root, maxBytes, protectedPaths) {
12846
13208
  let total = files.reduce((sum, file) => sum + file.size, 0);
12847
13209
  for (const file of files.filter((item) => !protectedPaths.has(item.path)).sort((a, b) => a.mtimeMs - b.mtimeMs)) {
12848
13210
  if (total <= maxBytes) break;
12849
- await rm11(file.path, { force: true });
13211
+ await rm13(file.path, { force: true });
12850
13212
  total -= file.size;
12851
13213
  }
12852
13214
  }
12853
13215
  async function removeRejectedResolvedFiles(attachments) {
12854
13216
  await Promise.all(
12855
- attachments.filter((attachment) => attachment.decision !== "accepted").map((attachment) => rm11(attachment.absPath, { force: true }))
13217
+ attachments.filter((attachment) => attachment.decision !== "accepted").map((attachment) => rm13(attachment.absPath, { force: true }))
12856
13218
  );
12857
13219
  }
12858
13220
 
@@ -12977,6 +13339,14 @@ var ActiveRuns = class {
12977
13339
  snapshot() {
12978
13340
  return [...this.handles.values()];
12979
13341
  }
13342
+ /**
13343
+ * Number of in-flight runs plus reserved-but-not-yet-registered scopes.
13344
+ * Used by the auto-update scheduler to find a quiet window: a reservation
13345
+ * means a run is about to start, so the bridge is not idle.
13346
+ */
13347
+ busyCount() {
13348
+ return this.handles.size + this.reservations.size;
13349
+ }
12980
13350
  scopes() {
12981
13351
  return [...this.handles.keys()];
12982
13352
  }
@@ -13322,8 +13692,8 @@ function isTerminalEvent(event) {
13322
13692
 
13323
13693
  // src/session/context-store.ts
13324
13694
  import { createHash as createHash5 } from "crypto";
13325
- import { readFile as readFile13 } from "fs/promises";
13326
- import { join as join19 } from "path";
13695
+ import { readFile as readFile15 } from "fs/promises";
13696
+ import { join as join21 } from "path";
13327
13697
  var MAX_MESSAGES = 25;
13328
13698
  var MAX_MESSAGE_CHARS = 8e3;
13329
13699
  var MAX_HISTORY_CHARS = 64e3;
@@ -13388,7 +13758,7 @@ var ConversationContextStore = class {
13388
13758
  identity.cwdRealpath,
13389
13759
  identity.policyFingerprint
13390
13760
  ])).digest("hex");
13391
- return join19(this.profileDir, "context", `${hash}.json`);
13761
+ return join21(this.profileDir, "context", `${hash}.json`);
13392
13762
  }
13393
13763
  async load(identity) {
13394
13764
  const path4 = this.path(identity);
@@ -13403,7 +13773,7 @@ var ConversationContextStore = class {
13403
13773
  }
13404
13774
  async readCheckpoint(path4) {
13405
13775
  try {
13406
- const value = JSON.parse(await readFile13(path4, "utf8"));
13776
+ const value = JSON.parse(await readFile15(path4, "utf8"));
13407
13777
  if (!value || typeof value !== "object") return void 0;
13408
13778
  const record5 = value;
13409
13779
  if (typeof record5.sessionId !== "string" || typeof record5.completedAt !== "number" || !Number.isFinite(record5.completedAt) || !Array.isArray(record5.messages)) return void 0;
@@ -13423,8 +13793,8 @@ var ConversationContextStore = class {
13423
13793
 
13424
13794
  // src/memory/store.ts
13425
13795
  import { createHash as createHash6, randomUUID as randomUUID3 } from "crypto";
13426
- import { mkdir as mkdir14, readdir as readdir7, realpath as realpath5, stat as stat6, writeFile as writeFile10 } from "fs/promises";
13427
- import { join as join20 } from "path";
13796
+ import { mkdir as mkdir17, readdir as readdir8, realpath as realpath5, stat as stat6, writeFile as writeFile10 } from "fs/promises";
13797
+ import { join as join22 } from "path";
13428
13798
  import * as lockfile5 from "proper-lockfile";
13429
13799
  var initializations = /* @__PURE__ */ new Map();
13430
13800
  var README_NAME = "README.md";
@@ -13454,7 +13824,7 @@ var WorkspaceMemoryStore = class {
13454
13824
  maxNotes;
13455
13825
  maxBytes;
13456
13826
  constructor(profileDir, limits = {}) {
13457
- this.root = join20(profileDir, "memory");
13827
+ this.root = join22(profileDir, "memory");
13458
13828
  this.maxNotes = limits.maxNotes ?? 200;
13459
13829
  this.maxBytes = limits.maxBytes ?? 1024 * 1024;
13460
13830
  }
@@ -13462,10 +13832,10 @@ var WorkspaceMemoryStore = class {
13462
13832
  const directory = await this.ensureDirectory(cwdRealpath);
13463
13833
  let noteCount = 0;
13464
13834
  let totalBytes = 0;
13465
- for (const entry of await readdir7(directory, { withFileTypes: true })) {
13835
+ for (const entry of await readdir8(directory, { withFileTypes: true })) {
13466
13836
  if (entry.name === README_NAME || !entry.isFile() || entry.name.startsWith(".README.md.tmp-")) continue;
13467
13837
  try {
13468
- const info = await stat6(join20(directory, entry.name));
13838
+ const info = await stat6(join22(directory, entry.name));
13469
13839
  noteCount += 1;
13470
13840
  totalBytes += info.size;
13471
13841
  } catch (err) {
@@ -13486,7 +13856,7 @@ var WorkspaceMemoryStore = class {
13486
13856
  /** Creates a new note; capacity reporting is advisory, not a concurrent hard quota. */
13487
13857
  async appendNote(cwdRealpath, content) {
13488
13858
  const directory = await this.ensureDirectory(cwdRealpath);
13489
- const path4 = join20(directory, `${randomUUID3()}.md`);
13859
+ const path4 = join22(directory, `${randomUUID3()}.md`);
13490
13860
  await writeFile10(path4, content, { encoding: "utf8", flag: "wx", mode: 384 });
13491
13861
  return path4;
13492
13862
  }
@@ -13494,9 +13864,9 @@ var WorkspaceMemoryStore = class {
13494
13864
  const resolved = await realpath5(cwdRealpath);
13495
13865
  const canonical = process.platform === "win32" ? resolved.toLowerCase() : resolved;
13496
13866
  const hash = createHash6("sha256").update(canonical).digest("hex");
13497
- const directory = join20(this.root, hash);
13498
- await mkdir14(directory, { recursive: true, mode: 448 });
13499
- const readmePath = join20(directory, README_NAME);
13867
+ const directory = join22(this.root, hash);
13868
+ await mkdir17(directory, { recursive: true, mode: 448 });
13869
+ const readmePath = join22(directory, README_NAME);
13500
13870
  try {
13501
13871
  await stat6(readmePath);
13502
13872
  } catch (err) {
@@ -13854,6 +14224,10 @@ var PendingQueue = class {
13854
14224
  armTimer(scope) {
13855
14225
  return setTimeout(() => this.flush(scope), this.delayMs);
13856
14226
  }
14227
+ /** Scopes with queued (not yet flushed) messages. Used by idle detection. */
14228
+ pendingCount() {
14229
+ return this.map.size;
14230
+ }
13857
14231
  flush(scope) {
13858
14232
  const entry = this.map.get(scope);
13859
14233
  if (!entry) return;
@@ -13866,6 +14240,21 @@ var PendingQueue = class {
13866
14240
  }
13867
14241
  };
13868
14242
 
14243
+ // src/selfupdate/idle.ts
14244
+ var sources = /* @__PURE__ */ new Set();
14245
+ function registerIdleSource(check2) {
14246
+ sources.add(check2);
14247
+ return () => {
14248
+ sources.delete(check2);
14249
+ };
14250
+ }
14251
+ function allChannelsIdle() {
14252
+ for (const check2 of sources) {
14253
+ if (!check2()) return false;
14254
+ }
14255
+ return true;
14256
+ }
14257
+
13869
14258
  // src/bot/send-failure.ts
13870
14259
  var MAX_REASON_CHARS = 160;
13871
14260
  var UNKNOWN_REASON = "\u672A\u77E5\u9519\u8BEF";
@@ -14120,25 +14509,25 @@ function fitCotLines(lines) {
14120
14509
  }
14121
14510
  var FENCE_LINE = /^[ \t]*(`{3,})(.*)$/;
14122
14511
  function fenceLengthAt(lines, end) {
14123
- let open3 = 0;
14512
+ let open4 = 0;
14124
14513
  for (let index = 0; index < end; index += 1) {
14125
- open3 = advanceFence(open3, lines[index] ?? "");
14514
+ open4 = advanceFence(open4, lines[index] ?? "");
14126
14515
  }
14127
- return open3;
14516
+ return open4;
14128
14517
  }
14129
14518
  function fenceLengthAfter(lines, initial) {
14130
- let open3 = initial;
14519
+ let open4 = initial;
14131
14520
  for (const line of lines) {
14132
- open3 = advanceFence(open3, line);
14521
+ open4 = advanceFence(open4, line);
14133
14522
  }
14134
- return open3;
14523
+ return open4;
14135
14524
  }
14136
- function advanceFence(open3, line) {
14525
+ function advanceFence(open4, line) {
14137
14526
  const match = line.match(FENCE_LINE);
14138
- if (!match) return open3;
14527
+ if (!match) return open4;
14139
14528
  const marker = match[1] ?? "";
14140
- if (!open3) return marker.length;
14141
- return (match[2] ?? "").trim() === "" && marker.length >= open3 ? 0 : open3;
14529
+ if (!open4) return marker.length;
14530
+ return (match[2] ?? "").trim() === "" && marker.length >= open4 ? 0 : open4;
14142
14531
  }
14143
14532
  function applyCotEvent(lines, event) {
14144
14533
  let content = {};
@@ -14518,11 +14907,11 @@ async function startChannel(deps) {
14518
14907
  const chatModeCache = new ChatModeCache();
14519
14908
  const pool = new ProcessPool(() => getMaxConcurrentRuns(controls.cfg));
14520
14909
  const executor = new RunExecutor({ agent, pool, activeRuns });
14521
- const profileDir = deps.appPaths?.mediaDir ? dirname17(deps.appPaths.mediaDir) : void 0;
14910
+ const profileDir = deps.appPaths?.mediaDir ? dirname19(deps.appPaths.mediaDir) : void 0;
14522
14911
  const contextStore = profileDir ? new ConversationContextStore(profileDir) : void 0;
14523
14912
  const memory = profileDir ? new WorkspaceMemoryStore(profileDir) : void 0;
14524
14913
  const appSecret = await resolveAppSecret(cfg, deps.appPaths);
14525
- const callbackNonceStore = deps.appPaths?.mediaDir ? new CallbackNonceStore(join21(dirname17(deps.appPaths.mediaDir), "callback-nonces.json")) : void 0;
14914
+ const callbackNonceStore = deps.appPaths?.mediaDir ? new CallbackNonceStore(join23(dirname19(deps.appPaths.mediaDir), "callback-nonces.json")) : void 0;
14526
14915
  await callbackNonceStore?.load();
14527
14916
  const callbackAuth = callbackNonceStore ? new CallbackAuth({
14528
14917
  keys: [{ version: 1, secret: appSecret }],
@@ -14551,7 +14940,7 @@ async function startChannel(deps) {
14551
14940
  webhookServer,
14552
14941
  webhookBodyLimitBytes: cfg.webhook.bodyLimitBytes,
14553
14942
  dedupeTtlMs: cfg.webhook.dedupeTtlMs,
14554
- dedupeFile: deps.appPaths?.mediaDir ? join21(dirname17(deps.appPaths.mediaDir), "webhook-events.json") : void 0,
14943
+ dedupeFile: deps.appPaths?.mediaDir ? join23(dirname19(deps.appPaths.mediaDir), "webhook-events.json") : void 0,
14555
14944
  streamThrottleMs: 250,
14556
14945
  sendMessageApiVersion: () => getSendMessageApiVersion(controls.cfg)
14557
14946
  });
@@ -14708,9 +15097,13 @@ async function startChannel(deps) {
14708
15097
  console.log(`${stdoutTsPrefix()}\u6B63\u5728\u76D1\u542C Xiaojiu Webhook\uFF1A${route2}\uFF08\u5171\u4EAB\u7AEF\u53E3 ${cfg.webhook.port}\uFF09
14709
15098
  `);
14710
15099
  }
15100
+ const unregisterIdle = registerIdleSource(
15101
+ () => activeRuns.busyCount() === 0 && pending.pendingCount() === 0
15102
+ );
14711
15103
  return {
14712
15104
  channel,
14713
15105
  disconnect: async () => {
15106
+ unregisterIdle();
14714
15107
  activeRuns.pauseNewRuns("bridge-disconnect");
14715
15108
  ownerRefresh.stop();
14716
15109
  knownChatsRefresh.stop();
@@ -15393,7 +15786,7 @@ async function runAgentBatch(deps) {
15393
15786
  activePolicyFingerprints.delete(scope);
15394
15787
  }
15395
15788
  }
15396
- function createLazyProgressStream(scope, mode, open3) {
15789
+ function createLazyProgressStream(scope, mode, open4) {
15397
15790
  let stream2;
15398
15791
  let givenUp = false;
15399
15792
  let settle;
@@ -15408,7 +15801,7 @@ function createLazyProgressStream(scope, mode, open3) {
15408
15801
  ensureOpen: () => {
15409
15802
  if (stream2) return;
15410
15803
  log.info("outbound", "progress-stream-open", { scope, mode });
15411
- stream2 = open3();
15804
+ stream2 = open4();
15412
15805
  settle(stream2);
15413
15806
  },
15414
15807
  abandoned: () => givenUp,
@@ -15864,6 +16257,143 @@ function isDefined(value) {
15864
16257
  return value !== void 0;
15865
16258
  }
15866
16259
 
16260
+ // src/selfupdate/scheduler.ts
16261
+ var CHECK_INTERVAL_MS2 = 6 * 60 * 60 * 1e3;
16262
+ var INITIAL_DELAY_MS = 5 * 60 * 1e3;
16263
+ var IDLE_POLL_MS = 10 * 60 * 1e3;
16264
+ var MAX_IDLE_WAIT_MS = 6 * 60 * 60 * 1e3;
16265
+ function isAutoUpdateEnvDisabled(env = process.env) {
16266
+ return env.XIAOJIU_BRIDGE_NO_UPDATE_CHECK === "1" || env.CI === "true";
16267
+ }
16268
+ function startAutoUpdateScheduler(deps) {
16269
+ const now = deps.now ?? (() => Date.now());
16270
+ const checkIntervalMs = deps.checkIntervalMs ?? CHECK_INTERVAL_MS2;
16271
+ const idlePollMs = deps.idlePollMs ?? IDLE_POLL_MS;
16272
+ const maxIdleWaitMs = deps.maxIdleWaitMs ?? MAX_IDLE_WAIT_MS;
16273
+ let stopped = false;
16274
+ let ticking = false;
16275
+ let timer;
16276
+ const scheduleNext = (delayMs) => {
16277
+ if (stopped) return;
16278
+ timer = setTimeout(() => void tick(), delayMs);
16279
+ timer.unref?.();
16280
+ };
16281
+ const waitForIdle = async () => {
16282
+ const deadline = now() + maxIdleWaitMs;
16283
+ for (; ; ) {
16284
+ if (stopped) return false;
16285
+ if (deps.isIdle()) return true;
16286
+ if (now() >= deadline) return false;
16287
+ await new Promise((resolve5) => {
16288
+ const t = setTimeout(resolve5, idlePollMs);
16289
+ t.unref?.();
16290
+ });
16291
+ }
16292
+ };
16293
+ const tick = async () => {
16294
+ if (stopped || ticking) return;
16295
+ ticking = true;
16296
+ try {
16297
+ if (!deps.enabled() || isAutoUpdateEnvDisabled()) return;
16298
+ const info = await (deps.fetchInfo ?? fetchUpdateInfo)({});
16299
+ if (!info) return;
16300
+ log.info("self-update", "available", { from: info.currentVersion, to: info.latestVersion });
16301
+ const staged = await (deps.stage ?? stageVersion)({
16302
+ layout: deps.layout,
16303
+ targetVersion: info.latestVersion,
16304
+ log: (event, fields) => log.info("self-update", event, fields)
16305
+ });
16306
+ if (!staged.ok) {
16307
+ log.warn("self-update", "stage-failed", { version: info.latestVersion, err: staged.error });
16308
+ return;
16309
+ }
16310
+ await (deps.persistPending ?? writePending)(deps.layout, {
16311
+ version: info.latestVersion,
16312
+ dir: staged.dir,
16313
+ stagedAt: new Date(now()).toISOString()
16314
+ });
16315
+ if (await waitForIdle()) {
16316
+ log.info("self-update", "switching", { version: info.latestVersion });
16317
+ stopped = true;
16318
+ deps.requestSwitch();
16319
+ } else {
16320
+ log.info("self-update", "switch-deferred", { version: info.latestVersion });
16321
+ }
16322
+ } catch (err) {
16323
+ log.warn("self-update", "tick-failed", { err: err instanceof Error ? err.message : String(err) });
16324
+ } finally {
16325
+ ticking = false;
16326
+ scheduleNext(checkIntervalMs);
16327
+ }
16328
+ };
16329
+ scheduleNext(deps.initialDelayMs ?? INITIAL_DELAY_MS);
16330
+ return {
16331
+ stop() {
16332
+ stopped = true;
16333
+ clearTimeout(timer);
16334
+ }
16335
+ };
16336
+ }
16337
+
16338
+ // src/cli/commands/migrate-launcher.ts
16339
+ import { readFile as readFile16 } from "fs/promises";
16340
+ import { join as join24 } from "path";
16341
+ var RETRY_AFTER_MS = 24 * 60 * 60 * 1e3;
16342
+ async function maybeMigrateServiceToLauncher(opts) {
16343
+ const env = opts.env ?? process.env;
16344
+ if (isUnderLauncher(env)) return { migrated: false };
16345
+ if (!getAutoUpdateEnabled(opts.cfg)) return { migrated: false, reason: "auto-update disabled" };
16346
+ if (isAutoUpdateEnvDisabled(env)) return { migrated: false, reason: "update checks disabled" };
16347
+ const layout = updateLayout(opts.rootDir);
16348
+ const markerFile = join24(layout.updateDir, "launcher-migration.json");
16349
+ const lastAttempt = await readFile16(markerFile, "utf8").then((text2) => {
16350
+ const parsed = JSON.parse(text2);
16351
+ return typeof parsed === "object" && parsed !== null && "attemptedAt" in parsed && typeof parsed.attemptedAt === "string" ? Date.parse(parsed.attemptedAt) : Number.NaN;
16352
+ }).catch(() => Number.NaN);
16353
+ if (Number.isFinite(lastAttempt) && Date.now() - lastAttempt < RETRY_AFTER_MS) {
16354
+ return { migrated: false, reason: "migration attempted recently" };
16355
+ }
16356
+ const serviceId = `port-${opts.port}`;
16357
+ const probe = getServiceAdapter(serviceId);
16358
+ if (!probe?.fileExists()) return { migrated: false, reason: "no daemon service installed" };
16359
+ const installation = await resolveUpdateInstallation({ name: packageName });
16360
+ if (installation.kind !== "global") return { migrated: false, reason: `installation is ${installation.kind}` };
16361
+ await writeFileAtomic(markerFile, `${JSON.stringify({ attemptedAt: (/* @__PURE__ */ new Date()).toISOString() }, null, 2)}
16362
+ `, { mode: 384 });
16363
+ try {
16364
+ await prepareLauncherInstall(layout, version);
16365
+ const runArgs = await detectWebUiFlag(serviceId) ? ["run", "--web-ui", "--profile", opts.profile] : ["run", "--profile", opts.profile];
16366
+ const adapter = getServiceAdapter(serviceId, runArgs, {
16367
+ importArgs: [],
16368
+ entryPath: layout.launcherFile
16369
+ });
16370
+ if (!adapter) return { migrated: false, reason: "unsupported platform" };
16371
+ await adapter.install();
16372
+ log.info("self-update", "migrating-to-launcher", { version, serviceId });
16373
+ await adapter.restart();
16374
+ return { migrated: true };
16375
+ } catch (err) {
16376
+ log.warn("self-update", "migration-failed", { err: err instanceof Error ? err.message : String(err) });
16377
+ return { migrated: false, reason: err instanceof Error ? err.message : String(err) };
16378
+ }
16379
+ }
16380
+ async function detectWebUiFlag(serviceId) {
16381
+ const files = [];
16382
+ if (process.platform === "win32") {
16383
+ files.push(windowsLauncherCmdPath(serviceId));
16384
+ } else {
16385
+ const adapter = getServiceAdapter(serviceId);
16386
+ if (adapter) files.push(adapter.servicePath());
16387
+ }
16388
+ for (const file of files) {
16389
+ try {
16390
+ if ((await readFile16(file, "utf8")).includes("--web-ui")) return true;
16391
+ } catch {
16392
+ }
16393
+ }
16394
+ return false;
16395
+ }
16396
+
15867
16397
  // src/ui/server.ts
15868
16398
  import { createServer as createServer3 } from "http";
15869
16399
  import { randomBytes as randomBytes5 } from "crypto";
@@ -15882,7 +16412,7 @@ function prepareConsoleHtml(html) {
15882
16412
  if (styles.length === 0) return html;
15883
16413
  const block = styles.join("\n ");
15884
16414
  if (/<head[^>]*>/i.test(withoutStyles)) {
15885
- return withoutStyles.replace(/<head[^>]*>/i, (open3) => `${open3}
16415
+ return withoutStyles.replace(/<head[^>]*>/i, (open4) => `${open4}
15886
16416
  ${block}`);
15887
16417
  }
15888
16418
  return `${block}${withoutStyles}`;
@@ -15900,9 +16430,9 @@ function flattenCssLayers(css) {
15900
16430
  }
15901
16431
  return out.trim();
15902
16432
  }
15903
- function matchingBrace(src, open3) {
16433
+ function matchingBrace(src, open4) {
15904
16434
  let depth = 0;
15905
- for (let i = open3; i < src.length; i++) {
16435
+ for (let i = open4; i < src.length; i++) {
15906
16436
  const ch = src[i];
15907
16437
  if (ch === "{") depth++;
15908
16438
  else if (ch === "}") {
@@ -16159,7 +16689,7 @@ function accessView(access2) {
16159
16689
  }
16160
16690
 
16161
16691
  // src/session/store.ts
16162
- import { readFile as readFile14 } from "fs/promises";
16692
+ import { readFile as readFile17 } from "fs/promises";
16163
16693
  var SessionStore = class {
16164
16694
  data = {};
16165
16695
  saving = Promise.resolve();
@@ -16169,7 +16699,7 @@ var SessionStore = class {
16169
16699
  }
16170
16700
  async load() {
16171
16701
  try {
16172
- const text2 = await readFile14(this.path, "utf8");
16702
+ const text2 = await readFile17(this.path, "utf8");
16173
16703
  const raw = JSON.parse(text2);
16174
16704
  this.data = {};
16175
16705
  for (const [chatId, entry] of Object.entries(raw)) {
@@ -16307,7 +16837,7 @@ function peerFields(entry) {
16307
16837
  }
16308
16838
 
16309
16839
  // src/workspace/store.ts
16310
- import { readFile as readFile15 } from "fs/promises";
16840
+ import { readFile as readFile18 } from "fs/promises";
16311
16841
  var WorkspaceStore = class {
16312
16842
  data = { chats: {}, named: {} };
16313
16843
  saving = Promise.resolve();
@@ -16317,7 +16847,7 @@ var WorkspaceStore = class {
16317
16847
  }
16318
16848
  async load() {
16319
16849
  try {
16320
- const text2 = await readFile15(this.path, "utf8");
16850
+ const text2 = await readFile18(this.path, "utf8");
16321
16851
  const parsed = JSON.parse(text2);
16322
16852
  this.data = {
16323
16853
  chats: parsed.chats ?? {},
@@ -16636,7 +17166,7 @@ function asRecord3(body) {
16636
17166
  }
16637
17167
 
16638
17168
  // src/prompt/store.ts
16639
- import { readFile as readFile16 } from "fs/promises";
17169
+ import { readFile as readFile19 } from "fs/promises";
16640
17170
  var MAX_PROMPT_CHARS = 16e3;
16641
17171
  var PromptStore = class {
16642
17172
  data = { bot: "", chats: {} };
@@ -16647,7 +17177,7 @@ var PromptStore = class {
16647
17177
  }
16648
17178
  async load() {
16649
17179
  try {
16650
- const text2 = await readFile16(this.path, "utf8");
17180
+ const text2 = await readFile19(this.path, "utf8");
16651
17181
  this.data = normalizePromptData(JSON.parse(text2));
16652
17182
  } catch (err) {
16653
17183
  if (err.code === "ENOENT") return;
@@ -17309,7 +17839,7 @@ var WebhookRequestError2 = class extends Error {
17309
17839
 
17310
17840
  // src/agent/model-discovery.ts
17311
17841
  import { createInterface as createInterface7 } from "readline";
17312
- import { join as join22 } from "path";
17842
+ import { join as join25 } from "path";
17313
17843
  var DEFAULT_TIMEOUT_MS3 = 5e3;
17314
17844
  async function discoverModels(agentKind, options) {
17315
17845
  if (!options) return supportedModels(agentKind);
@@ -17482,7 +18012,7 @@ ${JSON.stringify({ method: "model/list", id: 2, params: { includeHidden: false,
17482
18012
  function spawnCodexAppServer2(options) {
17483
18013
  const envOverrides = {};
17484
18014
  if (options.codexHome) envOverrides.CODEX_HOME = options.codexHome;
17485
- else if (options.inheritCodexHome === false) envOverrides.CODEX_HOME = join22(options.profileStateDir, "codex-home");
18015
+ else if (options.inheritCodexHome === false) envOverrides.CODEX_HOME = join25(options.profileStateDir, "codex-home");
17486
18016
  return spawnProcess(options.binary, ["app-server", "--listen", "stdio://"], {
17487
18017
  env: mergeProcessEnv(process.env, envOverrides),
17488
18018
  stdio: ["pipe", "pipe", "pipe"]
@@ -17523,7 +18053,7 @@ function parseModels(input) {
17523
18053
  }
17524
18054
 
17525
18055
  // src/session/catalog.ts
17526
- import { readFile as readFile17 } from "fs/promises";
18056
+ import { readFile as readFile20 } from "fs/promises";
17527
18057
  var DEFAULT_MAX_ARCHIVED_AGE_MS = 90 * 24 * 60 * 60 * 1e3;
17528
18058
  var DEFAULT_MAX_ENTRIES_PER_SCOPE = 20;
17529
18059
  var DEFAULT_MAX_ENTRIES_PER_PROFILE = 1e3;
@@ -17545,7 +18075,7 @@ var SessionCatalog = class {
17545
18075
  }
17546
18076
  async load() {
17547
18077
  try {
17548
- const raw = JSON.parse(await readFile17(this.path, "utf8"));
18078
+ const raw = JSON.parse(await readFile20(this.path, "utf8"));
17549
18079
  if (!Array.isArray(raw)) {
17550
18080
  this.data.clear();
17551
18081
  return;
@@ -18553,6 +19083,16 @@ async function runStart(opts) {
18553
19083
  hostname: os.hostname()
18554
19084
  });
18555
19085
  await gcOldLogs(await collectProfileLogDirs(appPaths2.rootDir));
19086
+ const migration = await maybeMigrateServiceToLauncher({
19087
+ profile: appPaths2.profile,
19088
+ port,
19089
+ rootDir: appPaths2.rootDir,
19090
+ cfg
19091
+ });
19092
+ if (migration.migrated) {
19093
+ console.log(`${stdoutTsPrefix()}\u2713 \u5DF2\u5207\u6362\u5230\u81EA\u52A8\u66F4\u65B0\u8FD0\u884C\u6A21\u5F0F\uFF0C\u540E\u53F0\u670D\u52A1\u91CD\u542F\u4E2D\u2026`);
19094
+ return;
19095
+ }
18556
19096
  const claimed = await claimListenLock({
18557
19097
  port,
18558
19098
  host: cfg.webhook.host,
@@ -18612,19 +19152,29 @@ async function runStart(opts) {
18612
19152
  const uid = readAndPrune().find((e) => e.profileName === appPaths2.profile && e.pid === process.pid)?.id;
18613
19153
  console.log(`${stdoutTsPrefix()}\u2713 profile\u300C${appPaths2.profile}\u300D\u5DF2\u4E0A\u7EBF${mode}`);
18614
19154
  console.log(` \u8FDB\u7A0B: ${process.pid}${uid ? ` uid: ${uid}` : ""} webhook: ${webhook}`);
18615
- await parkWithShutdown(supervisor, appPaths2, uiServer, listenLock, port);
19155
+ markBootReady();
19156
+ await parkWithShutdown(supervisor, appPaths2, uiServer, listenLock, port, (requestExit) => {
19157
+ if (!isUnderLauncher() || !getAutoUpdateEnabled(cfg) || isAutoUpdateEnvDisabled()) return;
19158
+ startAutoUpdateScheduler({
19159
+ enabled: () => getAutoUpdateEnabled(cfg),
19160
+ isIdle: allChannelsIdle,
19161
+ requestSwitch: () => void requestExit(SWITCH_EXIT_CODE),
19162
+ layout: updateLayout(appPaths2.rootDir)
19163
+ });
19164
+ log.info("self-update", "scheduler-started", { profile: appPaths2.profile });
19165
+ });
18616
19166
  }
18617
19167
  async function collectProfileLogDirs(rootDir) {
18618
19168
  const dirs = [];
18619
19169
  let profiles;
18620
19170
  try {
18621
- profiles = await readdir8(join23(rootDir, "profiles"));
19171
+ profiles = await readdir9(join26(rootDir, "profiles"));
18622
19172
  } catch {
18623
19173
  return dirs;
18624
19174
  }
18625
19175
  for (const profile2 of profiles) {
18626
- dirs.push(join23(rootDir, "profiles", profile2, "logs"));
18627
- dirs.push(join23(rootDir, "profiles", profile2, "logs", "daemon"));
19176
+ dirs.push(join26(rootDir, "profiles", profile2, "logs"));
19177
+ dirs.push(join26(rootDir, "profiles", profile2, "logs", "daemon"));
18628
19178
  }
18629
19179
  return dirs;
18630
19180
  }
@@ -18640,9 +19190,9 @@ async function joinExistingListen(sidecar, profile2, port, webhook, webUi) {
18640
19190
  console.log(`\u2713 profile\u300C${profile2}\u300D\u5DF2\u4E0A\u7EBF\uFF08\u52A0\u5165\u8FDB\u7A0B ${sidecar.pid}${uid ? ` uid: ${uid}` : ""} webhook ${webhook}\uFF09`);
18641
19191
  if (webUi && sidecar.url) console.log(` \u63A7\u5236\u53F0\uFF1A${sidecar.url}`);
18642
19192
  }
18643
- function parkWithShutdown(supervisor, appPaths2, uiServer, listenLock, port) {
19193
+ function parkWithShutdown(supervisor, appPaths2, uiServer, listenLock, port, onParked) {
18644
19194
  let shuttingDown = false;
18645
- const shutdown = async (sig) => {
19195
+ const shutdown = async (sig, exitCode = 0) => {
18646
19196
  if (shuttingDown) return;
18647
19197
  shuttingDown = true;
18648
19198
  console.log(`
@@ -18658,7 +19208,7 @@ function parkWithShutdown(supervisor, appPaths2, uiServer, listenLock, port) {
18658
19208
  });
18659
19209
  await forceReleaseHostLock(listenLockFile(port, appPaths2.rootDir));
18660
19210
  await flushTelemetry();
18661
- process.exit(0);
19211
+ process.exit(exitCode);
18662
19212
  };
18663
19213
  process.on("SIGINT", () => void shutdown("SIGINT"));
18664
19214
  process.on("SIGTERM", () => void shutdown("SIGTERM"));
@@ -18669,6 +19219,7 @@ function parkWithShutdown(supervisor, appPaths2, uiServer, listenLock, port) {
18669
19219
  supervisor.unregisterAllSync();
18670
19220
  cleanupTmpFiles(appPaths2.userRegistryFile);
18671
19221
  });
19222
+ onParked?.((exitCode) => shutdown("auto-update", exitCode));
18672
19223
  return new Promise(() => {
18673
19224
  });
18674
19225
  }