@saltpub/xiaojiu-agent-bridge 0.1.6 → 0.1.8

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,182 @@
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
+ var BOOT_READY_TIMEOUT_MS = 9e4;
26
+ function readBootReadyTimeoutMs(env = process.env) {
27
+ const raw = Number(env.XIAOJIU_BRIDGE_BOOT_TIMEOUT_MS);
28
+ return Number.isSafeInteger(raw) && raw > 0 ? raw : BOOT_READY_TIMEOUT_MS;
29
+ }
30
+ function logline(message) {
31
+ try {
32
+ mkdirSync(updateDir, { recursive: true });
33
+ appendFileSync(logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${message}
34
+ `);
35
+ } catch {
36
+ }
37
+ }
38
+ function readJson(file) {
39
+ try {
40
+ return JSON.parse(readFileSync(file, "utf8"));
41
+ } catch {
42
+ return void 0;
43
+ }
44
+ }
45
+ function writeJsonAtomic(file, value) {
46
+ mkdirSync(dirname(file), { recursive: true });
47
+ const tmp = `${file}.tmp-${process.pid}`;
48
+ writeFileSync(tmp, `${JSON.stringify(value, null, 2)}
49
+ `, { mode: 384 });
50
+ renameSync(tmp, file);
51
+ }
52
+ function cliEntryOf(dir) {
53
+ return join(dir, "node_modules", ...PACKAGE_NAME.split("/"), "dist", "cli.js");
54
+ }
55
+ function applyPending() {
56
+ const pending = readJson(pendingFile);
57
+ if (!pending || typeof pending.version !== "string" || typeof pending.dir !== "string") return;
58
+ if (!existsSync(cliEntryOf(pending.dir))) {
59
+ logline(`pending ${pending.version} has no dist/cli.js; dropping`);
60
+ rmSync(pendingFile, { force: true });
61
+ return;
62
+ }
63
+ const current = readJson(currentFile);
64
+ const next = {
65
+ version: pending.version,
66
+ dir: pending.dir,
67
+ ...current && typeof current.version === "string" ? { previous: { version: current.version, dir: current.dir } } : {}
68
+ };
69
+ writeJsonAtomic(currentFile, next);
70
+ rmSync(pendingFile, { force: true });
71
+ logline(`switched ${current?.version ?? "(none)"} -> ${pending.version}`);
72
+ }
73
+ function markBad(version) {
74
+ const bad = readJson(badFile);
75
+ const versions = Array.isArray(bad?.versions) ? bad.versions.filter((v) => typeof v === "string") : [];
76
+ if (!versions.includes(version)) versions.push(version);
77
+ writeJsonAtomic(badFile, { versions });
78
+ }
79
+ function sleep(ms) {
80
+ return new Promise((resolve) => {
81
+ setTimeout(resolve, ms);
82
+ });
83
+ }
84
+ async function main() {
85
+ const childArgs = process.argv.slice(2);
86
+ let child;
87
+ let quitting = false;
88
+ for (const signal of ["SIGINT", "SIGTERM"]) {
89
+ process.on(signal, () => {
90
+ quitting = true;
91
+ child?.kill(signal);
92
+ });
93
+ }
94
+ for (; ; ) {
95
+ applyPending();
96
+ const current = readJson(currentFile);
97
+ if (!current || typeof current.version !== "string" || typeof current.dir !== "string") {
98
+ logline("no usable current.json; supervisor exiting");
99
+ process.exit(1);
100
+ }
101
+ if (!existsSync(cliEntryOf(current.dir))) {
102
+ const previous2 = current.previous;
103
+ if (previous2 && existsSync(cliEntryOf(previous2.dir))) {
104
+ logline(`current ${current.version} lost its files; reverting to ${previous2.version}`);
105
+ writeJsonAtomic(currentFile, { version: previous2.version, dir: previous2.dir });
106
+ continue;
107
+ }
108
+ logline(`current ${current.version} lost its files and no previous exists; supervisor exiting`);
109
+ process.exit(1);
110
+ }
111
+ const prior = readJson(bootFile);
112
+ const attempts = prior?.version === current.version && typeof prior.attempts === "number" ? prior.attempts : 0;
113
+ const boot = {
114
+ version: current.version,
115
+ ready: false,
116
+ attempts,
117
+ pid: process.pid,
118
+ startedAt: (/* @__PURE__ */ new Date()).toISOString()
119
+ };
120
+ writeJsonAtomic(bootFile, boot);
121
+ logline(`starting ${current.version} (attempt ${attempts + 1})`);
122
+ child = spawn(process.execPath, [cliEntryOf(current.dir), ...childArgs], {
123
+ stdio: "inherit",
124
+ env: {
125
+ ...process.env,
126
+ [ENV_LAUNCHER]: "1",
127
+ [ENV_VERSION_DIR]: current.dir,
128
+ [ENV_BOOT_FILE]: bootFile
129
+ }
130
+ });
131
+ const bootReadyTimeoutMs = readBootReadyTimeoutMs();
132
+ const deadline = setTimeout(() => {
133
+ const after2 = readJson(bootFile);
134
+ if (after2?.version === current.version && after2.ready === true) return;
135
+ logline(`child not ready after ${bootReadyTimeoutMs}ms; killing the wedged boot`);
136
+ try {
137
+ child?.kill("SIGTERM");
138
+ } catch {
139
+ }
140
+ setTimeout(() => {
141
+ try {
142
+ child?.kill("SIGKILL");
143
+ } catch {
144
+ }
145
+ }, 5e3).unref();
146
+ }, bootReadyTimeoutMs);
147
+ deadline.unref?.();
148
+ const code = await new Promise((resolve) => {
149
+ child?.on("exit", (exitCode, signal) => {
150
+ resolve(exitCode ?? (signal ? 1 : 0));
151
+ });
152
+ });
153
+ clearTimeout(deadline);
154
+ child = void 0;
155
+ if (quitting) process.exit(0);
156
+ if (code === SWITCH_EXIT_CODE) {
157
+ logline("child requested version switch");
158
+ continue;
159
+ }
160
+ const after = readJson(bootFile);
161
+ if (after?.ready === true) {
162
+ logline(`child exited (code ${code}) after ready; restarting`);
163
+ await sleep(CRASH_BACKOFF_MS);
164
+ continue;
165
+ }
166
+ const nextAttempts = attempts + 1;
167
+ writeJsonAtomic(bootFile, { ...boot, attempts: nextAttempts });
168
+ logline(`child exited (code ${code}) before ready; attempt ${nextAttempts}`);
169
+ const previous = current.previous;
170
+ if (nextAttempts >= MAX_BOOT_ATTEMPTS && previous && existsSync(cliEntryOf(previous.dir))) {
171
+ markBad(current.version);
172
+ logline(`${current.version} failed ${nextAttempts} boots; reverted to ${previous.version} and marked bad`);
173
+ writeJsonAtomic(currentFile, { version: previous.version, dir: previous.dir });
174
+ continue;
175
+ }
176
+ await sleep(Math.min(CRASH_BACKOFF_MS * 2 ** nextAttempts, BOOT_FAIL_MAX_BACKOFF_MS));
177
+ }
178
+ }
179
+ main().catch((err) => {
180
+ logline(`supervisor fatal: ${err instanceof Error ? err.stack ?? err.message : String(err)}`);
181
+ process.exit(1);
182
+ });
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.8",
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,8 @@
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
+ "launcher 新增启动超时:child 启动 90 秒后仍未写 `boot.json` 的 ready 标记(hang 住不退出的坏启动)会被杀掉并按一次未 ready 失败计入 attempts,连续两次后照常回退 previous 并标记 bad——此前这种 wedged 启动会让监督循环永久卡住。`XIAOJIU_BRIDGE_BOOT_TIMEOUT_MS` 可覆盖该时长(主要供测试)。",
116
+ "`update` 不再要求手动停止空闲的 daemon:无会话运行时自动停止后台服务 → 安装新版本 → 重新拉起(npm 失败自动回滚服务);有会话运行时两条路径都拒绝并不动任何文件(listen sidecar 新增 `activeRuns` 跨进程计数)。前台 `run`/控制台进程仍需手动停止。"
118
117
  ],
119
118
  "breakingChanges": [],
120
119
  "securityFix": false,