@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.
@@ -0,0 +1,159 @@
1
+ // src/launcher/launcher.ts
2
+ import { spawn } from "child_process";
3
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "fs";
4
+ import { homedir } from "os";
5
+ import { dirname, join } from "path";
6
+
7
+ // src/selfupdate/protocol.ts
8
+ var SWITCH_EXIT_CODE = 75;
9
+ var ENV_LAUNCHER = "XIAOJIU_BRIDGE_LAUNCHER";
10
+ var PACKAGE_NAME = "@saltpub/xiaojiu-agent-bridge";
11
+ var ENV_VERSION_DIR = "XIAOJIU_BRIDGE_VERSION_DIR";
12
+ var ENV_BOOT_FILE = "XIAOJIU_BRIDGE_BOOT_FILE";
13
+
14
+ // src/launcher/launcher.ts
15
+ var home = process.env.XIAOJIU_BRIDGE_HOME ?? join(homedir(), ".xiaojiu-agent-bridge");
16
+ var updateDir = join(home, "update");
17
+ var currentFile = join(updateDir, "current.json");
18
+ var pendingFile = join(updateDir, "pending.json");
19
+ var bootFile = join(updateDir, "boot.json");
20
+ var badFile = join(updateDir, "bad.json");
21
+ var logFile = join(updateDir, "launcher.log");
22
+ var MAX_BOOT_ATTEMPTS = 2;
23
+ var CRASH_BACKOFF_MS = 5e3;
24
+ var BOOT_FAIL_MAX_BACKOFF_MS = 6e4;
25
+ function logline(message) {
26
+ try {
27
+ mkdirSync(updateDir, { recursive: true });
28
+ appendFileSync(logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${message}
29
+ `);
30
+ } catch {
31
+ }
32
+ }
33
+ function readJson(file) {
34
+ try {
35
+ return JSON.parse(readFileSync(file, "utf8"));
36
+ } catch {
37
+ return void 0;
38
+ }
39
+ }
40
+ function writeJsonAtomic(file, value) {
41
+ mkdirSync(dirname(file), { recursive: true });
42
+ const tmp = `${file}.tmp-${process.pid}`;
43
+ writeFileSync(tmp, `${JSON.stringify(value, null, 2)}
44
+ `, { mode: 384 });
45
+ renameSync(tmp, file);
46
+ }
47
+ function cliEntryOf(dir) {
48
+ return join(dir, "node_modules", ...PACKAGE_NAME.split("/"), "dist", "cli.js");
49
+ }
50
+ function applyPending() {
51
+ const pending = readJson(pendingFile);
52
+ if (!pending || typeof pending.version !== "string" || typeof pending.dir !== "string") return;
53
+ if (!existsSync(cliEntryOf(pending.dir))) {
54
+ logline(`pending ${pending.version} has no dist/cli.js; dropping`);
55
+ rmSync(pendingFile, { force: true });
56
+ return;
57
+ }
58
+ const current = readJson(currentFile);
59
+ const next = {
60
+ version: pending.version,
61
+ dir: pending.dir,
62
+ ...current && typeof current.version === "string" ? { previous: { version: current.version, dir: current.dir } } : {}
63
+ };
64
+ writeJsonAtomic(currentFile, next);
65
+ rmSync(pendingFile, { force: true });
66
+ logline(`switched ${current?.version ?? "(none)"} -> ${pending.version}`);
67
+ }
68
+ function markBad(version) {
69
+ const bad = readJson(badFile);
70
+ const versions = Array.isArray(bad?.versions) ? bad.versions.filter((v) => typeof v === "string") : [];
71
+ if (!versions.includes(version)) versions.push(version);
72
+ writeJsonAtomic(badFile, { versions });
73
+ }
74
+ function sleep(ms) {
75
+ return new Promise((resolve) => {
76
+ setTimeout(resolve, ms);
77
+ });
78
+ }
79
+ async function main() {
80
+ const childArgs = process.argv.slice(2);
81
+ let child;
82
+ let quitting = false;
83
+ for (const signal of ["SIGINT", "SIGTERM"]) {
84
+ process.on(signal, () => {
85
+ quitting = true;
86
+ child?.kill(signal);
87
+ });
88
+ }
89
+ for (; ; ) {
90
+ applyPending();
91
+ const current = readJson(currentFile);
92
+ if (!current || typeof current.version !== "string" || typeof current.dir !== "string") {
93
+ logline("no usable current.json; supervisor exiting");
94
+ process.exit(1);
95
+ }
96
+ if (!existsSync(cliEntryOf(current.dir))) {
97
+ const previous2 = current.previous;
98
+ if (previous2 && existsSync(cliEntryOf(previous2.dir))) {
99
+ logline(`current ${current.version} lost its files; reverting to ${previous2.version}`);
100
+ writeJsonAtomic(currentFile, { version: previous2.version, dir: previous2.dir });
101
+ continue;
102
+ }
103
+ logline(`current ${current.version} lost its files and no previous exists; supervisor exiting`);
104
+ process.exit(1);
105
+ }
106
+ const prior = readJson(bootFile);
107
+ const attempts = prior?.version === current.version && typeof prior.attempts === "number" ? prior.attempts : 0;
108
+ const boot = {
109
+ version: current.version,
110
+ ready: false,
111
+ attempts,
112
+ pid: process.pid,
113
+ startedAt: (/* @__PURE__ */ new Date()).toISOString()
114
+ };
115
+ writeJsonAtomic(bootFile, boot);
116
+ logline(`starting ${current.version} (attempt ${attempts + 1})`);
117
+ child = spawn(process.execPath, [cliEntryOf(current.dir), ...childArgs], {
118
+ stdio: "inherit",
119
+ env: {
120
+ ...process.env,
121
+ [ENV_LAUNCHER]: "1",
122
+ [ENV_VERSION_DIR]: current.dir,
123
+ [ENV_BOOT_FILE]: bootFile
124
+ }
125
+ });
126
+ const code = await new Promise((resolve) => {
127
+ child?.on("exit", (exitCode, signal) => {
128
+ resolve(exitCode ?? (signal ? 1 : 0));
129
+ });
130
+ });
131
+ child = void 0;
132
+ if (quitting) process.exit(0);
133
+ if (code === SWITCH_EXIT_CODE) {
134
+ logline("child requested version switch");
135
+ continue;
136
+ }
137
+ const after = readJson(bootFile);
138
+ if (after?.ready === true) {
139
+ logline(`child exited (code ${code}) after ready; restarting`);
140
+ await sleep(CRASH_BACKOFF_MS);
141
+ continue;
142
+ }
143
+ const nextAttempts = attempts + 1;
144
+ writeJsonAtomic(bootFile, { ...boot, attempts: nextAttempts });
145
+ logline(`child exited (code ${code}) before ready; attempt ${nextAttempts}`);
146
+ const previous = current.previous;
147
+ if (nextAttempts >= MAX_BOOT_ATTEMPTS && previous && existsSync(cliEntryOf(previous.dir))) {
148
+ markBad(current.version);
149
+ logline(`${current.version} failed ${nextAttempts} boots; reverted to ${previous.version} and marked bad`);
150
+ writeJsonAtomic(currentFile, { version: previous.version, dir: previous.dir });
151
+ continue;
152
+ }
153
+ await sleep(Math.min(CRASH_BACKOFF_MS * 2 ** nextAttempts, BOOT_FAIL_MAX_BACKOFF_MS));
154
+ }
155
+ }
156
+ main().catch((err) => {
157
+ logline(`supervisor fatal: ${err instanceof Error ? err.stack ?? err.message : String(err)}`);
158
+ process.exit(1);
159
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@saltpub/xiaojiu-agent-bridge",
3
- "version": "0.1.6",
3
+ "version": "0.1.7",
4
4
  "description": "Bridge Xiaojiu IM with local CLI coding agents",
5
5
  "type": "module",
6
6
  "packageManager": "pnpm@10.33.0",
@@ -112,9 +112,7 @@
112
112
  "schemaVersion": 1,
113
113
  "channel": "stable",
114
114
  "highlights": [
115
- "新增默认开启的 OpenObserve 遥测:内置 `@saltpub/xiaojiu-bridge-telemetry` adapter,启动时自动探测内置 endpoint(健康检查可达性确认),事件/指标/错误经 OTLP 上报到 `xiaojiu_agent_bridge` 流;`XIAOJIU_BRIDGE_TELEMETRY_DISABLED=1` 可完全关闭,`XIAOJIU_BRIDGE_TELEMETRY_MODULE` 仍可指定外部 adapter。无 endpoint 可达时保持静默 noop,不影响 bridge 运行。",
116
- "Make explicit update checks distinguish registry errors from an up-to-date installation, validate package identity and stable-version selection, and use separate passive/explicit timeouts. Refuse mutating updates from npx or source installations and while the configured home contains live processes using the installation; keep all runtime inspection read-only. Preserve manually specified security-fix and migration metadata while deriving highlights from the exact current changelog section.",
117
- "Updated dependencies [a887d1c]"
115
+ "后台自动更新:daemon 托管安装改为稳定 launcher + 旁路版本目录(versions/<x.y.z>),每 6h 检查 npm、空闲窗口切换、健康检查失败自动回滚;旧 daemon 首次启动自动迁移;`update` 命令在 launcher 模式下走同一 stage 路径。`update.autoUpdate: false` 或 `XIAOJIU_BRIDGE_NO_UPDATE_CHECK=1` 可关闭。"
118
116
  ],
119
117
  "breakingChanges": [],
120
118
  "securityFix": false,