@saltpub/xiaojiu-agent-bridge 0.1.8 → 0.1.10
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/CHANGELOG.md +26 -1
- package/README.md +167 -166
- package/dist/cli.js +2027 -872
- package/dist/launcher.js +3 -1
- package/package.json +2 -3
package/dist/cli.js
CHANGED
|
@@ -20,6 +20,386 @@ var manifest = JSON.parse(readFileSync(packageJsonPath, "utf8"));
|
|
|
20
20
|
var packageName = manifest.name;
|
|
21
21
|
var version = manifest.version;
|
|
22
22
|
|
|
23
|
+
// src/selfupdate/install.ts
|
|
24
|
+
import { existsSync as existsSync2, readFileSync as readFileSync3 } from "fs";
|
|
25
|
+
import { dirname as dirname3, join as join5 } from "path";
|
|
26
|
+
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
27
|
+
|
|
28
|
+
// src/config/app-paths.ts
|
|
29
|
+
import { homedir } from "os";
|
|
30
|
+
import { join as join2 } from "path";
|
|
31
|
+
var DEFAULT_PROFILE = "claude";
|
|
32
|
+
function resolveAppPaths(opts = {}) {
|
|
33
|
+
const rootDir = opts.rootDir ?? process.env.XIAOJIU_BRIDGE_HOME ?? join2(homedir(), ".xiaojiu-agent-bridge");
|
|
34
|
+
const profile2 = normalizeProfileName(opts.profile ?? DEFAULT_PROFILE);
|
|
35
|
+
const profileDir = join2(rootDir, "profiles", profile2);
|
|
36
|
+
const registryDir = join2(rootDir, "registry");
|
|
37
|
+
const userLockDir = join2(registryDir, "locks");
|
|
38
|
+
return {
|
|
39
|
+
rootDir,
|
|
40
|
+
profile: profile2,
|
|
41
|
+
profileDir,
|
|
42
|
+
defaultWorkspaceDir: join2(`${rootDir}-workspaces`, profile2, "default"),
|
|
43
|
+
configFile: join2(rootDir, "config.json"),
|
|
44
|
+
activeProfileFile: join2(rootDir, "active-profile"),
|
|
45
|
+
sessionsFile: join2(profileDir, "sessions.json"),
|
|
46
|
+
workspacesFile: join2(profileDir, "workspaces.json"),
|
|
47
|
+
promptsFile: join2(profileDir, "prompts.json"),
|
|
48
|
+
secretsFile: join2(profileDir, "secrets.enc"),
|
|
49
|
+
keystoreSaltFile: join2(profileDir, ".keystore.salt"),
|
|
50
|
+
secretsGetterScript: join2(rootDir, "secrets-getter"),
|
|
51
|
+
mediaDir: join2(profileDir, "media"),
|
|
52
|
+
logsDir: join2(profileDir, "logs"),
|
|
53
|
+
uiFile: join2(profileDir, "ui.json"),
|
|
54
|
+
hostUiFile: join2(rootDir, "ui.json"),
|
|
55
|
+
hostLogsDir: join2(rootDir, "logs"),
|
|
56
|
+
hostLockFile: join2(userLockDir, "supervisor.lock"),
|
|
57
|
+
updateStateFile: join2(rootDir, "update-state.json"),
|
|
58
|
+
updateDir: join2(rootDir, "update"),
|
|
59
|
+
versionsDir: join2(rootDir, "versions"),
|
|
60
|
+
launcherDir: join2(rootDir, "launcher"),
|
|
61
|
+
launcherFile: join2(rootDir, "launcher", "launcher.mjs"),
|
|
62
|
+
currentVersionFile: join2(rootDir, "update", "current.json"),
|
|
63
|
+
pendingVersionFile: join2(rootDir, "update", "pending.json"),
|
|
64
|
+
bootStateFile: join2(rootDir, "update", "boot.json"),
|
|
65
|
+
badVersionsFile: join2(rootDir, "update", "bad.json"),
|
|
66
|
+
stageLockFile: join2(rootDir, "update", "stage.lock"),
|
|
67
|
+
selfUpdateLogFile: join2(rootDir, "update", "self-update.log"),
|
|
68
|
+
registryDir,
|
|
69
|
+
userRegistryFile: join2(registryDir, "processes.json"),
|
|
70
|
+
userLockDir,
|
|
71
|
+
profileLockFile: join2(userLockDir, "profile", `${profile2}.lock`),
|
|
72
|
+
appLockFile: (appId) => join2(userLockDir, "app", `${lockSafeName(appId)}.lock`)
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
function normalizeProfileName(profile2) {
|
|
76
|
+
const trimmed = profile2.trim();
|
|
77
|
+
if (!trimmed) throw new Error("profile name is required");
|
|
78
|
+
if (/[\u0000-\u001f\s/\\:*?"<>|]/.test(trimmed) || trimmed === "." || trimmed === "..") {
|
|
79
|
+
throw new Error(`invalid profile name: ${profile2}`);
|
|
80
|
+
}
|
|
81
|
+
return trimmed;
|
|
82
|
+
}
|
|
83
|
+
function lockSafeName(value) {
|
|
84
|
+
return value.replace(/[^A-Za-z0-9._-]/g, "_");
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// src/config/paths.ts
|
|
88
|
+
var appPaths = resolveAppPaths();
|
|
89
|
+
var paths = {
|
|
90
|
+
...appPaths,
|
|
91
|
+
appDir: appPaths.rootDir,
|
|
92
|
+
cacheDir: appPaths.rootDir,
|
|
93
|
+
processesFile: appPaths.userRegistryFile
|
|
94
|
+
/**
|
|
95
|
+
* Thin shell wrapper that exec-provider consumers invoke
|
|
96
|
+
* to resolve secrets from the bridge's encrypted store.
|
|
97
|
+
* Written user-owned and non-symlinked so it passes the
|
|
98
|
+
* AssertSecurePath audit on machines where `node` is a Homebrew/Volta
|
|
99
|
+
* symlink or root-owned (`/usr/bin/node`). Wrapper internals do the
|
|
100
|
+
* `node ... secrets get` invocation; the wrapper is the audited path.
|
|
101
|
+
*/
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
// src/selfupdate/store.ts
|
|
105
|
+
import { readFileSync as readFileSync2 } from "fs";
|
|
106
|
+
import { mkdir as mkdir2, readdir, readFile, rm as rm2 } from "fs/promises";
|
|
107
|
+
import { dirname as dirname2, join as join4 } from "path";
|
|
108
|
+
|
|
109
|
+
// src/platform/atomic-write.ts
|
|
110
|
+
import { randomBytes } from "crypto";
|
|
111
|
+
import { chmod, mkdir, open, rm } from "fs/promises";
|
|
112
|
+
import { basename, dirname, join as join3 } from "path";
|
|
113
|
+
import { promisify } from "util";
|
|
114
|
+
import gracefulFs from "graceful-fs";
|
|
115
|
+
var gracefulRename = promisify(gracefulFs.rename);
|
|
116
|
+
var DEFAULT_RENAME_ATTEMPTS = 5;
|
|
117
|
+
var DEFAULT_RETRY_DELAY_MS = 25;
|
|
118
|
+
async function writeFileAtomic(path4, data, opts = {}) {
|
|
119
|
+
await mkdir(dirname(path4), { recursive: true });
|
|
120
|
+
const tmp = join3(
|
|
121
|
+
dirname(path4),
|
|
122
|
+
`.${basename(path4)}.tmp-${process.pid}-${Date.now()}-${randomBytes(3).toString("hex")}`
|
|
123
|
+
);
|
|
124
|
+
try {
|
|
125
|
+
const handle2 = await open(tmp, "w", opts.mode ?? 384);
|
|
126
|
+
try {
|
|
127
|
+
await handle2.writeFile(data);
|
|
128
|
+
try {
|
|
129
|
+
await handle2.sync();
|
|
130
|
+
} catch (err) {
|
|
131
|
+
if (!isIgnorableWindowsFsyncError(err)) throw err;
|
|
132
|
+
}
|
|
133
|
+
} finally {
|
|
134
|
+
await handle2.close();
|
|
135
|
+
}
|
|
136
|
+
await chmod(tmp, opts.mode ?? 384);
|
|
137
|
+
await renameWithRetry(tmp, path4, opts);
|
|
138
|
+
await fsyncDir(dirname(path4));
|
|
139
|
+
} catch (err) {
|
|
140
|
+
await rm(tmp, { force: true }).catch(() => {
|
|
141
|
+
});
|
|
142
|
+
throw err;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
async function renameWithRetry(from, to, opts) {
|
|
146
|
+
const maxAttempts = opts.maxRenameAttempts ?? DEFAULT_RENAME_ATTEMPTS;
|
|
147
|
+
const delayMs = opts.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS;
|
|
148
|
+
const rename4 = opts.rename ?? ((src, dest, fallback) => fallback(src, dest));
|
|
149
|
+
let lastErr;
|
|
150
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
151
|
+
try {
|
|
152
|
+
await rename4(from, to, gracefulRename);
|
|
153
|
+
return;
|
|
154
|
+
} catch (err) {
|
|
155
|
+
lastErr = err;
|
|
156
|
+
if (!isTransientRenameError(err) || attempt === maxAttempts) break;
|
|
157
|
+
await sleep(delayMs * attempt);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
throw lastErr;
|
|
161
|
+
}
|
|
162
|
+
function isTransientRenameError(err) {
|
|
163
|
+
const code = err?.code;
|
|
164
|
+
return code === "EPERM" || code === "EBUSY";
|
|
165
|
+
}
|
|
166
|
+
function isIgnorableWindowsFsyncError(err) {
|
|
167
|
+
return process.platform === "win32" && err?.code === "EPERM";
|
|
168
|
+
}
|
|
169
|
+
async function fsyncDir(path4) {
|
|
170
|
+
try {
|
|
171
|
+
const handle2 = await open(path4, "r");
|
|
172
|
+
try {
|
|
173
|
+
await handle2.sync();
|
|
174
|
+
} finally {
|
|
175
|
+
await handle2.close();
|
|
176
|
+
}
|
|
177
|
+
} catch {
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
function sleep(ms) {
|
|
181
|
+
return new Promise((resolve5) => setTimeout(resolve5, ms));
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// src/selfupdate/version-check.ts
|
|
185
|
+
var REGISTRY_URL = "https://registry.npmjs.org";
|
|
186
|
+
var PASSIVE_REQUEST_TIMEOUT_MS = 1500;
|
|
187
|
+
var EXPLICIT_REQUEST_TIMEOUT_MS = 1e4;
|
|
188
|
+
function compareVersions(left, right) {
|
|
189
|
+
const a = parseVersion(left);
|
|
190
|
+
const b = parseVersion(right);
|
|
191
|
+
for (let index = 0; index < 3; index += 1) {
|
|
192
|
+
const difference = (a.numbers[index] ?? 0) - (b.numbers[index] ?? 0);
|
|
193
|
+
if (difference !== 0) return difference;
|
|
194
|
+
}
|
|
195
|
+
if (a.prerelease.length === 0 && b.prerelease.length === 0) return 0;
|
|
196
|
+
if (a.prerelease.length === 0) return 1;
|
|
197
|
+
if (b.prerelease.length === 0) return -1;
|
|
198
|
+
const length = Math.max(a.prerelease.length, b.prerelease.length);
|
|
199
|
+
for (let index = 0; index < length; index += 1) {
|
|
200
|
+
const leftPart = a.prerelease[index];
|
|
201
|
+
const rightPart = b.prerelease[index];
|
|
202
|
+
if (leftPart === void 0) return -1;
|
|
203
|
+
if (rightPart === void 0) return 1;
|
|
204
|
+
if (leftPart === rightPart) continue;
|
|
205
|
+
const leftNumeric = /^\d+$/.test(leftPart);
|
|
206
|
+
const rightNumeric = /^\d+$/.test(rightPart);
|
|
207
|
+
if (leftNumeric && rightNumeric) {
|
|
208
|
+
if (leftPart.length !== rightPart.length) return leftPart.length - rightPart.length;
|
|
209
|
+
return leftPart < rightPart ? -1 : 1;
|
|
210
|
+
}
|
|
211
|
+
if (leftNumeric) return -1;
|
|
212
|
+
if (rightNumeric) return 1;
|
|
213
|
+
return leftPart < rightPart ? -1 : 1;
|
|
214
|
+
}
|
|
215
|
+
return 0;
|
|
216
|
+
}
|
|
217
|
+
function parseUpdateInfo(metadata, currentVersion = version, expectedName = packageName) {
|
|
218
|
+
if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) throw new Error("Invalid npm Registry package metadata");
|
|
219
|
+
const pkg = metadata;
|
|
220
|
+
if (pkg.name !== expectedName || typeof pkg.version !== "string") throw new Error("Invalid npm Registry package identity or version");
|
|
221
|
+
const current = parseVersion(currentVersion);
|
|
222
|
+
const latest = parseVersion(pkg.version);
|
|
223
|
+
if (current.prerelease.length === 0 && latest.prerelease.length > 0) {
|
|
224
|
+
throw new Error("npm Registry latest points to a prerelease; refusing to update a stable installation");
|
|
225
|
+
}
|
|
226
|
+
if (compareVersions(pkg.version, currentVersion) <= 0) return void 0;
|
|
227
|
+
const update = pkg.xiaojiu?.update;
|
|
228
|
+
return {
|
|
229
|
+
currentVersion,
|
|
230
|
+
latestVersion: pkg.version,
|
|
231
|
+
highlights: stringList(update?.highlights),
|
|
232
|
+
breakingChanges: stringList(update?.breakingChanges),
|
|
233
|
+
securityFix: update?.securityFix === true,
|
|
234
|
+
requiresRestart: update?.requiresRestart === true
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
async function fetchUpdateInfo(options = {}) {
|
|
238
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
239
|
+
const name = options.packageName ?? packageName;
|
|
240
|
+
const controller = new AbortController();
|
|
241
|
+
const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? PASSIVE_REQUEST_TIMEOUT_MS);
|
|
242
|
+
try {
|
|
243
|
+
const response = await fetchImpl(`${REGISTRY_URL}/${encodeURIComponent(name)}/latest`, {
|
|
244
|
+
headers: { accept: "application/json" },
|
|
245
|
+
signal: controller.signal
|
|
246
|
+
});
|
|
247
|
+
if (!response.ok) {
|
|
248
|
+
if (options.throwOnError) throw new Error(`npm Registry returned ${response.status}`);
|
|
249
|
+
return void 0;
|
|
250
|
+
}
|
|
251
|
+
const metadata = await response.json();
|
|
252
|
+
return parseUpdateInfo(metadata, options.currentVersion ?? version, name);
|
|
253
|
+
} catch (error) {
|
|
254
|
+
if (options.throwOnError) throw error;
|
|
255
|
+
return void 0;
|
|
256
|
+
} finally {
|
|
257
|
+
clearTimeout(timer);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
function parseVersion(value) {
|
|
261
|
+
const match = value.match(
|
|
262
|
+
/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/
|
|
263
|
+
);
|
|
264
|
+
if (!match || match[0] !== value) throw new Error(`invalid semantic version: ${value}`);
|
|
265
|
+
if (![match[1], match[2], match[3]].every((part) => Number.isSafeInteger(Number(part)))) {
|
|
266
|
+
throw new Error(`invalid semantic version: ${value}`);
|
|
267
|
+
}
|
|
268
|
+
return {
|
|
269
|
+
numbers: [Number(match[1]), Number(match[2]), Number(match[3])],
|
|
270
|
+
prerelease: match[4]?.split(".") ?? []
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
function stringList(value) {
|
|
274
|
+
if (!Array.isArray(value)) return [];
|
|
275
|
+
return value.filter((item) => typeof item === "string").map((item) => item.replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").trim().slice(0, 200)).filter((item) => item.length > 0).slice(0, 5);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// src/selfupdate/store.ts
|
|
279
|
+
function updateLayout(rootDir) {
|
|
280
|
+
return {
|
|
281
|
+
updateDir: join4(rootDir, "update"),
|
|
282
|
+
versionsDir: join4(rootDir, "versions"),
|
|
283
|
+
launcherDir: join4(rootDir, "launcher"),
|
|
284
|
+
launcherFile: join4(rootDir, "launcher", "launcher.mjs"),
|
|
285
|
+
currentVersionFile: join4(rootDir, "update", "current.json"),
|
|
286
|
+
pendingVersionFile: join4(rootDir, "update", "pending.json"),
|
|
287
|
+
bootStateFile: join4(rootDir, "update", "boot.json"),
|
|
288
|
+
badVersionsFile: join4(rootDir, "update", "bad.json"),
|
|
289
|
+
stageLockFile: join4(rootDir, "update", "stage.lock"),
|
|
290
|
+
selfUpdateLogFile: join4(rootDir, "update", "self-update.log")
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
function versionDir(layout, version3) {
|
|
294
|
+
return join4(layout.versionsDir, version3);
|
|
295
|
+
}
|
|
296
|
+
function packageDirOf(installRoot, name = packageName) {
|
|
297
|
+
return join4(installRoot, "node_modules", ...name.split("/"));
|
|
298
|
+
}
|
|
299
|
+
async function readJson(file) {
|
|
300
|
+
try {
|
|
301
|
+
return JSON.parse(await readFile(file, "utf8"));
|
|
302
|
+
} catch {
|
|
303
|
+
return void 0;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
async function writeJson(file, value) {
|
|
307
|
+
await mkdir2(dirname2(file), { recursive: true });
|
|
308
|
+
await writeFileAtomic(file, `${JSON.stringify(value, null, 2)}
|
|
309
|
+
`, { mode: 384 });
|
|
310
|
+
}
|
|
311
|
+
function isPointer(value) {
|
|
312
|
+
if (!value || typeof value !== "object") return false;
|
|
313
|
+
const v = value;
|
|
314
|
+
return typeof v.version === "string" && typeof v.dir === "string";
|
|
315
|
+
}
|
|
316
|
+
function readCurrent(layout) {
|
|
317
|
+
return readJson(layout.currentVersionFile).then((v) => v && isPointer(v) ? v : void 0);
|
|
318
|
+
}
|
|
319
|
+
function readCurrentSync(layout) {
|
|
320
|
+
try {
|
|
321
|
+
const value = JSON.parse(readFileSync2(layout.currentVersionFile, "utf8"));
|
|
322
|
+
return value && isPointer(value) ? value : void 0;
|
|
323
|
+
} catch {
|
|
324
|
+
return void 0;
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
function writeCurrent(layout, pointer) {
|
|
328
|
+
return writeJson(layout.currentVersionFile, pointer);
|
|
329
|
+
}
|
|
330
|
+
function writePending(layout, pending) {
|
|
331
|
+
return writeJson(layout.pendingVersionFile, pending);
|
|
332
|
+
}
|
|
333
|
+
async function readBadVersions(layout) {
|
|
334
|
+
const bad = await readJson(layout.badVersionsFile);
|
|
335
|
+
return Array.isArray(bad?.versions) ? bad.versions.filter((v) => typeof v === "string") : [];
|
|
336
|
+
}
|
|
337
|
+
async function gcVersions(layout, keep = 3) {
|
|
338
|
+
const current = await readCurrent(layout);
|
|
339
|
+
const protectedDirs = new Set(
|
|
340
|
+
[current?.dir, current?.previous?.dir].filter((d) => typeof d === "string")
|
|
341
|
+
);
|
|
342
|
+
let entries;
|
|
343
|
+
try {
|
|
344
|
+
entries = await readdir(layout.versionsDir);
|
|
345
|
+
} catch {
|
|
346
|
+
return [];
|
|
347
|
+
}
|
|
348
|
+
const removed = [];
|
|
349
|
+
const valid = [];
|
|
350
|
+
for (const name of entries) {
|
|
351
|
+
const dir = join4(layout.versionsDir, name);
|
|
352
|
+
if (!/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(name)) {
|
|
353
|
+
if (!protectedDirs.has(dir)) {
|
|
354
|
+
await rm2(dir, { recursive: true, force: true, maxRetries: 5 });
|
|
355
|
+
removed.push(dir);
|
|
356
|
+
}
|
|
357
|
+
continue;
|
|
358
|
+
}
|
|
359
|
+
if (!protectedDirs.has(dir)) valid.push({ name, dir });
|
|
360
|
+
}
|
|
361
|
+
const dirs = valid.sort((a, b) => compareVersions(a.name, b.name)).reverse().map((entry) => entry.dir);
|
|
362
|
+
for (const dir of dirs.slice(Math.max(keep - protectedDirs.size, 0))) {
|
|
363
|
+
await rm2(dir, { recursive: true, force: true, maxRetries: 5 });
|
|
364
|
+
removed.push(dir);
|
|
365
|
+
}
|
|
366
|
+
return removed;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
// src/selfupdate/install.ts
|
|
370
|
+
function resolveInstall(options = {}) {
|
|
371
|
+
const pkgDir = options.pkgDir ?? invokingPackageDir();
|
|
372
|
+
const own = readVersionAt(pkgDir) ?? { version, dir: pkgDir };
|
|
373
|
+
if (existsSync2(join5(pkgDir, ".git"))) return { ...own, source: "checkout" };
|
|
374
|
+
const pointer = readCurrentSync(updateLayout(options.rootDir ?? paths.rootDir));
|
|
375
|
+
if (pointer) {
|
|
376
|
+
const pointed = readVersionAt(packageDirOf(pointer.dir));
|
|
377
|
+
if (pointed) return { ...pointed, source: "pointer" };
|
|
378
|
+
}
|
|
379
|
+
return { ...own, source: "bootstrap" };
|
|
380
|
+
}
|
|
381
|
+
function invokingPackageDir() {
|
|
382
|
+
let dir = dirname3(fileURLToPath2(import.meta.url));
|
|
383
|
+
for (; ; ) {
|
|
384
|
+
if (readVersionAt(dir)) return dir;
|
|
385
|
+
const parent = dirname3(dir);
|
|
386
|
+
if (parent === dir) return dir;
|
|
387
|
+
dir = parent;
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
function readVersionAt(dir) {
|
|
391
|
+
try {
|
|
392
|
+
const manifest2 = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
|
|
393
|
+
if (typeof manifest2 !== "object" || manifest2 === null) return void 0;
|
|
394
|
+
const name = "name" in manifest2 ? manifest2.name : void 0;
|
|
395
|
+
const found = "version" in manifest2 ? manifest2.version : void 0;
|
|
396
|
+
if (name !== packageName || typeof found !== "string" || found.length === 0) return void 0;
|
|
397
|
+
return { version: found, dir };
|
|
398
|
+
} catch {
|
|
399
|
+
return void 0;
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
|
|
23
403
|
// src/platform/spawn.ts
|
|
24
404
|
import crossSpawn from "cross-spawn";
|
|
25
405
|
import { execFile } from "child_process";
|
|
@@ -176,8 +556,8 @@ async function checkAgentVersion(input) {
|
|
|
176
556
|
);
|
|
177
557
|
return;
|
|
178
558
|
}
|
|
179
|
-
const
|
|
180
|
-
if (!
|
|
559
|
+
const version3 = (stdout.trim() || stderr.trim()).split("\n")[0]?.trim();
|
|
560
|
+
if (!version3) {
|
|
181
561
|
reject4(
|
|
182
562
|
new AgentPreflightError({
|
|
183
563
|
...base(),
|
|
@@ -188,7 +568,7 @@ async function checkAgentVersion(input) {
|
|
|
188
568
|
);
|
|
189
569
|
return;
|
|
190
570
|
}
|
|
191
|
-
resolve5(
|
|
571
|
+
resolve5(version3);
|
|
192
572
|
});
|
|
193
573
|
});
|
|
194
574
|
});
|
|
@@ -415,248 +795,96 @@ function positiveInt(value) {
|
|
|
415
795
|
var DEFAULT_SEND_MESSAGE_API_VERSION = "v2";
|
|
416
796
|
function isComplete(cfg) {
|
|
417
797
|
const app = cfg.accounts?.app;
|
|
418
|
-
return Boolean(app?.id && hasSecret(app?.secret) && cfg.webhook);
|
|
419
|
-
}
|
|
420
|
-
function hasSecret(s) {
|
|
421
|
-
if (!s) return false;
|
|
422
|
-
if (typeof s === "string") return s.length > 0;
|
|
423
|
-
return Boolean(s.source && s.id);
|
|
424
|
-
}
|
|
425
|
-
function isSecretRef(s) {
|
|
426
|
-
return typeof s === "object" && s !== null;
|
|
427
|
-
}
|
|
428
|
-
function secretKeyForApp(appId) {
|
|
429
|
-
return `app-${appId}`;
|
|
430
|
-
}
|
|
431
|
-
function getMessageReplyMode(cfg) {
|
|
432
|
-
const raw = cfg.preferences?.messageReply;
|
|
433
|
-
if (raw === "text" && cfg.preferences?.messageReplyMigrated !== true) {
|
|
434
|
-
return "markdown";
|
|
435
|
-
}
|
|
436
|
-
if (raw === "card" || raw === "markdown" || raw === "text") return raw;
|
|
437
|
-
return "markdown";
|
|
438
|
-
}
|
|
439
|
-
function getShowToolCalls(cfg) {
|
|
440
|
-
return cfg.preferences?.showToolCalls === true;
|
|
441
|
-
}
|
|
442
|
-
function getAutoUpdateEnabled(cfg) {
|
|
443
|
-
return cfg.update?.autoUpdate !== false;
|
|
444
|
-
}
|
|
445
|
-
function getThinkingLevel(preferences) {
|
|
446
|
-
const raw = preferences?.thinking;
|
|
447
|
-
return raw && isThinkingLevel(raw) ? raw : "off";
|
|
448
|
-
}
|
|
449
|
-
function getCotMessages(cfg) {
|
|
450
|
-
const raw = cfg.preferences?.cotMessages;
|
|
451
|
-
if (raw === "off") return "off";
|
|
452
|
-
if (raw === "brief" || raw === "simple") return "brief";
|
|
453
|
-
if (raw === "detailed" || raw === "on") return "detailed";
|
|
454
|
-
return "off";
|
|
455
|
-
}
|
|
456
|
-
function getMaxConcurrentRuns(cfg) {
|
|
457
|
-
const raw = cfg.preferences?.maxConcurrentRuns;
|
|
458
|
-
if (typeof raw !== "number" || !Number.isFinite(raw) || raw < 1) return 10;
|
|
459
|
-
return Math.min(Math.floor(raw), 50);
|
|
460
|
-
}
|
|
461
|
-
function getRequireMentionInGroup(cfg) {
|
|
462
|
-
if (cfg.preferences?.requireMentionInGroup !== void 0) {
|
|
463
|
-
return cfg.preferences.requireMentionInGroup !== false;
|
|
464
|
-
}
|
|
465
|
-
const profileAccess = cfg.access;
|
|
466
|
-
if (profileAccess?.requireMentionInGroup !== void 0) {
|
|
467
|
-
return profileAccess.requireMentionInGroup;
|
|
468
|
-
}
|
|
469
|
-
return true;
|
|
470
|
-
}
|
|
471
|
-
function getAgentStopGraceMs(cfg) {
|
|
472
|
-
const raw = cfg.preferences?.agentStopGraceMs;
|
|
473
|
-
if (typeof raw !== "number" || !Number.isFinite(raw)) return 5e3;
|
|
474
|
-
return Math.min(3e4, Math.max(100, Math.floor(raw)));
|
|
475
|
-
}
|
|
476
|
-
function getSendMessageApiVersion(cfg) {
|
|
477
|
-
return cfg.preferences?.sendMessageApiVersion === "v1" ? "v1" : DEFAULT_SEND_MESSAGE_API_VERSION;
|
|
478
|
-
}
|
|
479
|
-
function getRunIdleTimeoutMs(cfg) {
|
|
480
|
-
const raw = cfg.preferences?.runIdleTimeoutMinutes;
|
|
481
|
-
if (typeof raw !== "number" || !Number.isFinite(raw) || raw <= 0) return void 0;
|
|
482
|
-
const clamped = Math.min(Math.max(Math.floor(raw), 1), 120);
|
|
483
|
-
return clamped * 6e4;
|
|
484
|
-
}
|
|
485
|
-
|
|
486
|
-
// src/cli/commands/update.ts
|
|
487
|
-
import { existsSync as existsSync7 } from "fs";
|
|
488
|
-
import { readFile as readFile7 } from "fs/promises";
|
|
489
|
-
import path3 from "path";
|
|
490
|
-
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
491
|
-
|
|
492
|
-
// src/config/app-paths.ts
|
|
493
|
-
import { homedir } from "os";
|
|
494
|
-
import { join as join2 } from "path";
|
|
495
|
-
var DEFAULT_PROFILE = "claude";
|
|
496
|
-
function resolveAppPaths(opts = {}) {
|
|
497
|
-
const rootDir = opts.rootDir ?? process.env.XIAOJIU_BRIDGE_HOME ?? join2(homedir(), ".xiaojiu-agent-bridge");
|
|
498
|
-
const profile2 = normalizeProfileName(opts.profile ?? DEFAULT_PROFILE);
|
|
499
|
-
const profileDir = join2(rootDir, "profiles", profile2);
|
|
500
|
-
const registryDir = join2(rootDir, "registry");
|
|
501
|
-
const userLockDir = join2(registryDir, "locks");
|
|
502
|
-
return {
|
|
503
|
-
rootDir,
|
|
504
|
-
profile: profile2,
|
|
505
|
-
profileDir,
|
|
506
|
-
defaultWorkspaceDir: join2(`${rootDir}-workspaces`, profile2, "default"),
|
|
507
|
-
configFile: join2(rootDir, "config.json"),
|
|
508
|
-
activeProfileFile: join2(rootDir, "active-profile"),
|
|
509
|
-
sessionsFile: join2(profileDir, "sessions.json"),
|
|
510
|
-
workspacesFile: join2(profileDir, "workspaces.json"),
|
|
511
|
-
promptsFile: join2(profileDir, "prompts.json"),
|
|
512
|
-
secretsFile: join2(profileDir, "secrets.enc"),
|
|
513
|
-
keystoreSaltFile: join2(profileDir, ".keystore.salt"),
|
|
514
|
-
secretsGetterScript: join2(rootDir, "secrets-getter"),
|
|
515
|
-
mediaDir: join2(profileDir, "media"),
|
|
516
|
-
logsDir: join2(profileDir, "logs"),
|
|
517
|
-
uiFile: join2(profileDir, "ui.json"),
|
|
518
|
-
hostUiFile: join2(rootDir, "ui.json"),
|
|
519
|
-
hostLogsDir: join2(rootDir, "logs"),
|
|
520
|
-
hostLockFile: join2(userLockDir, "supervisor.lock"),
|
|
521
|
-
updateStateFile: join2(rootDir, "update-state.json"),
|
|
522
|
-
updateDir: join2(rootDir, "update"),
|
|
523
|
-
versionsDir: join2(rootDir, "versions"),
|
|
524
|
-
launcherDir: join2(rootDir, "launcher"),
|
|
525
|
-
launcherFile: join2(rootDir, "launcher", "launcher.mjs"),
|
|
526
|
-
currentVersionFile: join2(rootDir, "update", "current.json"),
|
|
527
|
-
pendingVersionFile: join2(rootDir, "update", "pending.json"),
|
|
528
|
-
bootStateFile: join2(rootDir, "update", "boot.json"),
|
|
529
|
-
badVersionsFile: join2(rootDir, "update", "bad.json"),
|
|
530
|
-
stageLockFile: join2(rootDir, "update", "stage.lock"),
|
|
531
|
-
selfUpdateLogFile: join2(rootDir, "update", "self-update.log"),
|
|
532
|
-
registryDir,
|
|
533
|
-
userRegistryFile: join2(registryDir, "processes.json"),
|
|
534
|
-
userLockDir,
|
|
535
|
-
profileLockFile: join2(userLockDir, "profile", `${profile2}.lock`),
|
|
536
|
-
appLockFile: (appId) => join2(userLockDir, "app", `${lockSafeName(appId)}.lock`)
|
|
537
|
-
};
|
|
538
|
-
}
|
|
539
|
-
function normalizeProfileName(profile2) {
|
|
540
|
-
const trimmed = profile2.trim();
|
|
541
|
-
if (!trimmed) throw new Error("profile name is required");
|
|
542
|
-
if (/[\u0000-\u001f\s/\\:*?"<>|]/.test(trimmed) || trimmed === "." || trimmed === "..") {
|
|
543
|
-
throw new Error(`invalid profile name: ${profile2}`);
|
|
544
|
-
}
|
|
545
|
-
return trimmed;
|
|
546
|
-
}
|
|
547
|
-
function lockSafeName(value) {
|
|
548
|
-
return value.replace(/[^A-Za-z0-9._-]/g, "_");
|
|
549
|
-
}
|
|
550
|
-
|
|
551
|
-
// src/config/paths.ts
|
|
552
|
-
var appPaths = resolveAppPaths();
|
|
553
|
-
var paths = {
|
|
554
|
-
...appPaths,
|
|
555
|
-
appDir: appPaths.rootDir,
|
|
556
|
-
cacheDir: appPaths.rootDir,
|
|
557
|
-
processesFile: appPaths.userRegistryFile
|
|
558
|
-
/**
|
|
559
|
-
* Thin shell wrapper that exec-provider consumers invoke
|
|
560
|
-
* to resolve secrets from the bridge's encrypted store.
|
|
561
|
-
* Written user-owned and non-symlinked so it passes the
|
|
562
|
-
* AssertSecurePath audit on machines where `node` is a Homebrew/Volta
|
|
563
|
-
* symlink or root-owned (`/usr/bin/node`). Wrapper internals do the
|
|
564
|
-
* `node ... secrets get` invocation; the wrapper is the audited path.
|
|
565
|
-
*/
|
|
566
|
-
};
|
|
567
|
-
|
|
568
|
-
// src/platform/atomic-write.ts
|
|
569
|
-
import { randomBytes } from "crypto";
|
|
570
|
-
import { chmod, mkdir, open, rm } from "fs/promises";
|
|
571
|
-
import { basename, dirname, join as join3 } from "path";
|
|
572
|
-
import { promisify } from "util";
|
|
573
|
-
import gracefulFs from "graceful-fs";
|
|
574
|
-
var gracefulRename = promisify(gracefulFs.rename);
|
|
575
|
-
var DEFAULT_RENAME_ATTEMPTS = 5;
|
|
576
|
-
var DEFAULT_RETRY_DELAY_MS = 25;
|
|
577
|
-
async function writeFileAtomic(path4, data, opts = {}) {
|
|
578
|
-
await mkdir(dirname(path4), { recursive: true });
|
|
579
|
-
const tmp = join3(
|
|
580
|
-
dirname(path4),
|
|
581
|
-
`.${basename(path4)}.tmp-${process.pid}-${Date.now()}-${randomBytes(3).toString("hex")}`
|
|
582
|
-
);
|
|
583
|
-
try {
|
|
584
|
-
const handle2 = await open(tmp, "w", opts.mode ?? 384);
|
|
585
|
-
try {
|
|
586
|
-
await handle2.writeFile(data);
|
|
587
|
-
try {
|
|
588
|
-
await handle2.sync();
|
|
589
|
-
} catch (err) {
|
|
590
|
-
if (!isIgnorableWindowsFsyncError(err)) throw err;
|
|
591
|
-
}
|
|
592
|
-
} finally {
|
|
593
|
-
await handle2.close();
|
|
594
|
-
}
|
|
595
|
-
await chmod(tmp, opts.mode ?? 384);
|
|
596
|
-
await renameWithRetry(tmp, path4, opts);
|
|
597
|
-
await fsyncDir(dirname(path4));
|
|
598
|
-
} catch (err) {
|
|
599
|
-
await rm(tmp, { force: true }).catch(() => {
|
|
600
|
-
});
|
|
601
|
-
throw err;
|
|
602
|
-
}
|
|
798
|
+
return Boolean(app?.id && hasSecret(app?.secret) && cfg.webhook);
|
|
603
799
|
}
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
800
|
+
function hasSecret(s) {
|
|
801
|
+
if (!s) return false;
|
|
802
|
+
if (typeof s === "string") return s.length > 0;
|
|
803
|
+
return Boolean(s.source && s.id);
|
|
804
|
+
}
|
|
805
|
+
function isSecretRef(s) {
|
|
806
|
+
return typeof s === "object" && s !== null;
|
|
807
|
+
}
|
|
808
|
+
function secretKeyForApp(appId) {
|
|
809
|
+
return `app-${appId}`;
|
|
810
|
+
}
|
|
811
|
+
function getMessageReplyMode(cfg) {
|
|
812
|
+
const raw = cfg.preferences?.messageReply;
|
|
813
|
+
if (raw === "text" && cfg.preferences?.messageReplyMigrated !== true) {
|
|
814
|
+
return "markdown";
|
|
618
815
|
}
|
|
619
|
-
|
|
816
|
+
if (raw === "card" || raw === "markdown" || raw === "text") return raw;
|
|
817
|
+
return "markdown";
|
|
620
818
|
}
|
|
621
|
-
function
|
|
622
|
-
|
|
623
|
-
return code === "EPERM" || code === "EBUSY";
|
|
819
|
+
function getShowToolCalls(cfg) {
|
|
820
|
+
return cfg.preferences?.showToolCalls === true;
|
|
624
821
|
}
|
|
625
|
-
function
|
|
626
|
-
return
|
|
822
|
+
function getAutoUpdateEnabled(cfg) {
|
|
823
|
+
return cfg.update?.autoUpdate !== false;
|
|
627
824
|
}
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
825
|
+
function getThinkingLevel(preferences) {
|
|
826
|
+
const raw = preferences?.thinking;
|
|
827
|
+
return raw && isThinkingLevel(raw) ? raw : "off";
|
|
828
|
+
}
|
|
829
|
+
function getCotMessages(cfg) {
|
|
830
|
+
const raw = cfg.preferences?.cotMessages;
|
|
831
|
+
if (raw === "off") return "off";
|
|
832
|
+
if (raw === "brief" || raw === "simple") return "brief";
|
|
833
|
+
if (raw === "detailed" || raw === "on") return "detailed";
|
|
834
|
+
return "off";
|
|
835
|
+
}
|
|
836
|
+
function getMaxConcurrentRuns(cfg) {
|
|
837
|
+
const raw = cfg.preferences?.maxConcurrentRuns;
|
|
838
|
+
if (typeof raw !== "number" || !Number.isFinite(raw) || raw < 1) return 10;
|
|
839
|
+
return Math.min(Math.floor(raw), 50);
|
|
840
|
+
}
|
|
841
|
+
function getRequireMentionInGroup(cfg) {
|
|
842
|
+
if (cfg.preferences?.requireMentionInGroup !== void 0) {
|
|
843
|
+
return cfg.preferences.requireMentionInGroup !== false;
|
|
844
|
+
}
|
|
845
|
+
const profileAccess = cfg.access;
|
|
846
|
+
if (profileAccess?.requireMentionInGroup !== void 0) {
|
|
847
|
+
return profileAccess.requireMentionInGroup;
|
|
637
848
|
}
|
|
849
|
+
return true;
|
|
638
850
|
}
|
|
639
|
-
function
|
|
640
|
-
|
|
851
|
+
function getAgentStopGraceMs(cfg) {
|
|
852
|
+
const raw = cfg.preferences?.agentStopGraceMs;
|
|
853
|
+
if (typeof raw !== "number" || !Number.isFinite(raw)) return 5e3;
|
|
854
|
+
return Math.min(3e4, Math.max(100, Math.floor(raw)));
|
|
855
|
+
}
|
|
856
|
+
function getSendMessageApiVersion(cfg) {
|
|
857
|
+
return cfg.preferences?.sendMessageApiVersion === "v1" ? "v1" : DEFAULT_SEND_MESSAGE_API_VERSION;
|
|
858
|
+
}
|
|
859
|
+
function getRunIdleTimeoutMs(cfg) {
|
|
860
|
+
const raw = cfg.preferences?.runIdleTimeoutMinutes;
|
|
861
|
+
if (typeof raw !== "number" || !Number.isFinite(raw) || raw <= 0) return void 0;
|
|
862
|
+
const clamped = Math.min(Math.max(Math.floor(raw), 1), 120);
|
|
863
|
+
return clamped * 6e4;
|
|
641
864
|
}
|
|
642
865
|
|
|
866
|
+
// src/cli/commands/update.ts
|
|
867
|
+
import { existsSync as existsSync8 } from "fs";
|
|
868
|
+
import { readFile as readFile7 } from "fs/promises";
|
|
869
|
+
import path3 from "path";
|
|
870
|
+
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
871
|
+
|
|
643
872
|
// src/cli/commands/update-safety.ts
|
|
644
|
-
import { readFile as
|
|
873
|
+
import { readFile as readFile5, readdir as readdir4, realpath } from "fs/promises";
|
|
645
874
|
import path2 from "path";
|
|
646
875
|
|
|
647
876
|
// src/daemon/launchd.ts
|
|
648
877
|
import { spawnSync } from "child_process";
|
|
649
|
-
import { existsSync as
|
|
650
|
-
import { mkdir as
|
|
878
|
+
import { existsSync as existsSync4 } from "fs";
|
|
879
|
+
import { mkdir as mkdir3, rm as rm3, writeFile } from "fs/promises";
|
|
651
880
|
import { userInfo } from "os";
|
|
652
|
-
import { dirname as
|
|
881
|
+
import { dirname as dirname5 } from "path";
|
|
653
882
|
|
|
654
883
|
// src/daemon/paths.ts
|
|
655
884
|
import { homedir as homedir2 } from "os";
|
|
656
|
-
import { join as
|
|
885
|
+
import { join as join6 } from "path";
|
|
657
886
|
import { createHash } from "crypto";
|
|
658
887
|
var SERVICE_NAME = "xiaojiu-agent-bridge.bot";
|
|
659
|
-
var SUPERVISOR_SERVICE_ID = "supervisor";
|
|
660
888
|
function serviceProfileId(profile2) {
|
|
661
889
|
const trimmed = profile2.trim();
|
|
662
890
|
if (!trimmed) throw new Error("profile name is required for service id");
|
|
@@ -674,43 +902,43 @@ function launchAgentLabel(profile2 = paths.profile) {
|
|
|
674
902
|
return `ai.${serviceNameForProfile(profile2)}`;
|
|
675
903
|
}
|
|
676
904
|
function launchAgentPlistPath(profile2 = paths.profile) {
|
|
677
|
-
return
|
|
905
|
+
return join6(homedir2(), "Library", "LaunchAgents", `${launchAgentLabel(profile2)}.plist`);
|
|
678
906
|
}
|
|
679
907
|
var SYSTEMD_UNIT_NAME = systemdUnitName();
|
|
680
908
|
function systemdUnitName(profile2 = paths.profile) {
|
|
681
909
|
return `${serviceNameForProfile(profile2)}.service`;
|
|
682
910
|
}
|
|
683
911
|
function systemdUnitPath(profile2 = paths.profile) {
|
|
684
|
-
const base = process.env.XDG_CONFIG_HOME ??
|
|
685
|
-
return
|
|
912
|
+
const base = process.env.XDG_CONFIG_HOME ?? join6(homedir2(), ".config");
|
|
913
|
+
return join6(base, "systemd", "user", systemdUnitName(profile2));
|
|
686
914
|
}
|
|
687
915
|
var WINDOWS_TASK_NAME = windowsTaskName();
|
|
688
916
|
function windowsTaskName(profile2 = paths.profile) {
|
|
689
917
|
return `XiaojiuAgentBridge.Bot.${serviceProfileId(profile2)}`;
|
|
690
918
|
}
|
|
691
919
|
function windowsLauncherCmdPath(profile2 = paths.profile) {
|
|
692
|
-
return
|
|
920
|
+
return join6(paths.appDir, "daemon", serviceProfileId(profile2), "launcher.cmd");
|
|
693
921
|
}
|
|
694
922
|
function windowsLauncherVbsPath(profile2 = paths.profile) {
|
|
695
|
-
return
|
|
923
|
+
return join6(paths.appDir, "daemon", serviceProfileId(profile2), "launcher.vbs");
|
|
696
924
|
}
|
|
697
925
|
function windowsTaskXmlPath(profile2 = paths.profile) {
|
|
698
|
-
return
|
|
926
|
+
return join6(paths.appDir, "daemon", serviceProfileId(profile2), "task.xml");
|
|
699
927
|
}
|
|
700
928
|
function daemonLogDir(profile2 = paths.profile) {
|
|
701
|
-
return
|
|
929
|
+
return join6(resolveAppPaths({ rootDir: paths.rootDir, profile: profile2 }).logsDir, "daemon");
|
|
702
930
|
}
|
|
703
931
|
function daemonStdoutPath(profile2 = paths.profile) {
|
|
704
|
-
return
|
|
932
|
+
return join6(daemonLogDir(profile2), "daemon-stdout.log");
|
|
705
933
|
}
|
|
706
934
|
function daemonStderrPath(profile2 = paths.profile) {
|
|
707
|
-
return
|
|
935
|
+
return join6(daemonLogDir(profile2), "daemon-stderr.log");
|
|
708
936
|
}
|
|
709
937
|
|
|
710
938
|
// src/daemon/launch-spec.ts
|
|
711
|
-
import { existsSync as
|
|
939
|
+
import { existsSync as existsSync3 } from "fs";
|
|
712
940
|
import { createRequire } from "module";
|
|
713
|
-
import { dirname as
|
|
941
|
+
import { dirname as dirname4, resolve } from "path";
|
|
714
942
|
import { pathToFileURL } from "url";
|
|
715
943
|
function resolveDaemonLaunch(argv1 = process.argv[1], override) {
|
|
716
944
|
if (override) return override;
|
|
@@ -721,8 +949,8 @@ function resolveDaemonLaunch(argv1 = process.argv[1], override) {
|
|
|
721
949
|
if (!entryPath.endsWith(".ts")) {
|
|
722
950
|
return { importArgs: [], entryPath };
|
|
723
951
|
}
|
|
724
|
-
const registerHtml = resolve(
|
|
725
|
-
if (!
|
|
952
|
+
const registerHtml = resolve(dirname4(entryPath), "register-html.mjs");
|
|
953
|
+
if (!existsSync3(registerHtml)) {
|
|
726
954
|
throw new Error(
|
|
727
955
|
`cannot install a daemon from TypeScript sources (${entryPath}); missing ${registerHtml}`
|
|
728
956
|
);
|
|
@@ -796,12 +1024,12 @@ async function writePlist(profile2, runArgs = ["run"], launch) {
|
|
|
796
1024
|
channelHome: paths.rootDir
|
|
797
1025
|
});
|
|
798
1026
|
const plistPath = launchAgentPlistPath(profile2);
|
|
799
|
-
await
|
|
800
|
-
await
|
|
1027
|
+
await mkdir3(dirname5(plistPath), { recursive: true });
|
|
1028
|
+
await mkdir3(daemonLogDir(profile2), { recursive: true });
|
|
801
1029
|
await writeFile(plistPath, content, "utf8");
|
|
802
1030
|
}
|
|
803
1031
|
function plistExists(profile2) {
|
|
804
|
-
return
|
|
1032
|
+
return existsSync4(launchAgentPlistPath(profile2));
|
|
805
1033
|
}
|
|
806
1034
|
function userTarget() {
|
|
807
1035
|
return `gui/${userInfo().uid}`;
|
|
@@ -851,14 +1079,14 @@ function describeService(profile2) {
|
|
|
851
1079
|
return r.stdout || r.stderr || "";
|
|
852
1080
|
}
|
|
853
1081
|
async function deletePlist(profile2) {
|
|
854
|
-
await
|
|
1082
|
+
await rm3(launchAgentPlistPath(profile2), { force: true });
|
|
855
1083
|
}
|
|
856
1084
|
|
|
857
1085
|
// src/daemon/schtasks.ts
|
|
858
1086
|
import { spawnSync as spawnSync2 } from "child_process";
|
|
859
|
-
import { existsSync as
|
|
860
|
-
import { mkdir as
|
|
861
|
-
import { dirname as
|
|
1087
|
+
import { existsSync as existsSync5 } from "fs";
|
|
1088
|
+
import { mkdir as mkdir4, rm as rm4, writeFile as writeFile2 } from "fs/promises";
|
|
1089
|
+
import { dirname as dirname6 } from "path";
|
|
862
1090
|
function buildLauncherCmd(inputs) {
|
|
863
1091
|
const runArgs = inputs.runArgs.join(" ");
|
|
864
1092
|
const importArgs = (inputs.importArgs ?? []).map((a) => `"${a}"`).join(" ");
|
|
@@ -943,8 +1171,8 @@ async function writeLauncherScripts(profile2, runArgs = ["run"], launch) {
|
|
|
943
1171
|
runArgs,
|
|
944
1172
|
channelHome: paths.rootDir
|
|
945
1173
|
});
|
|
946
|
-
await
|
|
947
|
-
await
|
|
1174
|
+
await mkdir4(dirname6(cmdPath), { recursive: true });
|
|
1175
|
+
await mkdir4(daemonLogDir(profile2), { recursive: true });
|
|
948
1176
|
await writeFile2(cmdPath, content, "utf8");
|
|
949
1177
|
await writeFile2(vbsPath, buildLauncherVbs(cmdPath), "utf8");
|
|
950
1178
|
await writeFile2(xmlPath, `\uFEFF${buildTaskXml(profile2, vbsPath)}`, { encoding: "utf16le" });
|
|
@@ -1037,16 +1265,16 @@ async function deleteTask(profile2) {
|
|
|
1037
1265
|
windowsLauncherVbsPath(profile2),
|
|
1038
1266
|
windowsTaskXmlPath(profile2)
|
|
1039
1267
|
]) {
|
|
1040
|
-
if (
|
|
1268
|
+
if (existsSync5(path4)) await rm4(path4, { force: true });
|
|
1041
1269
|
}
|
|
1042
1270
|
return r;
|
|
1043
1271
|
}
|
|
1044
1272
|
|
|
1045
1273
|
// src/daemon/systemd.ts
|
|
1046
1274
|
import { spawnSync as spawnSync3 } from "child_process";
|
|
1047
|
-
import { existsSync as
|
|
1048
|
-
import { mkdir as
|
|
1049
|
-
import { dirname as
|
|
1275
|
+
import { existsSync as existsSync6 } from "fs";
|
|
1276
|
+
import { mkdir as mkdir5, rm as rm5, writeFile as writeFile3 } from "fs/promises";
|
|
1277
|
+
import { dirname as dirname7 } from "path";
|
|
1050
1278
|
function buildUnit(inputs) {
|
|
1051
1279
|
const escape = (s) => s.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
|
|
1052
1280
|
const runArgs = inputs.runArgs.join(" ");
|
|
@@ -1083,12 +1311,12 @@ async function writeUnit(profile2, runArgs = ["run"], launch) {
|
|
|
1083
1311
|
channelHome: paths.rootDir
|
|
1084
1312
|
});
|
|
1085
1313
|
const unitPath = systemdUnitPath(profile2);
|
|
1086
|
-
await
|
|
1087
|
-
await
|
|
1314
|
+
await mkdir5(dirname7(unitPath), { recursive: true });
|
|
1315
|
+
await mkdir5(daemonLogDir(profile2), { recursive: true });
|
|
1088
1316
|
await writeFile3(unitPath, content, "utf8");
|
|
1089
1317
|
}
|
|
1090
1318
|
function unitExists(profile2) {
|
|
1091
|
-
return
|
|
1319
|
+
return existsSync6(systemdUnitPath(profile2));
|
|
1092
1320
|
}
|
|
1093
1321
|
function runSystemctl(args) {
|
|
1094
1322
|
const r = spawnSync3("systemctl", ["--user", ...args], { encoding: "utf8" });
|
|
@@ -1135,7 +1363,7 @@ async function waitUntilInactive(profile2, timeoutMs = 5e3) {
|
|
|
1135
1363
|
return false;
|
|
1136
1364
|
}
|
|
1137
1365
|
async function deleteUnit(profile2) {
|
|
1138
|
-
await
|
|
1366
|
+
await rm5(systemdUnitPath(profile2), { force: true });
|
|
1139
1367
|
}
|
|
1140
1368
|
|
|
1141
1369
|
// src/daemon/service-adapter.ts
|
|
@@ -1246,8 +1474,8 @@ function getServiceAdapter(profile2 = "claude", runArgs = ["run"], launch) {
|
|
|
1246
1474
|
}
|
|
1247
1475
|
|
|
1248
1476
|
// src/runtime/locks.ts
|
|
1249
|
-
import { chmod as chmod2, mkdir as
|
|
1250
|
-
import { dirname as
|
|
1477
|
+
import { chmod as chmod2, mkdir as mkdir6, readFile as readFile2, rm as rm6, unlink, writeFile as writeFile4 } from "fs/promises";
|
|
1478
|
+
import { dirname as dirname8 } from "path";
|
|
1251
1479
|
import * as lockfile from "proper-lockfile";
|
|
1252
1480
|
|
|
1253
1481
|
// src/config/permissions.ts
|
|
@@ -1680,9 +1908,27 @@ async function acquireProfileRuntimeLock(paths2, agentKind) {
|
|
|
1680
1908
|
function runtimeLockMetaFile(target) {
|
|
1681
1909
|
return `${target}.meta.json`;
|
|
1682
1910
|
}
|
|
1911
|
+
async function breakDeadRuntimeLock(target) {
|
|
1912
|
+
const meta = await readRuntimeLockMeta(target);
|
|
1913
|
+
if (!meta || pidAlive(meta.pid)) return false;
|
|
1914
|
+
await unlink(runtimeLockMetaFile(target)).catch(() => {
|
|
1915
|
+
});
|
|
1916
|
+
await rm6(`${target}.lock`, { recursive: true, force: true }).catch(() => {
|
|
1917
|
+
});
|
|
1918
|
+
return true;
|
|
1919
|
+
}
|
|
1920
|
+
function pidAlive(pid) {
|
|
1921
|
+
try {
|
|
1922
|
+
process.kill(pid, 0);
|
|
1923
|
+
return true;
|
|
1924
|
+
} catch (err) {
|
|
1925
|
+
const code = err.code;
|
|
1926
|
+
return code === "EPERM" || code === "EACCES";
|
|
1927
|
+
}
|
|
1928
|
+
}
|
|
1683
1929
|
async function readRuntimeLockMeta(target) {
|
|
1684
1930
|
try {
|
|
1685
|
-
const parsed = JSON.parse(await
|
|
1931
|
+
const parsed = JSON.parse(await readFile2(runtimeLockMetaFile(target), "utf8"));
|
|
1686
1932
|
return isRuntimeLockMeta(parsed) ? parsed : void 0;
|
|
1687
1933
|
} catch (err) {
|
|
1688
1934
|
if (err.code === "ENOENT") return void 0;
|
|
@@ -1708,7 +1954,7 @@ async function checkRuntimeLock(target) {
|
|
|
1708
1954
|
}
|
|
1709
1955
|
}
|
|
1710
1956
|
async function acquireRuntimeLock(meta) {
|
|
1711
|
-
await
|
|
1957
|
+
await mkdir6(dirname8(meta.target), { recursive: true });
|
|
1712
1958
|
await writeFile4(meta.target, "", { flag: "a", mode: 384 });
|
|
1713
1959
|
await chmod2(meta.target, 384);
|
|
1714
1960
|
let release;
|
|
@@ -1752,17 +1998,17 @@ function isRuntimeLockMeta(value) {
|
|
|
1752
1998
|
import { randomBytes as randomBytes2 } from "crypto";
|
|
1753
1999
|
import {
|
|
1754
2000
|
closeSync,
|
|
1755
|
-
existsSync as
|
|
2001
|
+
existsSync as existsSync7,
|
|
1756
2002
|
fsyncSync,
|
|
1757
2003
|
mkdirSync,
|
|
1758
2004
|
openSync,
|
|
1759
|
-
readFileSync as
|
|
2005
|
+
readFileSync as readFileSync4,
|
|
1760
2006
|
renameSync,
|
|
1761
2007
|
unlinkSync,
|
|
1762
2008
|
writeFileSync
|
|
1763
2009
|
} from "fs";
|
|
1764
|
-
import { mkdir as
|
|
1765
|
-
import { basename as basename2, dirname as
|
|
2010
|
+
import { mkdir as mkdir7, writeFile as writeFile5 } from "fs/promises";
|
|
2011
|
+
import { basename as basename2, dirname as dirname9, join as join7 } from "path";
|
|
1766
2012
|
import * as lockfile2 from "proper-lockfile";
|
|
1767
2013
|
var EMPTY = { entries: [] };
|
|
1768
2014
|
function isValidEntry(e) {
|
|
@@ -1791,7 +2037,7 @@ function writeAtomicSync(entries, path4) {
|
|
|
1791
2037
|
const tmp = `${path4}.tmp-${process.pid}`;
|
|
1792
2038
|
const body = `${JSON.stringify({ entries }, null, 2)}
|
|
1793
2039
|
`;
|
|
1794
|
-
mkdirSync(
|
|
2040
|
+
mkdirSync(dirname9(path4), { recursive: true });
|
|
1795
2041
|
const fd = openSync(tmp, "w", 384);
|
|
1796
2042
|
try {
|
|
1797
2043
|
writeFileSync(fd, body, "utf8");
|
|
@@ -1800,7 +2046,7 @@ function writeAtomicSync(entries, path4) {
|
|
|
1800
2046
|
closeSync(fd);
|
|
1801
2047
|
}
|
|
1802
2048
|
renameSync(tmp, path4);
|
|
1803
|
-
fsyncDirSync(
|
|
2049
|
+
fsyncDirSync(dirname9(path4));
|
|
1804
2050
|
}
|
|
1805
2051
|
function generateShortId() {
|
|
1806
2052
|
return randomBytes2(2).toString("hex");
|
|
@@ -1817,7 +2063,8 @@ async function register(args) {
|
|
|
1817
2063
|
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1818
2064
|
version: args.version,
|
|
1819
2065
|
...typeof args.webhookPort === "number" ? { webhookPort: args.webhookPort } : {},
|
|
1820
|
-
...args.webhookPath ? { webhookPath: args.webhookPath } : {}
|
|
2066
|
+
...args.webhookPath ? { webhookPath: args.webhookPath } : {},
|
|
2067
|
+
...typeof args.launcherPid === "number" ? { launcherPid: args.launcherPid } : {}
|
|
1821
2068
|
};
|
|
1822
2069
|
await withRegistryFileLock(registryFile, async () => {
|
|
1823
2070
|
const { entries: live } = await readForWriteState(registryFile);
|
|
@@ -1900,7 +2147,7 @@ function withRegistryFileLockSync(registryFile, fn) {
|
|
|
1900
2147
|
}
|
|
1901
2148
|
}
|
|
1902
2149
|
async function ensureRegistryFile(registryFile) {
|
|
1903
|
-
await
|
|
2150
|
+
await mkdir7(dirname9(registryFile), { recursive: true });
|
|
1904
2151
|
const legacy = legacyRegistryFile(registryFile);
|
|
1905
2152
|
const initial = legacy ? readRegistryFile(legacy) ?? EMPTY : EMPTY;
|
|
1906
2153
|
try {
|
|
@@ -1914,7 +2161,7 @@ async function ensureRegistryFile(registryFile) {
|
|
|
1914
2161
|
}
|
|
1915
2162
|
}
|
|
1916
2163
|
function ensureRegistryFileSync(registryFile) {
|
|
1917
|
-
mkdirSync(
|
|
2164
|
+
mkdirSync(dirname9(registryFile), { recursive: true });
|
|
1918
2165
|
const legacy = legacyRegistryFile(registryFile);
|
|
1919
2166
|
const initial = legacy ? readRegistryFile(legacy) ?? EMPTY : EMPTY;
|
|
1920
2167
|
try {
|
|
@@ -1961,8 +2208,8 @@ function lockMatchesEntry(lock6, entry, kind) {
|
|
|
1961
2208
|
return true;
|
|
1962
2209
|
}
|
|
1963
2210
|
function rootDirFromRegistryFile(registryFile) {
|
|
1964
|
-
const parent =
|
|
1965
|
-
return basename2(parent) === "registry" ?
|
|
2211
|
+
const parent = dirname9(registryFile);
|
|
2212
|
+
return basename2(parent) === "registry" ? dirname9(parent) : parent;
|
|
1966
2213
|
}
|
|
1967
2214
|
function readRaw(path4) {
|
|
1968
2215
|
const preferred = readRegistryFile(path4);
|
|
@@ -1975,7 +2222,7 @@ function readRaw(path4) {
|
|
|
1975
2222
|
}
|
|
1976
2223
|
function readRegistryFile(path4) {
|
|
1977
2224
|
try {
|
|
1978
|
-
const text2 =
|
|
2225
|
+
const text2 = readFileSync4(path4, "utf8");
|
|
1979
2226
|
const parsed = JSON.parse(text2);
|
|
1980
2227
|
if (!parsed || !Array.isArray(parsed.entries)) return { entries: [] };
|
|
1981
2228
|
return { entries: parsed.entries.filter(isValidEntry) };
|
|
@@ -1986,10 +2233,10 @@ function readRegistryFile(path4) {
|
|
|
1986
2233
|
}
|
|
1987
2234
|
function legacyRegistryFile(path4) {
|
|
1988
2235
|
if (basename2(path4) !== "processes.json") return void 0;
|
|
1989
|
-
const parent =
|
|
2236
|
+
const parent = dirname9(path4);
|
|
1990
2237
|
if (basename2(parent) !== "registry") return void 0;
|
|
1991
|
-
const legacy =
|
|
1992
|
-
return
|
|
2238
|
+
const legacy = join7(dirname9(parent), "processes.json");
|
|
2239
|
+
return existsSync7(path4) ? void 0 : legacy;
|
|
1993
2240
|
}
|
|
1994
2241
|
function fsyncDirSync(path4) {
|
|
1995
2242
|
try {
|
|
@@ -2005,14 +2252,14 @@ function fsyncDirSync(path4) {
|
|
|
2005
2252
|
|
|
2006
2253
|
// src/runtime/listen-sidecar.ts
|
|
2007
2254
|
import { createServer } from "net";
|
|
2008
|
-
import { mkdir as
|
|
2009
|
-
import { dirname as
|
|
2255
|
+
import { mkdir as mkdir9, readdir as readdir3, readFile as readFile3, rm as rm9 } from "fs/promises";
|
|
2256
|
+
import { dirname as dirname11, join as join9 } from "path";
|
|
2010
2257
|
|
|
2011
2258
|
// src/core/logger.ts
|
|
2012
2259
|
import { AsyncLocalStorage } from "async_hooks";
|
|
2013
2260
|
import { createWriteStream, mkdirSync as mkdirSync2 } from "fs";
|
|
2014
|
-
import { readdir, rename, rm as
|
|
2015
|
-
import { join as
|
|
2261
|
+
import { readdir as readdir2, rename, rm as rm7, stat } from "fs/promises";
|
|
2262
|
+
import { join as join8 } from "path";
|
|
2016
2263
|
|
|
2017
2264
|
// src/core/telemetry.ts
|
|
2018
2265
|
var noop = {
|
|
@@ -2152,7 +2399,7 @@ function getStream() {
|
|
|
2152
2399
|
}
|
|
2153
2400
|
try {
|
|
2154
2401
|
mkdirSync2(dir, { recursive: true });
|
|
2155
|
-
stream = createWriteStream(
|
|
2402
|
+
stream = createWriteStream(join8(dir, logFileName(today)), { flags: "a" });
|
|
2156
2403
|
currentDate = today;
|
|
2157
2404
|
return stream;
|
|
2158
2405
|
} catch {
|
|
@@ -2577,7 +2824,7 @@ async function gcOldLogs(extraDirs = []) {
|
|
|
2577
2824
|
for (const dir of dirs) {
|
|
2578
2825
|
let entries;
|
|
2579
2826
|
try {
|
|
2580
|
-
entries = await
|
|
2827
|
+
entries = await readdir2(dir);
|
|
2581
2828
|
} catch {
|
|
2582
2829
|
continue;
|
|
2583
2830
|
}
|
|
@@ -2587,13 +2834,13 @@ async function gcOldLogs(extraDirs = []) {
|
|
|
2587
2834
|
const fileMs = Date.parse(`${m[1]}-${m[2]}-${m[3]}T00:00:00Z`);
|
|
2588
2835
|
if (Number.isNaN(fileMs) || fileMs >= cutoff) continue;
|
|
2589
2836
|
try {
|
|
2590
|
-
await
|
|
2837
|
+
await rm7(join8(dir, name));
|
|
2591
2838
|
removed++;
|
|
2592
2839
|
} catch {
|
|
2593
2840
|
}
|
|
2594
2841
|
}
|
|
2595
2842
|
for (const name of DAEMON_LOG_NAMES) {
|
|
2596
|
-
await rotateIfOversized(
|
|
2843
|
+
await rotateIfOversized(join8(dir, name)).catch(() => void 0);
|
|
2597
2844
|
}
|
|
2598
2845
|
}
|
|
2599
2846
|
if (removed > 0) {
|
|
@@ -2610,7 +2857,7 @@ async function rotateIfOversized(path4) {
|
|
|
2610
2857
|
}
|
|
2611
2858
|
if (st.size <= DAEMON_LOG_MAX_BYTES) return;
|
|
2612
2859
|
const oldPath = `${path4}.old`;
|
|
2613
|
-
await
|
|
2860
|
+
await rm7(oldPath, { force: true }).catch(() => void 0);
|
|
2614
2861
|
await rename(path4, oldPath);
|
|
2615
2862
|
log.info("logger", "daemon-log-rotated", { rotatedBytes: st.size });
|
|
2616
2863
|
}
|
|
@@ -2655,11 +2902,11 @@ function sanitizeTelemetryError(err) {
|
|
|
2655
2902
|
}
|
|
2656
2903
|
|
|
2657
2904
|
// src/runtime/host-lock.ts
|
|
2658
|
-
import { mkdir as
|
|
2659
|
-
import { dirname as
|
|
2905
|
+
import { mkdir as mkdir8, rm as rm8, writeFile as writeFile6 } from "fs/promises";
|
|
2906
|
+
import { dirname as dirname10 } from "path";
|
|
2660
2907
|
import * as lockfile3 from "proper-lockfile";
|
|
2661
2908
|
async function acquireHostLock(target) {
|
|
2662
|
-
await
|
|
2909
|
+
await mkdir8(dirname10(target), { recursive: true });
|
|
2663
2910
|
await writeFile6(target, "", { flag: "a", mode: 384 }).catch(() => {
|
|
2664
2911
|
});
|
|
2665
2912
|
try {
|
|
@@ -2676,24 +2923,24 @@ async function acquireHostLock(target) {
|
|
|
2676
2923
|
}
|
|
2677
2924
|
async function forceReleaseHostLock(target) {
|
|
2678
2925
|
await lockfile3.unlock(target, { realpath: false }).catch(() => void 0);
|
|
2679
|
-
await
|
|
2926
|
+
await rm8(`${target}.lock`, { recursive: true, force: true }).catch(() => void 0);
|
|
2680
2927
|
}
|
|
2681
2928
|
|
|
2682
2929
|
// src/runtime/listen-sidecar.ts
|
|
2683
2930
|
function listenSidecarFile(port, rootDir) {
|
|
2684
|
-
return
|
|
2931
|
+
return join9(resolveAppPaths({ rootDir }).rootDir, "registry", "listen", `${port}.json`);
|
|
2685
2932
|
}
|
|
2686
2933
|
function listenLockFile(port, rootDir) {
|
|
2687
|
-
return
|
|
2934
|
+
return join9(resolveAppPaths({ rootDir }).userLockDir, "listen", `${port}.lock`);
|
|
2688
2935
|
}
|
|
2689
2936
|
async function writeListenSidecar(file, record5) {
|
|
2690
|
-
await
|
|
2937
|
+
await mkdir9(dirname11(file), { recursive: true });
|
|
2691
2938
|
await writeFileAtomic(file, `${JSON.stringify(record5, null, 2)}
|
|
2692
2939
|
`, { mode: 384 });
|
|
2693
2940
|
}
|
|
2694
2941
|
async function readListenSidecar(file) {
|
|
2695
2942
|
try {
|
|
2696
|
-
const parsed = JSON.parse(await
|
|
2943
|
+
const parsed = JSON.parse(await readFile3(file, "utf8"));
|
|
2697
2944
|
if (typeof parsed.pid !== "number" || typeof parsed.port !== "number" || typeof parsed.url !== "string" || typeof parsed.token !== "string") {
|
|
2698
2945
|
return void 0;
|
|
2699
2946
|
}
|
|
@@ -2703,7 +2950,7 @@ async function readListenSidecar(file) {
|
|
|
2703
2950
|
}
|
|
2704
2951
|
}
|
|
2705
2952
|
async function removeListenSidecar(file) {
|
|
2706
|
-
await
|
|
2953
|
+
await rm9(file, { force: true }).catch(
|
|
2707
2954
|
(err) => log.warn("listen", "sidecar-remove-failed", { err: String(err) })
|
|
2708
2955
|
);
|
|
2709
2956
|
}
|
|
@@ -2731,17 +2978,17 @@ async function liveListenSidecar(port, rootDir) {
|
|
|
2731
2978
|
return sidecar;
|
|
2732
2979
|
}
|
|
2733
2980
|
async function listLiveListenSidecars(rootDir) {
|
|
2734
|
-
const dir =
|
|
2981
|
+
const dir = join9(resolveAppPaths({ rootDir }).rootDir, "registry", "listen");
|
|
2735
2982
|
let names = [];
|
|
2736
2983
|
try {
|
|
2737
|
-
names = await
|
|
2984
|
+
names = await readdir3(dir);
|
|
2738
2985
|
} catch {
|
|
2739
2986
|
return [];
|
|
2740
2987
|
}
|
|
2741
2988
|
const live = [];
|
|
2742
2989
|
for (const name of names) {
|
|
2743
2990
|
if (!name.endsWith(".json")) continue;
|
|
2744
|
-
const file =
|
|
2991
|
+
const file = join9(dir, name);
|
|
2745
2992
|
const sidecar = await readListenSidecar(file);
|
|
2746
2993
|
if (!sidecar) continue;
|
|
2747
2994
|
if (!isAlive(sidecar.pid)) {
|
|
@@ -2783,9 +3030,9 @@ async function waitForListenOwner(port, host, rootDir, graceMs) {
|
|
|
2783
3030
|
}
|
|
2784
3031
|
|
|
2785
3032
|
// src/ui/sidecar.ts
|
|
2786
|
-
import { readFile as
|
|
2787
|
-
import { dirname as
|
|
2788
|
-
import { mkdir as
|
|
3033
|
+
import { readFile as readFile4, rm as rm10 } from "fs/promises";
|
|
3034
|
+
import { dirname as dirname12 } from "path";
|
|
3035
|
+
import { mkdir as mkdir10 } from "fs/promises";
|
|
2789
3036
|
async function writeUiSidecar(uiFile, handle2, startedAt) {
|
|
2790
3037
|
const record5 = {
|
|
2791
3038
|
url: handle2.url,
|
|
@@ -2794,13 +3041,13 @@ async function writeUiSidecar(uiFile, handle2, startedAt) {
|
|
|
2794
3041
|
pid: process.pid,
|
|
2795
3042
|
startedAt
|
|
2796
3043
|
};
|
|
2797
|
-
await
|
|
3044
|
+
await mkdir10(dirname12(uiFile), { recursive: true });
|
|
2798
3045
|
await writeFileAtomic(uiFile, `${JSON.stringify(record5, null, 2)}
|
|
2799
3046
|
`, { mode: 384 });
|
|
2800
3047
|
}
|
|
2801
3048
|
async function readUiSidecar(uiFile) {
|
|
2802
3049
|
try {
|
|
2803
|
-
const parsed = JSON.parse(await
|
|
3050
|
+
const parsed = JSON.parse(await readFile4(uiFile, "utf8"));
|
|
2804
3051
|
if (!parsed.url || !parsed.token || typeof parsed.port !== "number") return void 0;
|
|
2805
3052
|
return parsed;
|
|
2806
3053
|
} catch {
|
|
@@ -2808,7 +3055,7 @@ async function readUiSidecar(uiFile) {
|
|
|
2808
3055
|
}
|
|
2809
3056
|
}
|
|
2810
3057
|
async function removeUiSidecar(uiFile) {
|
|
2811
|
-
await
|
|
3058
|
+
await rm10(uiFile, { force: true }).catch(
|
|
2812
3059
|
(err) => log.warn("ui", "sidecar-remove-failed", { err: String(err) })
|
|
2813
3060
|
);
|
|
2814
3061
|
}
|
|
@@ -2998,7 +3245,7 @@ async function packageRoot(entry, name) {
|
|
|
2998
3245
|
}
|
|
2999
3246
|
async function readProcessArgs(pid) {
|
|
3000
3247
|
if (process.platform === "linux") {
|
|
3001
|
-
const args = (await
|
|
3248
|
+
const args = (await readFile5(`/proc/${pid}/cmdline`, "utf8")).split("\0").filter(Boolean);
|
|
3002
3249
|
const cwd = await realpath(`/proc/${pid}/cwd`);
|
|
3003
3250
|
return args.map((arg) => /(?:^|\/)dist\/cli\.js$|(?:^|\/)bin\/xiaojiu-agent-bridge\.mjs$|(?:^|\/)src\/cli\/index\.ts$/.test(arg) ? path2.resolve(cwd, arg) : arg);
|
|
3004
3251
|
}
|
|
@@ -3029,217 +3276,36 @@ function capture(command, args) {
|
|
|
3029
3276
|
child.kill();
|
|
3030
3277
|
reject4(new Error(`${command} timed out`));
|
|
3031
3278
|
}, 1e4);
|
|
3032
|
-
child.once("error", () => clearTimeout(timer));
|
|
3033
|
-
});
|
|
3034
|
-
}
|
|
3035
|
-
async function optionalRead(file) {
|
|
3036
|
-
try {
|
|
3037
|
-
return await readFile4(file, "utf8");
|
|
3038
|
-
} catch (error) {
|
|
3039
|
-
if (error.code === "ENOENT") return void 0;
|
|
3040
|
-
throw error;
|
|
3041
|
-
}
|
|
3042
|
-
}
|
|
3043
|
-
async function namesIn(dir) {
|
|
3044
|
-
try {
|
|
3045
|
-
return await readdir3(dir);
|
|
3046
|
-
} catch (error) {
|
|
3047
|
-
if (error.code === "ENOENT") return [];
|
|
3048
|
-
throw error;
|
|
3049
|
-
}
|
|
3050
|
-
}
|
|
3051
|
-
function samePath(left, right) {
|
|
3052
|
-
return process.platform === "win32" ? left.toLowerCase() === right.toLowerCase() : left === right;
|
|
3053
|
-
}
|
|
3054
|
-
function unknownState(detail) {
|
|
3055
|
-
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.`);
|
|
3056
|
-
}
|
|
3057
|
-
|
|
3058
|
-
// src/selfupdate/version-check.ts
|
|
3059
|
-
var REGISTRY_URL = "https://registry.npmjs.org";
|
|
3060
|
-
var PASSIVE_REQUEST_TIMEOUT_MS = 1500;
|
|
3061
|
-
var EXPLICIT_REQUEST_TIMEOUT_MS = 1e4;
|
|
3062
|
-
function compareVersions(left, right) {
|
|
3063
|
-
const a = parseVersion(left);
|
|
3064
|
-
const b = parseVersion(right);
|
|
3065
|
-
for (let index = 0; index < 3; index += 1) {
|
|
3066
|
-
const difference = (a.numbers[index] ?? 0) - (b.numbers[index] ?? 0);
|
|
3067
|
-
if (difference !== 0) return difference;
|
|
3068
|
-
}
|
|
3069
|
-
if (a.prerelease.length === 0 && b.prerelease.length === 0) return 0;
|
|
3070
|
-
if (a.prerelease.length === 0) return 1;
|
|
3071
|
-
if (b.prerelease.length === 0) return -1;
|
|
3072
|
-
const length = Math.max(a.prerelease.length, b.prerelease.length);
|
|
3073
|
-
for (let index = 0; index < length; index += 1) {
|
|
3074
|
-
const leftPart = a.prerelease[index];
|
|
3075
|
-
const rightPart = b.prerelease[index];
|
|
3076
|
-
if (leftPart === void 0) return -1;
|
|
3077
|
-
if (rightPart === void 0) return 1;
|
|
3078
|
-
if (leftPart === rightPart) continue;
|
|
3079
|
-
const leftNumeric = /^\d+$/.test(leftPart);
|
|
3080
|
-
const rightNumeric = /^\d+$/.test(rightPart);
|
|
3081
|
-
if (leftNumeric && rightNumeric) {
|
|
3082
|
-
if (leftPart.length !== rightPart.length) return leftPart.length - rightPart.length;
|
|
3083
|
-
return leftPart < rightPart ? -1 : 1;
|
|
3084
|
-
}
|
|
3085
|
-
if (leftNumeric) return -1;
|
|
3086
|
-
if (rightNumeric) return 1;
|
|
3087
|
-
return leftPart < rightPart ? -1 : 1;
|
|
3088
|
-
}
|
|
3089
|
-
return 0;
|
|
3090
|
-
}
|
|
3091
|
-
function parseUpdateInfo(metadata, currentVersion = version, expectedName = packageName) {
|
|
3092
|
-
if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) throw new Error("Invalid npm Registry package metadata");
|
|
3093
|
-
const pkg = metadata;
|
|
3094
|
-
if (pkg.name !== expectedName || typeof pkg.version !== "string") throw new Error("Invalid npm Registry package identity or version");
|
|
3095
|
-
const current = parseVersion(currentVersion);
|
|
3096
|
-
const latest = parseVersion(pkg.version);
|
|
3097
|
-
if (current.prerelease.length === 0 && latest.prerelease.length > 0) {
|
|
3098
|
-
throw new Error("npm Registry latest points to a prerelease; refusing to update a stable installation");
|
|
3099
|
-
}
|
|
3100
|
-
if (compareVersions(pkg.version, currentVersion) <= 0) return void 0;
|
|
3101
|
-
const update = pkg.xiaojiu?.update;
|
|
3102
|
-
return {
|
|
3103
|
-
currentVersion,
|
|
3104
|
-
latestVersion: pkg.version,
|
|
3105
|
-
highlights: stringList(update?.highlights),
|
|
3106
|
-
breakingChanges: stringList(update?.breakingChanges),
|
|
3107
|
-
securityFix: update?.securityFix === true,
|
|
3108
|
-
requiresRestart: update?.requiresRestart === true
|
|
3109
|
-
};
|
|
3110
|
-
}
|
|
3111
|
-
async function fetchUpdateInfo(options = {}) {
|
|
3112
|
-
const fetchImpl = options.fetchImpl ?? fetch;
|
|
3113
|
-
const name = options.packageName ?? packageName;
|
|
3114
|
-
const controller = new AbortController();
|
|
3115
|
-
const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? PASSIVE_REQUEST_TIMEOUT_MS);
|
|
3116
|
-
try {
|
|
3117
|
-
const response = await fetchImpl(`${REGISTRY_URL}/${encodeURIComponent(name)}/latest`, {
|
|
3118
|
-
headers: { accept: "application/json" },
|
|
3119
|
-
signal: controller.signal
|
|
3120
|
-
});
|
|
3121
|
-
if (!response.ok) {
|
|
3122
|
-
if (options.throwOnError) throw new Error(`npm Registry returned ${response.status}`);
|
|
3123
|
-
return void 0;
|
|
3124
|
-
}
|
|
3125
|
-
const metadata = await response.json();
|
|
3126
|
-
return parseUpdateInfo(metadata, options.currentVersion ?? version, name);
|
|
3127
|
-
} catch (error) {
|
|
3128
|
-
if (options.throwOnError) throw error;
|
|
3129
|
-
return void 0;
|
|
3130
|
-
} finally {
|
|
3131
|
-
clearTimeout(timer);
|
|
3132
|
-
}
|
|
3133
|
-
}
|
|
3134
|
-
function parseVersion(value) {
|
|
3135
|
-
const match = value.match(
|
|
3136
|
-
/^(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-]+)*)?$/
|
|
3137
|
-
);
|
|
3138
|
-
if (!match || match[0] !== value) throw new Error(`invalid semantic version: ${value}`);
|
|
3139
|
-
if (![match[1], match[2], match[3]].every((part) => Number.isSafeInteger(Number(part)))) {
|
|
3140
|
-
throw new Error(`invalid semantic version: ${value}`);
|
|
3141
|
-
}
|
|
3142
|
-
return {
|
|
3143
|
-
numbers: [Number(match[1]), Number(match[2]), Number(match[3])],
|
|
3144
|
-
prerelease: match[4]?.split(".") ?? []
|
|
3145
|
-
};
|
|
3146
|
-
}
|
|
3147
|
-
function stringList(value) {
|
|
3148
|
-
if (!Array.isArray(value)) return [];
|
|
3149
|
-
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);
|
|
3150
|
-
}
|
|
3151
|
-
|
|
3152
|
-
// src/selfupdate/stage.ts
|
|
3153
|
-
import { mkdir as mkdir11, mkdtemp, open as open2, readFile as readFile6, rm as rm10 } from "fs/promises";
|
|
3154
|
-
import { tmpdir } from "os";
|
|
3155
|
-
import { join as join9 } from "path";
|
|
3156
|
-
|
|
3157
|
-
// src/selfupdate/store.ts
|
|
3158
|
-
import { mkdir as mkdir10, readdir as readdir4, readFile as readFile5, rm as rm9 } from "fs/promises";
|
|
3159
|
-
import { dirname as dirname11, join as join8 } from "path";
|
|
3160
|
-
function updateLayout(rootDir) {
|
|
3161
|
-
return {
|
|
3162
|
-
updateDir: join8(rootDir, "update"),
|
|
3163
|
-
versionsDir: join8(rootDir, "versions"),
|
|
3164
|
-
launcherDir: join8(rootDir, "launcher"),
|
|
3165
|
-
launcherFile: join8(rootDir, "launcher", "launcher.mjs"),
|
|
3166
|
-
currentVersionFile: join8(rootDir, "update", "current.json"),
|
|
3167
|
-
pendingVersionFile: join8(rootDir, "update", "pending.json"),
|
|
3168
|
-
bootStateFile: join8(rootDir, "update", "boot.json"),
|
|
3169
|
-
badVersionsFile: join8(rootDir, "update", "bad.json"),
|
|
3170
|
-
stageLockFile: join8(rootDir, "update", "stage.lock"),
|
|
3171
|
-
selfUpdateLogFile: join8(rootDir, "update", "self-update.log")
|
|
3172
|
-
};
|
|
3173
|
-
}
|
|
3174
|
-
function versionDir(layout, version2) {
|
|
3175
|
-
return join8(layout.versionsDir, version2);
|
|
3176
|
-
}
|
|
3177
|
-
function packageDirOf(installRoot, name = packageName) {
|
|
3178
|
-
return join8(installRoot, "node_modules", ...name.split("/"));
|
|
3279
|
+
child.once("error", () => clearTimeout(timer));
|
|
3280
|
+
});
|
|
3179
3281
|
}
|
|
3180
|
-
async function
|
|
3282
|
+
async function optionalRead(file) {
|
|
3181
3283
|
try {
|
|
3182
|
-
return
|
|
3183
|
-
} catch {
|
|
3184
|
-
return void 0;
|
|
3284
|
+
return await readFile5(file, "utf8");
|
|
3285
|
+
} catch (error) {
|
|
3286
|
+
if (error.code === "ENOENT") return void 0;
|
|
3287
|
+
throw error;
|
|
3185
3288
|
}
|
|
3186
3289
|
}
|
|
3187
|
-
async function
|
|
3188
|
-
await mkdir10(dirname11(file), { recursive: true });
|
|
3189
|
-
await writeFileAtomic(file, `${JSON.stringify(value, null, 2)}
|
|
3190
|
-
`, { mode: 384 });
|
|
3191
|
-
}
|
|
3192
|
-
function isPointer(value) {
|
|
3193
|
-
if (!value || typeof value !== "object") return false;
|
|
3194
|
-
const v = value;
|
|
3195
|
-
return typeof v.version === "string" && typeof v.dir === "string";
|
|
3196
|
-
}
|
|
3197
|
-
function readCurrent(layout) {
|
|
3198
|
-
return readJson(layout.currentVersionFile).then((v) => v && isPointer(v) ? v : void 0);
|
|
3199
|
-
}
|
|
3200
|
-
function writeCurrent(layout, pointer) {
|
|
3201
|
-
return writeJson(layout.currentVersionFile, pointer);
|
|
3202
|
-
}
|
|
3203
|
-
function writePending(layout, pending) {
|
|
3204
|
-
return writeJson(layout.pendingVersionFile, pending);
|
|
3205
|
-
}
|
|
3206
|
-
async function readBadVersions(layout) {
|
|
3207
|
-
const bad = await readJson(layout.badVersionsFile);
|
|
3208
|
-
return Array.isArray(bad?.versions) ? bad.versions.filter((v) => typeof v === "string") : [];
|
|
3209
|
-
}
|
|
3210
|
-
async function gcVersions(layout, keep = 3) {
|
|
3211
|
-
const current = await readCurrent(layout);
|
|
3212
|
-
const protectedDirs = new Set(
|
|
3213
|
-
[current?.dir, current?.previous?.dir].filter((d) => typeof d === "string")
|
|
3214
|
-
);
|
|
3215
|
-
let entries;
|
|
3290
|
+
async function namesIn(dir) {
|
|
3216
3291
|
try {
|
|
3217
|
-
|
|
3218
|
-
} catch {
|
|
3219
|
-
return [];
|
|
3220
|
-
|
|
3221
|
-
const removed = [];
|
|
3222
|
-
const valid = [];
|
|
3223
|
-
for (const name of entries) {
|
|
3224
|
-
const dir = join8(layout.versionsDir, name);
|
|
3225
|
-
if (!/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(name)) {
|
|
3226
|
-
if (!protectedDirs.has(dir)) {
|
|
3227
|
-
await rm9(dir, { recursive: true, force: true, maxRetries: 5 });
|
|
3228
|
-
removed.push(dir);
|
|
3229
|
-
}
|
|
3230
|
-
continue;
|
|
3231
|
-
}
|
|
3232
|
-
if (!protectedDirs.has(dir)) valid.push({ name, dir });
|
|
3233
|
-
}
|
|
3234
|
-
const dirs = valid.sort((a, b) => compareVersions(a.name, b.name)).reverse().map((entry) => entry.dir);
|
|
3235
|
-
for (const dir of dirs.slice(Math.max(keep - protectedDirs.size, 0))) {
|
|
3236
|
-
await rm9(dir, { recursive: true, force: true, maxRetries: 5 });
|
|
3237
|
-
removed.push(dir);
|
|
3292
|
+
return await readdir4(dir);
|
|
3293
|
+
} catch (error) {
|
|
3294
|
+
if (error.code === "ENOENT") return [];
|
|
3295
|
+
throw error;
|
|
3238
3296
|
}
|
|
3239
|
-
|
|
3297
|
+
}
|
|
3298
|
+
function samePath(left, right) {
|
|
3299
|
+
return process.platform === "win32" ? left.toLowerCase() === right.toLowerCase() : left === right;
|
|
3300
|
+
}
|
|
3301
|
+
function unknownState(detail) {
|
|
3302
|
+
return new Error(`Cannot safely update: ${detail}. Inspect \`xiaojiu-agent-bridge ps\` and stop the bridge/listen/UI processes before retrying. No files were changed.`);
|
|
3240
3303
|
}
|
|
3241
3304
|
|
|
3242
3305
|
// src/selfupdate/stage.ts
|
|
3306
|
+
import { mkdir as mkdir11, mkdtemp, open as open2, readFile as readFile6, rm as rm11 } from "fs/promises";
|
|
3307
|
+
import { tmpdir } from "os";
|
|
3308
|
+
import { join as join10 } from "path";
|
|
3243
3309
|
var STAGE_LOCK_STALE_MS = 30 * 60 * 1e3;
|
|
3244
3310
|
var SMOKE_TIMEOUT_MS = 3e4;
|
|
3245
3311
|
async function stageVersion(deps) {
|
|
@@ -3263,7 +3329,7 @@ async function stageVersion(deps) {
|
|
|
3263
3329
|
log2("stage.reuse", { version: targetVersion, dir });
|
|
3264
3330
|
return { ok: true, dir, reused: true };
|
|
3265
3331
|
}
|
|
3266
|
-
await
|
|
3332
|
+
await rm11(dir, { recursive: true, force: true, maxRetries: 5 });
|
|
3267
3333
|
const registryArgs = [`--registry=${REGISTRY_URL}`];
|
|
3268
3334
|
if (name.startsWith("@")) registryArgs.push(`--${name.split("/")[0]}:registry=${REGISTRY_URL}`);
|
|
3269
3335
|
const result = await (deps.runNpm ?? runNpm)([
|
|
@@ -3277,17 +3343,17 @@ async function stageVersion(deps) {
|
|
|
3277
3343
|
...registryArgs
|
|
3278
3344
|
]);
|
|
3279
3345
|
if (result.code !== 0) {
|
|
3280
|
-
await
|
|
3346
|
+
await rm11(dir, { recursive: true, force: true, maxRetries: 5 });
|
|
3281
3347
|
return { ok: false, error: `npm install failed (${result.code}): ${(result.stderr ?? "").trim().slice(0, 300)}` };
|
|
3282
3348
|
}
|
|
3283
3349
|
if (!await installedVersionMatches(pkgDir, targetVersion)) {
|
|
3284
|
-
await
|
|
3350
|
+
await rm11(dir, { recursive: true, force: true, maxRetries: 5 });
|
|
3285
3351
|
return { ok: false, error: `staged package.json does not report ${targetVersion}` };
|
|
3286
3352
|
}
|
|
3287
3353
|
try {
|
|
3288
3354
|
await (deps.runSmoke ?? smokeTest)(pkgDir, targetVersion);
|
|
3289
3355
|
} catch (err) {
|
|
3290
|
-
await
|
|
3356
|
+
await rm11(dir, { recursive: true, force: true, maxRetries: 5 });
|
|
3291
3357
|
return { ok: false, error: `smoke test failed: ${err instanceof Error ? err.message : String(err)}` };
|
|
3292
3358
|
}
|
|
3293
3359
|
log2("stage.installed", { version: targetVersion, dir });
|
|
@@ -3300,7 +3366,7 @@ async function stageVersion(deps) {
|
|
|
3300
3366
|
}
|
|
3301
3367
|
async function installedVersionMatches(pkgDir, expected) {
|
|
3302
3368
|
try {
|
|
3303
|
-
const manifest2 = JSON.parse(await readFile6(
|
|
3369
|
+
const manifest2 = JSON.parse(await readFile6(join10(pkgDir, "package.json"), "utf8"));
|
|
3304
3370
|
return typeof manifest2 === "object" && manifest2 !== null && "version" in manifest2 && manifest2.version === expected;
|
|
3305
3371
|
} catch {
|
|
3306
3372
|
return false;
|
|
@@ -3314,7 +3380,7 @@ async function acquireStageLock(layout) {
|
|
|
3314
3380
|
await handle2.writeFile(JSON.stringify({ pid: process.pid, at: (/* @__PURE__ */ new Date()).toISOString() }));
|
|
3315
3381
|
await handle2.close();
|
|
3316
3382
|
return async () => {
|
|
3317
|
-
await
|
|
3383
|
+
await rm11(layout.stageLockFile, { force: true });
|
|
3318
3384
|
};
|
|
3319
3385
|
} catch (err) {
|
|
3320
3386
|
if (err.code !== "EEXIST") throw err;
|
|
@@ -3324,7 +3390,7 @@ async function acquireStageLock(layout) {
|
|
|
3324
3390
|
return !Number.isFinite(at) || Date.now() - at > STAGE_LOCK_STALE_MS;
|
|
3325
3391
|
}).catch(() => true);
|
|
3326
3392
|
if (!stale) return void 0;
|
|
3327
|
-
await
|
|
3393
|
+
await rm11(layout.stageLockFile, { force: true });
|
|
3328
3394
|
}
|
|
3329
3395
|
}
|
|
3330
3396
|
return void 0;
|
|
@@ -3344,9 +3410,9 @@ function runNpm(args) {
|
|
|
3344
3410
|
});
|
|
3345
3411
|
}
|
|
3346
3412
|
async function smokeTest(pkgDir, expectedVersion) {
|
|
3347
|
-
const fakeHome = await mkdtemp(
|
|
3413
|
+
const fakeHome = await mkdtemp(join10(tmpdir(), "xiaojiu-smoke-"));
|
|
3348
3414
|
try {
|
|
3349
|
-
const bin =
|
|
3415
|
+
const bin = join10(pkgDir, "bin", "xiaojiu-agent-bridge.mjs");
|
|
3350
3416
|
await new Promise((resolve5, reject4) => {
|
|
3351
3417
|
const child = spawnProcess(process.execPath, [bin, "--version"], {
|
|
3352
3418
|
stdio: ["ignore", "pipe", "pipe"],
|
|
@@ -3376,7 +3442,7 @@ async function smokeTest(pkgDir, expectedVersion) {
|
|
|
3376
3442
|
});
|
|
3377
3443
|
});
|
|
3378
3444
|
} finally {
|
|
3379
|
-
await
|
|
3445
|
+
await rm11(fakeHome, { recursive: true, force: true, maxRetries: 5 });
|
|
3380
3446
|
}
|
|
3381
3447
|
}
|
|
3382
3448
|
|
|
@@ -3389,7 +3455,7 @@ async function maybeShowUpdateNotice() {
|
|
|
3389
3455
|
if (Number.isFinite(lastChecked) && Date.now() - lastChecked < CHECK_INTERVAL_MS) return;
|
|
3390
3456
|
let info;
|
|
3391
3457
|
try {
|
|
3392
|
-
info = await fetchUpdateInfo({ throwOnError: true });
|
|
3458
|
+
info = await fetchUpdateInfo({ throwOnError: true, currentVersion: resolveInstall().version });
|
|
3393
3459
|
} catch {
|
|
3394
3460
|
return;
|
|
3395
3461
|
}
|
|
@@ -3401,11 +3467,12 @@ async function maybeShowUpdateNotice() {
|
|
|
3401
3467
|
}
|
|
3402
3468
|
async function runUpdateCheck(options = {}) {
|
|
3403
3469
|
const name = options.packageName ?? packageName;
|
|
3404
|
-
const current = options.currentVersion ?? version;
|
|
3405
3470
|
const log2 = options.log ?? ((message) => process.stdout.write(`${message}
|
|
3406
3471
|
`));
|
|
3407
3472
|
const layout = options.layout ?? updateLayout(paths.rootDir);
|
|
3408
|
-
|
|
3473
|
+
const pointer = await readCurrent(layout);
|
|
3474
|
+
const current = options.currentVersion ?? pointer?.version ?? version;
|
|
3475
|
+
if (!options.checkOnly && pointer) {
|
|
3409
3476
|
const info2 = await fetchUpdateInfo({
|
|
3410
3477
|
fetchImpl: options.fetchImpl,
|
|
3411
3478
|
currentVersion: current,
|
|
@@ -3513,8 +3580,9 @@ async function runUpdateCheck(options = {}) {
|
|
|
3513
3580
|
}
|
|
3514
3581
|
}
|
|
3515
3582
|
async function runChangelog(requestedVersion) {
|
|
3516
|
-
const
|
|
3517
|
-
const
|
|
3583
|
+
const install = resolveInstall();
|
|
3584
|
+
const changelog = await readFile7(changelogPath(install.dir), "utf8");
|
|
3585
|
+
const target = requestedVersion ?? install.version;
|
|
3518
3586
|
const section = extractChangelogSection(changelog, target);
|
|
3519
3587
|
if (!section) {
|
|
3520
3588
|
throw new Error(`No changelog entry found for ${target}`);
|
|
@@ -3586,15 +3654,16 @@ async function restartLauncherServices() {
|
|
|
3586
3654
|
function isUpdateCheckDisabled() {
|
|
3587
3655
|
return process.env.XIAOJIU_BRIDGE_NO_UPDATE_CHECK === "1" || process.env.CI === "true" || process.env.TERM === "dumb" || !process.stdin.isTTY || !process.stdout.isTTY;
|
|
3588
3656
|
}
|
|
3589
|
-
function changelogPath() {
|
|
3590
|
-
const moduleDir = path3.dirname(
|
|
3657
|
+
function changelogPath(installDir) {
|
|
3658
|
+
const moduleDir = path3.dirname(fileURLToPath3(import.meta.url));
|
|
3591
3659
|
const candidates = [
|
|
3660
|
+
...installDir ? [path3.join(installDir, "CHANGELOG.md")] : [],
|
|
3592
3661
|
path3.resolve(moduleDir, "CHANGELOG.md"),
|
|
3593
3662
|
path3.resolve(moduleDir, "..", "CHANGELOG.md"),
|
|
3594
3663
|
path3.resolve(moduleDir, "..", "..", "CHANGELOG.md"),
|
|
3595
3664
|
path3.resolve(moduleDir, "..", "..", "..", "CHANGELOG.md")
|
|
3596
3665
|
];
|
|
3597
|
-
const match = candidates.find((candidate) =>
|
|
3666
|
+
const match = candidates.find((candidate) => existsSync8(candidate));
|
|
3598
3667
|
if (!match) throw new Error("CHANGELOG.md is not included in this installation");
|
|
3599
3668
|
return match;
|
|
3600
3669
|
}
|
|
@@ -3620,75 +3689,6 @@ async function writeState(state) {
|
|
|
3620
3689
|
}
|
|
3621
3690
|
}
|
|
3622
3691
|
|
|
3623
|
-
// src/cli/commands/listen-client.ts
|
|
3624
|
-
var ListenApiError = class extends Error {
|
|
3625
|
-
constructor(message, status) {
|
|
3626
|
-
super(message);
|
|
3627
|
-
this.status = status;
|
|
3628
|
-
}
|
|
3629
|
-
status;
|
|
3630
|
-
};
|
|
3631
|
-
function apiUrl(sidecar, path4) {
|
|
3632
|
-
const url = new URL(sidecar.url);
|
|
3633
|
-
url.pathname = path4;
|
|
3634
|
-
url.search = "";
|
|
3635
|
-
url.searchParams.set("token", sidecar.token);
|
|
3636
|
-
return url.toString();
|
|
3637
|
-
}
|
|
3638
|
-
function errorMessage(parsed, fallback) {
|
|
3639
|
-
if (parsed && typeof parsed === "object" && "error" in parsed) {
|
|
3640
|
-
const error = parsed.error;
|
|
3641
|
-
if (typeof error === "string" && error.trim()) return error;
|
|
3642
|
-
}
|
|
3643
|
-
return fallback;
|
|
3644
|
-
}
|
|
3645
|
-
async function postJson(sidecar, path4, body) {
|
|
3646
|
-
const response = await fetch(apiUrl(sidecar, path4), {
|
|
3647
|
-
method: "POST",
|
|
3648
|
-
headers: {
|
|
3649
|
-
"content-type": "application/json",
|
|
3650
|
-
"x-ui-token": sidecar.token
|
|
3651
|
-
},
|
|
3652
|
-
body: JSON.stringify(body)
|
|
3653
|
-
});
|
|
3654
|
-
const text2 = await response.text();
|
|
3655
|
-
let parsed = {};
|
|
3656
|
-
if (text2) {
|
|
3657
|
-
try {
|
|
3658
|
-
parsed = JSON.parse(text2);
|
|
3659
|
-
} catch {
|
|
3660
|
-
parsed = { error: text2 };
|
|
3661
|
-
}
|
|
3662
|
-
}
|
|
3663
|
-
if (!response.ok) {
|
|
3664
|
-
throw new ListenApiError(errorMessage(parsed, `HTTP ${response.status}`), response.status);
|
|
3665
|
-
}
|
|
3666
|
-
return parsed;
|
|
3667
|
-
}
|
|
3668
|
-
async function joinListenProfile(sidecar, profile2) {
|
|
3669
|
-
await postJson(sidecar, "/api/profiles/start", { profile: profile2 });
|
|
3670
|
-
}
|
|
3671
|
-
async function leaveListenProfile(sidecar, profile2) {
|
|
3672
|
-
await postJson(sidecar, "/api/profiles/stop", { profile: profile2 });
|
|
3673
|
-
}
|
|
3674
|
-
async function listListenBots(sidecar) {
|
|
3675
|
-
const response = await fetch(apiUrl(sidecar, "/api/bots"), {
|
|
3676
|
-
headers: { "x-ui-token": sidecar.token }
|
|
3677
|
-
});
|
|
3678
|
-
if (!response.ok) throw new ListenApiError(`HTTP ${response.status}`, response.status);
|
|
3679
|
-
const parsed = await response.json();
|
|
3680
|
-
if (!parsed || typeof parsed !== "object" || !("bots" in parsed) || !Array.isArray(parsed.bots)) {
|
|
3681
|
-
return [];
|
|
3682
|
-
}
|
|
3683
|
-
const names = [];
|
|
3684
|
-
for (const bot of parsed.bots) {
|
|
3685
|
-
if (bot && typeof bot === "object" && "profileName" in bot && typeof bot.profileName === "string") {
|
|
3686
|
-
names.push({ profileName: bot.profileName });
|
|
3687
|
-
}
|
|
3688
|
-
}
|
|
3689
|
-
return names;
|
|
3690
|
-
}
|
|
3691
|
-
|
|
3692
3692
|
// src/cli/commands/ps.ts
|
|
3693
3693
|
function runPs() {
|
|
3694
3694
|
const live = readAndPrune().filter((entry) => isAlive(entry.pid));
|
|
@@ -3712,99 +3712,6 @@ function runPs() {
|
|
|
3712
3712
|
const headers = { idx: "#", uid: "uid", pid: "\u8FDB\u7A0B", webhook: "webhook", online: "\u5728\u7EBF" };
|
|
3713
3713
|
printTable([headers, ...rows]);
|
|
3714
3714
|
}
|
|
3715
|
-
async function stopSharedProfile(entry) {
|
|
3716
|
-
if (typeof entry.webhookPort !== "number") {
|
|
3717
|
-
console.error(
|
|
3718
|
-
`\u2717 uid ${entry.id} \u4E0E\u540C\u8FDB\u7A0B\u7684\u5176\u5B83 profile \u4E0D\u80FD\u901A\u8FC7 kill \u5355\u72EC\u5173\u95ED\uFF0C\u8BF7\u4F7F\u7528 xiaojiu-agent-bridge stop --profile ${entry.profileName}\u3002`
|
|
3719
|
-
);
|
|
3720
|
-
return false;
|
|
3721
|
-
}
|
|
3722
|
-
const sidecar = await liveListenSidecar(entry.webhookPort);
|
|
3723
|
-
if (!sidecar) {
|
|
3724
|
-
console.error(
|
|
3725
|
-
`\u2717 \u627E\u4E0D\u5230\u8FDB\u7A0B ${entry.pid} \u7684\u76D1\u542C\u63A7\u5236\u5668\uFF0C\u672A\u5173\u95ED uid ${entry.id}\uFF0C\u4EE5\u514D\u540C\u65F6\u5173\u95ED\u5176\u5B83 profile\u3002`
|
|
3726
|
-
);
|
|
3727
|
-
return false;
|
|
3728
|
-
}
|
|
3729
|
-
try {
|
|
3730
|
-
await leaveListenProfile(sidecar, entry.profileName);
|
|
3731
|
-
const remaining = await listListenBots(sidecar);
|
|
3732
|
-
if (remaining.some((bot) => bot.profileName !== entry.profileName)) {
|
|
3733
|
-
console.log(`\u2713 \u5DF2\u5173\u95ED uid ${entry.id}\uFF08profile ${entry.profileName}\uFF09\uFF0C\u5176\u5B83 profile \u4ECD\u5728\u8FD0\u884C\u3002`);
|
|
3734
|
-
return true;
|
|
3735
|
-
}
|
|
3736
|
-
} catch (err) {
|
|
3737
|
-
console.error(`\u2717 \u5355\u72EC\u5173\u95ED profile ${entry.profileName} \u5931\u8D25\uFF1A${err instanceof Error ? err.message : String(err)}`);
|
|
3738
|
-
return false;
|
|
3739
|
-
}
|
|
3740
|
-
console.error(
|
|
3741
|
-
`\u2717 profile ${entry.profileName} \u5DF2\u8BF7\u6C42\u5173\u95ED\uFF0C\u4F46\u76D1\u542C\u8FDB\u7A0B\u4ECD\u6709\u5176\u5B83 profile\uFF0C\u672A\u7EC8\u6B62\u8FDB\u7A0B\u3002`
|
|
3742
|
-
);
|
|
3743
|
-
return false;
|
|
3744
|
-
}
|
|
3745
|
-
async function runKillCli(target) {
|
|
3746
|
-
if (!target) {
|
|
3747
|
-
console.error("\u7528\u6CD5: xiaojiu-agent-bridge kill <uid\u3001\u8FDB\u7A0B \u6216\u5E8F\u53F7>");
|
|
3748
|
-
process.exit(1);
|
|
3749
|
-
}
|
|
3750
|
-
const entry = resolveTarget(target);
|
|
3751
|
-
if (!entry) {
|
|
3752
|
-
console.error(`\u2717 \u6CA1\u627E\u5230\u5339\u914D\u7684 bot:${target}`);
|
|
3753
|
-
console.error(" \u7528 `xiaojiu-agent-bridge ps` \u770B\u53EF\u9009\u76EE\u6807\u3002");
|
|
3754
|
-
process.exit(1);
|
|
3755
|
-
}
|
|
3756
|
-
const peers = readAndPrune().filter((candidate) => candidate.pid === entry.pid);
|
|
3757
|
-
if (peers.length > 1) {
|
|
3758
|
-
console.log(`\u6B63\u5728\u5173\u95ED uid ${entry.id}\u2026`);
|
|
3759
|
-
if (await stopSharedProfile(entry)) return;
|
|
3760
|
-
process.exit(1);
|
|
3761
|
-
}
|
|
3762
|
-
const owner = findOwningService(entry);
|
|
3763
|
-
if (owner) {
|
|
3764
|
-
console.error(
|
|
3765
|
-
`\u2717 uid ${entry.id} (\u8FDB\u7A0B ${entry.pid}) \u7531 ${owner.platformName} \u6258\u7BA1,SIGTERM \u4E4B\u540E\u4F1A\u88AB\u670D\u52A1\u7BA1\u7406\u5668\u7ACB\u523B\u91CD\u542F\u3002`
|
|
3766
|
-
);
|
|
3767
|
-
console.error(` \u8981\u505C\u6389\u5B83: ${owner.stopHint}`);
|
|
3768
|
-
console.error(` \u53EA\u662F\u60F3\u91CD\u542F: ${owner.restartHint}`);
|
|
3769
|
-
process.exit(1);
|
|
3770
|
-
}
|
|
3771
|
-
console.log(`\u6B63\u5728\u5173\u95ED uid ${entry.id}\u2026`);
|
|
3772
|
-
let result;
|
|
3773
|
-
try {
|
|
3774
|
-
result = await stopProcessEntry(entry);
|
|
3775
|
-
} catch (err) {
|
|
3776
|
-
if (err.code === "ESRCH") {
|
|
3777
|
-
await unregister(entry.id);
|
|
3778
|
-
console.log(`\u2713 uid ${entry.id} \u5DF2\u4E0D\u5728\u8FD0\u884C\uFF0C\u5DF2\u6E05\u7406\u8BB0\u5F55\u3002`);
|
|
3779
|
-
return;
|
|
3780
|
-
}
|
|
3781
|
-
console.error(`\u2717 \u5173\u95ED\u5931\u8D25:${err.message}`);
|
|
3782
|
-
process.exit(1);
|
|
3783
|
-
}
|
|
3784
|
-
if (result === "killed") {
|
|
3785
|
-
console.log(`\u2713 \u5DF2\u5F3A\u5236\u5173\u95ED uid ${entry.id}\u3002`);
|
|
3786
|
-
return;
|
|
3787
|
-
}
|
|
3788
|
-
console.log(`\u2713 \u5DF2\u5173\u95ED uid ${entry.id}\u3002`);
|
|
3789
|
-
}
|
|
3790
|
-
function findOwningService(entry) {
|
|
3791
|
-
const candidates = [
|
|
3792
|
-
...typeof entry.webhookPort === "number" ? [{ serviceId: `port-${entry.webhookPort}`, flag: `--profile ${entry.profileName}` }] : [],
|
|
3793
|
-
{ serviceId: SUPERVISOR_SERVICE_ID, flag: `--profile ${entry.profileName}` }
|
|
3794
|
-
];
|
|
3795
|
-
for (const { serviceId, flag } of candidates) {
|
|
3796
|
-
const adapter = getServiceAdapter(serviceId);
|
|
3797
|
-
if (!adapter?.fileExists() || !adapter.isRunning()) continue;
|
|
3798
|
-
const { pid } = adapter.parseStatus(adapter.describeStatus());
|
|
3799
|
-
if (!pid || Number(pid) !== entry.pid) continue;
|
|
3800
|
-
return {
|
|
3801
|
-
platformName: adapter.platformName,
|
|
3802
|
-
stopHint: `xiaojiu-agent-bridge stop ${flag}`,
|
|
3803
|
-
restartHint: `xiaojiu-agent-bridge restart ${flag}`
|
|
3804
|
-
};
|
|
3805
|
-
}
|
|
3806
|
-
return void 0;
|
|
3807
|
-
}
|
|
3808
3715
|
async function stopProcessEntry(entry, timeoutMs = 2e3) {
|
|
3809
3716
|
process.kill(entry.pid, "SIGTERM");
|
|
3810
3717
|
const deadline = Date.now() + timeoutMs;
|
|
@@ -3951,8 +3858,8 @@ async function listSecretIds(storePaths = paths) {
|
|
|
3951
3858
|
}
|
|
3952
3859
|
|
|
3953
3860
|
// src/config/profile-store.ts
|
|
3954
|
-
import { chmod as chmod3, mkdir as mkdir12, readFile as readFile9, rename as rename2, rm as
|
|
3955
|
-
import { dirname as
|
|
3861
|
+
import { chmod as chmod3, mkdir as mkdir12, readFile as readFile9, rename as rename2, rm as rm12, rmdir, stat as stat2, writeFile as writeFile7 } from "fs/promises";
|
|
3862
|
+
import { dirname as dirname13, join as join11 } from "path";
|
|
3956
3863
|
import * as lockfile4 from "proper-lockfile";
|
|
3957
3864
|
async function loadRootConfig(path4) {
|
|
3958
3865
|
try {
|
|
@@ -4024,7 +3931,7 @@ function serializeProfileConfig(profile2) {
|
|
|
4024
3931
|
}
|
|
4025
3932
|
async function withConfigFileLock(configPath, fn) {
|
|
4026
3933
|
const lockTarget = `${configPath}.lock`;
|
|
4027
|
-
await mkdir12(
|
|
3934
|
+
await mkdir12(dirname13(lockTarget), { recursive: true });
|
|
4028
3935
|
await writeFile7(lockTarget, "", { flag: "a", mode: 384 });
|
|
4029
3936
|
await chmod3(lockTarget, 384).catch(() => {
|
|
4030
3937
|
});
|
|
@@ -4045,7 +3952,7 @@ async function withConfigFileLock(configPath, fn) {
|
|
|
4045
3952
|
}
|
|
4046
3953
|
}
|
|
4047
3954
|
async function readActiveProfile(rootDir) {
|
|
4048
|
-
const activeProfileFile =
|
|
3955
|
+
const activeProfileFile = join11(
|
|
4049
3956
|
rootDir ?? process.env.XIAOJIU_BRIDGE_HOME ?? resolveAppPaths().rootDir,
|
|
4050
3957
|
"active-profile"
|
|
4051
3958
|
);
|
|
@@ -4059,7 +3966,7 @@ async function readActiveProfile(rootDir) {
|
|
|
4059
3966
|
}
|
|
4060
3967
|
}
|
|
4061
3968
|
async function writeActiveProfile(rootDir, profile2) {
|
|
4062
|
-
const activeProfileFile =
|
|
3969
|
+
const activeProfileFile = join11(rootDir, "active-profile");
|
|
4063
3970
|
await writeFileAtomic(activeProfileFile, `${profile2}
|
|
4064
3971
|
`, { mode: 384 });
|
|
4065
3972
|
}
|
|
@@ -4134,7 +4041,7 @@ async function removeProfile(root, profile2, rootDir, opts = {}) {
|
|
|
4134
4041
|
const profileDir = resolveAppPaths({ rootDir, profile: profile2 }).profileDir;
|
|
4135
4042
|
if (opts.purge) {
|
|
4136
4043
|
if (!await pathExists(profileDir)) return { root: next, purged: true };
|
|
4137
|
-
const trashDir2 =
|
|
4044
|
+
const trashDir2 = join11(rootDir, ".trash");
|
|
4138
4045
|
await mkdir12(trashDir2, { recursive: true });
|
|
4139
4046
|
const stagedTo = await nextArchivePath(trashDir2, profile2, opts.now?.() ?? /* @__PURE__ */ new Date());
|
|
4140
4047
|
await rename2(profileDir, stagedTo);
|
|
@@ -4146,13 +4053,13 @@ async function removeProfile(root, profile2, rootDir, opts = {}) {
|
|
|
4146
4053
|
await rename2(stagedTo, profileDir);
|
|
4147
4054
|
},
|
|
4148
4055
|
cleanup: async () => {
|
|
4149
|
-
await
|
|
4056
|
+
await rm12(stagedTo, { recursive: true, force: true });
|
|
4150
4057
|
await rmdir(trashDir2).catch(() => {
|
|
4151
4058
|
});
|
|
4152
4059
|
}
|
|
4153
4060
|
};
|
|
4154
4061
|
}
|
|
4155
|
-
const trashDir =
|
|
4062
|
+
const trashDir = join11(rootDir, ".trash");
|
|
4156
4063
|
await mkdir12(trashDir, { recursive: true });
|
|
4157
4064
|
const archivedTo = await nextArchivePath(trashDir, profile2, opts.now?.() ?? /* @__PURE__ */ new Date());
|
|
4158
4065
|
await rename2(profileDir, archivedTo);
|
|
@@ -4165,7 +4072,7 @@ async function removeProfile(root, profile2, rootDir, opts = {}) {
|
|
|
4165
4072
|
};
|
|
4166
4073
|
}
|
|
4167
4074
|
async function nextArchivePath(trashDir, profile2, now) {
|
|
4168
|
-
const base =
|
|
4075
|
+
const base = join11(trashDir, `${profile2}-${archiveTimestamp(now)}`);
|
|
4169
4076
|
for (let suffix = 0; ; suffix++) {
|
|
4170
4077
|
const candidate = suffix === 0 ? base : `${base}-${suffix}`;
|
|
4171
4078
|
if (!await pathExists(candidate)) return candidate;
|
|
@@ -4191,7 +4098,7 @@ function agentKindFromString(value) {
|
|
|
4191
4098
|
|
|
4192
4099
|
// src/runtime/profile-discovery.ts
|
|
4193
4100
|
import { readdir as readdir5 } from "fs/promises";
|
|
4194
|
-
import { join as
|
|
4101
|
+
import { join as join12 } from "path";
|
|
4195
4102
|
async function listAllProfiles(rootDir) {
|
|
4196
4103
|
const rootPaths = resolveAppPaths({ rootDir });
|
|
4197
4104
|
const root = await loadRootConfig(rootPaths.configFile);
|
|
@@ -4229,7 +4136,7 @@ async function listAllProfiles(rootDir) {
|
|
|
4229
4136
|
});
|
|
4230
4137
|
}
|
|
4231
4138
|
async function readProfileStateDirs(rootDir) {
|
|
4232
|
-
const profilesDir =
|
|
4139
|
+
const profilesDir = join12(rootDir, "profiles");
|
|
4233
4140
|
try {
|
|
4234
4141
|
const entries = await readdir5(profilesDir, { withFileTypes: true });
|
|
4235
4142
|
return entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name);
|
|
@@ -4240,15 +4147,15 @@ async function readProfileStateDirs(rootDir) {
|
|
|
4240
4147
|
}
|
|
4241
4148
|
async function isLogOnlyProfileState(rootDir, profile2) {
|
|
4242
4149
|
try {
|
|
4243
|
-
const entries = await readdir5(
|
|
4150
|
+
const entries = await readdir5(join12(rootDir, "profiles", profile2), { withFileTypes: true });
|
|
4244
4151
|
return entries.length === 1 && entries[0]?.isDirectory() === true && entries[0].name === "logs";
|
|
4245
4152
|
} catch {
|
|
4246
4153
|
return false;
|
|
4247
4154
|
}
|
|
4248
4155
|
}
|
|
4249
|
-
function profileSort(a, b,
|
|
4250
|
-
if (a ===
|
|
4251
|
-
if (b ===
|
|
4156
|
+
function profileSort(a, b, active3) {
|
|
4157
|
+
if (a === active3) return -1;
|
|
4158
|
+
if (b === active3) return 1;
|
|
4252
4159
|
return a.localeCompare(b);
|
|
4253
4160
|
}
|
|
4254
4161
|
|
|
@@ -4288,12 +4195,12 @@ async function runSecretsGet() {
|
|
|
4288
4195
|
console.error(`secrets get: invalid stdin JSON: ${err.message}`);
|
|
4289
4196
|
process.exit(2);
|
|
4290
4197
|
}
|
|
4291
|
-
const
|
|
4198
|
+
const ids2 = req.ids ?? [];
|
|
4292
4199
|
const resp = {
|
|
4293
4200
|
protocolVersion: PROTOCOL_VERSION,
|
|
4294
4201
|
values: {}
|
|
4295
4202
|
};
|
|
4296
|
-
for (const id of
|
|
4203
|
+
for (const id of ids2) {
|
|
4297
4204
|
try {
|
|
4298
4205
|
const v = await resolveSecretAcrossProfiles(id);
|
|
4299
4206
|
if (v !== void 0) {
|
|
@@ -4323,14 +4230,14 @@ async function runSecretsSet(appId, opts = {}) {
|
|
|
4323
4230
|
}
|
|
4324
4231
|
async function runSecretsList(opts = {}) {
|
|
4325
4232
|
const appPaths2 = await resolveSecretProfilePaths(opts);
|
|
4326
|
-
const
|
|
4327
|
-
if (
|
|
4233
|
+
const ids2 = await listSecretIds(appPaths2);
|
|
4234
|
+
if (ids2.length === 0) {
|
|
4328
4235
|
console.log("\u5F53\u524D\u6CA1\u6709\u52A0\u5BC6\u5B58\u50A8\u7684 secret\u3002");
|
|
4329
4236
|
return;
|
|
4330
4237
|
}
|
|
4331
|
-
console.log(`# \u5F53\u524D\u5171 ${
|
|
4238
|
+
console.log(`# \u5F53\u524D\u5171 ${ids2.length} \u4E2A secret \u5728\u52A0\u5BC6\u5B58\u50A8\u91CC
|
|
4332
4239
|
`);
|
|
4333
|
-
for (const id of
|
|
4240
|
+
for (const id of ids2) {
|
|
4334
4241
|
console.log(` - ${id}`);
|
|
4335
4242
|
}
|
|
4336
4243
|
}
|
|
@@ -4350,16 +4257,16 @@ async function runSecretsRemove(appId, opts = {}) {
|
|
|
4350
4257
|
async function resolveSecretAcrossProfiles(id, rootDir = paths.rootDir, warn = (message) => console.error(message), profile2 = process.env.XIAOJIU_BRIDGE_PROFILE) {
|
|
4351
4258
|
if (profile2) {
|
|
4352
4259
|
const appPaths2 = resolveAppPaths({ rootDir, profile: profile2 });
|
|
4353
|
-
const
|
|
4354
|
-
if (!
|
|
4260
|
+
const ids2 = await listSecretIds(appPaths2);
|
|
4261
|
+
if (!ids2.includes(id)) return void 0;
|
|
4355
4262
|
return getSecret(id, appPaths2);
|
|
4356
4263
|
}
|
|
4357
4264
|
const profiles = await listSecretProfiles(rootDir);
|
|
4358
4265
|
const matches = [];
|
|
4359
4266
|
for (const profile3 of profiles) {
|
|
4360
4267
|
const appPaths2 = resolveAppPaths({ rootDir, profile: profile3.name });
|
|
4361
|
-
const
|
|
4362
|
-
if (
|
|
4268
|
+
const ids2 = await listSecretIds(appPaths2);
|
|
4269
|
+
if (ids2.includes(id)) matches.push(appPaths2);
|
|
4363
4270
|
}
|
|
4364
4271
|
if (matches.length === 0) return void 0;
|
|
4365
4272
|
if (matches.length > 1) {
|
|
@@ -4409,12 +4316,12 @@ async function readAllStdin() {
|
|
|
4409
4316
|
}
|
|
4410
4317
|
|
|
4411
4318
|
// src/cli/commands/profile.ts
|
|
4412
|
-
import { existsSync as
|
|
4413
|
-
import { rm as
|
|
4319
|
+
import { existsSync as existsSync9 } from "fs";
|
|
4320
|
+
import { rm as rm13 } from "fs/promises";
|
|
4414
4321
|
|
|
4415
4322
|
// src/config/secret-resolver.ts
|
|
4416
4323
|
import { readFile as readFile10 } from "fs/promises";
|
|
4417
|
-
import { join as
|
|
4324
|
+
import { join as join13, resolve as resolve2 } from "path";
|
|
4418
4325
|
var ENV_TEMPLATE_RE = /^\$\{([A-Z][A-Z0-9_]{0,127})\}$/;
|
|
4419
4326
|
var DEFAULT_PROVIDER = "default";
|
|
4420
4327
|
var DEFAULT_EXEC_TIMEOUT_MS = 5e3;
|
|
@@ -4470,7 +4377,7 @@ function resolveEnvRef(ref, pc) {
|
|
|
4470
4377
|
return v;
|
|
4471
4378
|
}
|
|
4472
4379
|
async function resolveFileRef(ref, pc) {
|
|
4473
|
-
const path4 = pc?.path ?
|
|
4380
|
+
const path4 = pc?.path ? join13(pc.path, ref.id) : ref.id;
|
|
4474
4381
|
const text2 = await readFile10(path4, "utf8");
|
|
4475
4382
|
return text2.trim();
|
|
4476
4383
|
}
|
|
@@ -4588,13 +4495,13 @@ async function spawnExecProvider(pc, ref) {
|
|
|
4588
4495
|
|
|
4589
4496
|
// src/runtime/profile-runtime.ts
|
|
4590
4497
|
import { mkdir as mkdir14, realpath as realpath4 } from "fs/promises";
|
|
4591
|
-
import { dirname as
|
|
4498
|
+
import { dirname as dirname16 } from "path";
|
|
4592
4499
|
import * as p2 from "@clack/prompts";
|
|
4593
4500
|
|
|
4594
4501
|
// src/cli/agent-detection.ts
|
|
4595
4502
|
import { constants } from "fs";
|
|
4596
4503
|
import { access } from "fs/promises";
|
|
4597
|
-
import { delimiter, extname, isAbsolute, join as
|
|
4504
|
+
import { delimiter, extname, isAbsolute, join as join14 } from "path";
|
|
4598
4505
|
async function resolveExecutablePath(command) {
|
|
4599
4506
|
if (isAbsolute(command)) {
|
|
4600
4507
|
await access(command, constants.X_OK);
|
|
@@ -4613,10 +4520,10 @@ async function resolveExecutablePath(command) {
|
|
|
4613
4520
|
throw new Error(`executable not found: ${command}`);
|
|
4614
4521
|
}
|
|
4615
4522
|
function executableCandidates(dir, command) {
|
|
4616
|
-
const candidates = [
|
|
4523
|
+
const candidates = [join14(dir, command)];
|
|
4617
4524
|
if (extname(command)) return candidates;
|
|
4618
4525
|
for (const ext of pathExts()) {
|
|
4619
|
-
candidates.push(
|
|
4526
|
+
candidates.push(join14(dir, `${command}${ext}`));
|
|
4620
4527
|
}
|
|
4621
4528
|
return candidates;
|
|
4622
4529
|
}
|
|
@@ -4646,12 +4553,12 @@ async function detectInstalledAgents() {
|
|
|
4646
4553
|
|
|
4647
4554
|
// src/cli/profile-bootstrap.ts
|
|
4648
4555
|
import { mkdir as mkdir13, realpath as realpath3 } from "fs/promises";
|
|
4649
|
-
import { join as
|
|
4556
|
+
import { join as join15 } from "path";
|
|
4650
4557
|
|
|
4651
4558
|
// src/policy/workspace.ts
|
|
4652
4559
|
import { realpath as realpath2, stat as stat3 } from "fs/promises";
|
|
4653
4560
|
import { homedir as homedir3, tmpdir as tmpdir2 } from "os";
|
|
4654
|
-
import { basename as basename3, dirname as
|
|
4561
|
+
import { basename as basename3, dirname as dirname14, resolve as resolve3 } from "path";
|
|
4655
4562
|
async function resolveWorkingDirectory(requestedCwd) {
|
|
4656
4563
|
const trimmed = requestedCwd.trim();
|
|
4657
4564
|
if (!trimmed) {
|
|
@@ -4681,17 +4588,17 @@ function reject(reason, requestedCwd, userVisible) {
|
|
|
4681
4588
|
return { ok: false, reason, requestedCwd, userVisible };
|
|
4682
4589
|
}
|
|
4683
4590
|
function classifyHighRiskWorkingDirectory(real, requestedCwd, tempRealpath, homeRealpath) {
|
|
4684
|
-
if (real ===
|
|
4591
|
+
if (real === dirname14(real)) {
|
|
4685
4592
|
return reject("filesystem-root", requestedCwd, "\u4E0D\u80FD\u628A\u6587\u4EF6\u7CFB\u7EDF\u6839\u76EE\u5F55\u8BBE\u4E3A\u5DE5\u4F5C\u76EE\u5F55\u3002");
|
|
4686
4593
|
}
|
|
4687
4594
|
const home = homeRealpath;
|
|
4688
4595
|
if (real === home) {
|
|
4689
4596
|
return reject("home-root", requestedCwd, "\u4E0D\u80FD\u628A Home \u6839\u76EE\u5F55\u8BBE\u4E3A\u5DE5\u4F5C\u76EE\u5F55\uFF0C\u8BF7\u9009\u62E9\u66F4\u5177\u4F53\u7684\u5B50\u76EE\u5F55\u3002");
|
|
4690
4597
|
}
|
|
4691
|
-
if (real ===
|
|
4598
|
+
if (real === dirname14(home)) {
|
|
4692
4599
|
return reject("user-root", requestedCwd, "\u4E0D\u80FD\u628A\u7528\u6237\u76EE\u5F55\u6839\u8BBE\u4E3A\u5DE5\u4F5C\u76EE\u5F55\uFF0C\u8BF7\u9009\u62E9\u66F4\u5177\u4F53\u7684\u5B50\u76EE\u5F55\u3002");
|
|
4693
4600
|
}
|
|
4694
|
-
if (
|
|
4601
|
+
if (dirname14(real) === home && (/* @__PURE__ */ new Set(["Desktop", "Downloads"])).has(basename3(real))) {
|
|
4695
4602
|
return reject("broad-user-folder", requestedCwd, "\u8FD9\u4E2A\u76EE\u5F55\u8303\u56F4\u8FC7\u5927\uFF0C\u8BF7\u9009\u62E9\u66F4\u5177\u4F53\u7684\u5B50\u76EE\u5F55\u3002");
|
|
4696
4603
|
}
|
|
4697
4604
|
const temp = resolve3(tmpdir2());
|
|
@@ -4712,7 +4619,7 @@ function classifyHighRiskWorkingDirectory(real, requestedCwd, tempRealpath, home
|
|
|
4712
4619
|
if (systemRoots.has(real)) {
|
|
4713
4620
|
return reject("system-root", requestedCwd, "\u4E0D\u80FD\u628A\u7CFB\u7EDF\u76EE\u5F55\u8BBE\u4E3A\u5DE5\u4F5C\u76EE\u5F55\u3002");
|
|
4714
4621
|
}
|
|
4715
|
-
if (real === "/Volumes" ||
|
|
4622
|
+
if (real === "/Volumes" || dirname14(real) === "/Volumes") {
|
|
4716
4623
|
return reject("volume-root", requestedCwd, "\u4E0D\u80FD\u628A\u78C1\u76D8\u5377\u6839\u76EE\u5F55\u8BBE\u4E3A\u5DE5\u4F5C\u76EE\u5F55\uFF0C\u8BF7\u9009\u62E9\u66F4\u5177\u4F53\u7684\u5B50\u76EE\u5F55\u3002");
|
|
4717
4624
|
}
|
|
4718
4625
|
return void 0;
|
|
@@ -4742,7 +4649,7 @@ async function createBootstrapProfileConfig(input) {
|
|
|
4742
4649
|
};
|
|
4743
4650
|
}
|
|
4744
4651
|
if (input.profileDir && profile2.codex?.inheritCodexHome === false) {
|
|
4745
|
-
await mkdir13(
|
|
4652
|
+
await mkdir13(join15(input.profileDir, "codex-home"), { recursive: true });
|
|
4746
4653
|
}
|
|
4747
4654
|
return profile2;
|
|
4748
4655
|
}
|
|
@@ -4965,7 +4872,7 @@ function cancel2() {
|
|
|
4965
4872
|
|
|
4966
4873
|
// src/config/store.ts
|
|
4967
4874
|
import { readFile as readFile11 } from "fs/promises";
|
|
4968
|
-
import { dirname as
|
|
4875
|
+
import { dirname as dirname15, resolve as resolve4 } from "path";
|
|
4969
4876
|
async function loadConfig(path4 = paths.configFile) {
|
|
4970
4877
|
try {
|
|
4971
4878
|
const text2 = await readFile11(path4, "utf8");
|
|
@@ -5010,7 +4917,7 @@ async function ensureSecretsGetterWrapper(appPaths2 = paths, opts = {}) {
|
|
|
5010
4917
|
const node = opts.nodePath ?? process.execPath;
|
|
5011
4918
|
const bridgeEntry = opts.bridgeEntry ?? resolveDaemonEntryPath(process.argv[1]);
|
|
5012
4919
|
const quotedBridgeEntry = platform2 === "win32" ? bridgeEntry : resolveDaemonEntryPath(bridgeEntry);
|
|
5013
|
-
const rootDir = resolve4(appPaths2.rootDir ??
|
|
4920
|
+
const rootDir = resolve4(appPaths2.rootDir ?? dirname15(appPaths2.secretsGetterScript));
|
|
5014
4921
|
if (platform2 === "win32") {
|
|
5015
4922
|
const dq = (s) => `"${s.replace(/"/g, '""')}"`;
|
|
5016
4923
|
const content2 = `@echo off\r
|
|
@@ -5147,8 +5054,8 @@ var DEFAULT_RATE_LIMIT_RETRIES = 3;
|
|
|
5147
5054
|
var DEFAULT_BACKOFF_MS = 200;
|
|
5148
5055
|
var DEFAULT_MAX_BACKOFF_MS = 2e3;
|
|
5149
5056
|
var DEFAULT_SEND_MESSAGE_API_VERSION2 = "v2";
|
|
5150
|
-
function sendMessagePath(
|
|
5151
|
-
return `/open/im/${
|
|
5057
|
+
function sendMessagePath(version3 = DEFAULT_SEND_MESSAGE_API_VERSION2) {
|
|
5058
|
+
return `/open/im/${version3}/messages`;
|
|
5152
5059
|
}
|
|
5153
5060
|
var XiaojiuApiError = class extends Error {
|
|
5154
5061
|
code;
|
|
@@ -5568,7 +5475,7 @@ function createRuntimeProfileConfig(input) {
|
|
|
5568
5475
|
});
|
|
5569
5476
|
}
|
|
5570
5477
|
async function resolveProfileRuntime(opts) {
|
|
5571
|
-
const rootDir = opts.config ?
|
|
5478
|
+
const rootDir = opts.config ? dirname16(opts.config) : void 0;
|
|
5572
5479
|
const requestedAgent = agentKindFromString(opts.agent);
|
|
5573
5480
|
const explicitProfile = opts.profile;
|
|
5574
5481
|
const activeProfile = explicitProfile ?? await readActiveProfile(rootDir);
|
|
@@ -5968,7 +5875,7 @@ function assertBootstrapAppMatchesExistingConfig(opts, profile2, cfg) {
|
|
|
5968
5875
|
);
|
|
5969
5876
|
}
|
|
5970
5877
|
async function materializeEnvSecretForService(opts = {}) {
|
|
5971
|
-
const rootDir = opts.config ?
|
|
5878
|
+
const rootDir = opts.config ? dirname16(opts.config) : void 0;
|
|
5972
5879
|
const explicitProfile = opts.profile;
|
|
5973
5880
|
const activeProfile = explicitProfile ?? await readActiveProfile(rootDir);
|
|
5974
5881
|
let profile2 = activeProfile ?? "claude";
|
|
@@ -6300,8 +6207,11 @@ async function runProfileRemove(name, opts = {}) {
|
|
|
6300
6207
|
const profilePaths = resolveAppPaths({ rootDir, profile: name });
|
|
6301
6208
|
const profileLock = await checkRuntimeLock(profilePaths.profileLockFile);
|
|
6302
6209
|
if (profileLock.locked) {
|
|
6303
|
-
const
|
|
6304
|
-
|
|
6210
|
+
const broken = await breakDeadRuntimeLock(profilePaths.profileLockFile);
|
|
6211
|
+
if (!broken) {
|
|
6212
|
+
const holder = profileLock.meta ? ` pid=${profileLock.meta.pid} startedAt=${profileLock.meta.startedAt}` : "";
|
|
6213
|
+
throw new Error(`profile is locked/running: ${name}${holder}`);
|
|
6214
|
+
}
|
|
6305
6215
|
}
|
|
6306
6216
|
const lock6 = await acquireProfileRuntimeLock(profilePaths, profile2.agentKind);
|
|
6307
6217
|
try {
|
|
@@ -6311,8 +6221,8 @@ async function runProfileRemove(name, opts = {}) {
|
|
|
6311
6221
|
});
|
|
6312
6222
|
try {
|
|
6313
6223
|
if (Object.keys(result.root.profiles).length === 0) {
|
|
6314
|
-
await
|
|
6315
|
-
await
|
|
6224
|
+
await rm13(configFile, { force: true });
|
|
6225
|
+
await rm13(resolveAppPaths({ rootDir }).activeProfileFile, { force: true });
|
|
6316
6226
|
} else {
|
|
6317
6227
|
await saveRootConfig(result.root, configFile);
|
|
6318
6228
|
await writeActiveProfile(rootDir, result.root.activeProfile);
|
|
@@ -6378,7 +6288,7 @@ async function runProfileExport(name, opts = {}) {
|
|
|
6378
6288
|
console.log(body.trimEnd());
|
|
6379
6289
|
return;
|
|
6380
6290
|
}
|
|
6381
|
-
if (
|
|
6291
|
+
if (existsSync9(opts.output) && !opts.force) {
|
|
6382
6292
|
throw new Error("output already exists; use --force");
|
|
6383
6293
|
}
|
|
6384
6294
|
await writeFileAtomic(opts.output, body, { mode: 384 });
|
|
@@ -6389,10 +6299,10 @@ function cloneJson(value) {
|
|
|
6389
6299
|
}
|
|
6390
6300
|
|
|
6391
6301
|
// src/selfupdate/runtime.ts
|
|
6392
|
-
import { existsSync as
|
|
6302
|
+
import { existsSync as existsSync10, readFileSync as readFileSync5, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "fs";
|
|
6393
6303
|
import { copyFile, mkdir as mkdir15 } from "fs/promises";
|
|
6394
|
-
import { dirname as
|
|
6395
|
-
import { fileURLToPath as
|
|
6304
|
+
import { dirname as dirname17 } from "path";
|
|
6305
|
+
import { fileURLToPath as fileURLToPath4 } from "url";
|
|
6396
6306
|
|
|
6397
6307
|
// src/selfupdate/protocol.ts
|
|
6398
6308
|
var SWITCH_EXIT_CODE = 75;
|
|
@@ -6403,11 +6313,24 @@ var ENV_BOOT_FILE = "XIAOJIU_BRIDGE_BOOT_FILE";
|
|
|
6403
6313
|
function isUnderLauncher(env = process.env) {
|
|
6404
6314
|
return env[ENV_LAUNCHER] === "1";
|
|
6405
6315
|
}
|
|
6316
|
+
function launcherPidFromEnv(env = process.env) {
|
|
6317
|
+
if (env[ENV_LAUNCHER] !== "1") return void 0;
|
|
6318
|
+
const file = env[ENV_BOOT_FILE];
|
|
6319
|
+
if (!file) return void 0;
|
|
6320
|
+
try {
|
|
6321
|
+
const parsed = JSON.parse(readFileSync5(file, "utf8"));
|
|
6322
|
+
if (typeof parsed !== "object" || parsed === null || !("pid" in parsed)) return void 0;
|
|
6323
|
+
const pid = parsed.pid;
|
|
6324
|
+
return typeof pid === "number" && pid !== process.pid ? pid : void 0;
|
|
6325
|
+
} catch {
|
|
6326
|
+
return void 0;
|
|
6327
|
+
}
|
|
6328
|
+
}
|
|
6406
6329
|
function markBootReady(env = process.env) {
|
|
6407
6330
|
const file = env[ENV_BOOT_FILE];
|
|
6408
6331
|
if (!file) return;
|
|
6409
6332
|
try {
|
|
6410
|
-
const parsed = JSON.parse(
|
|
6333
|
+
const parsed = JSON.parse(readFileSync5(file, "utf8"));
|
|
6411
6334
|
if (typeof parsed !== "object" || parsed === null) return;
|
|
6412
6335
|
const tmp = `${file}.ready-${process.pid}`;
|
|
6413
6336
|
writeFileSync2(tmp, `${JSON.stringify({ ...parsed, ready: true }, null, 2)}
|
|
@@ -6415,34 +6338,103 @@ function markBootReady(env = process.env) {
|
|
|
6415
6338
|
renameSync2(tmp, file);
|
|
6416
6339
|
} catch {
|
|
6417
6340
|
}
|
|
6418
|
-
}
|
|
6419
|
-
async function ensureLauncherFresh(layout, bundledLauncherFile = defaultBundledLauncher()) {
|
|
6420
|
-
if (!
|
|
6421
|
-
const bundled =
|
|
6422
|
-
try {
|
|
6423
|
-
if (
|
|
6424
|
-
} catch {
|
|
6341
|
+
}
|
|
6342
|
+
async function ensureLauncherFresh(layout, bundledLauncherFile = defaultBundledLauncher()) {
|
|
6343
|
+
if (!existsSync10(bundledLauncherFile)) return false;
|
|
6344
|
+
const bundled = readFileSync5(bundledLauncherFile);
|
|
6345
|
+
try {
|
|
6346
|
+
if (readFileSync5(layout.launcherFile).equals(bundled)) return true;
|
|
6347
|
+
} catch {
|
|
6348
|
+
}
|
|
6349
|
+
await mkdir15(dirname17(layout.launcherFile), { recursive: true });
|
|
6350
|
+
await copyFile(bundledLauncherFile, layout.launcherFile);
|
|
6351
|
+
return true;
|
|
6352
|
+
}
|
|
6353
|
+
async function prepareLauncherInstall(layout, runningVersion, deps = {}) {
|
|
6354
|
+
const existing = await readCurrent(layout);
|
|
6355
|
+
if (existing && await ensureLauncherFresh(layout)) return existing;
|
|
6356
|
+
const staged = await (deps.stage ?? stageVersion)({ layout, targetVersion: runningVersion });
|
|
6357
|
+
if (!staged.ok) throw new Error(`failed to seed versions store: ${staged.error}`);
|
|
6358
|
+
if (!existing) {
|
|
6359
|
+
await writeCurrent(layout, { version: runningVersion, dir: staged.dir });
|
|
6360
|
+
}
|
|
6361
|
+
const ok = await ensureLauncherFresh(layout);
|
|
6362
|
+
if (!ok) throw new Error("bundled dist/launcher.js not found; cannot adopt launcher mode");
|
|
6363
|
+
const pointer = await readCurrent(layout);
|
|
6364
|
+
if (!pointer) throw new Error("version pointer missing after seeding");
|
|
6365
|
+
return pointer;
|
|
6366
|
+
}
|
|
6367
|
+
function defaultBundledLauncher() {
|
|
6368
|
+
return fileURLToPath4(new URL("./launcher.js", import.meta.url));
|
|
6369
|
+
}
|
|
6370
|
+
|
|
6371
|
+
// src/cli/commands/listen-client.ts
|
|
6372
|
+
var ListenApiError = class extends Error {
|
|
6373
|
+
constructor(message, status) {
|
|
6374
|
+
super(message);
|
|
6375
|
+
this.status = status;
|
|
6376
|
+
}
|
|
6377
|
+
status;
|
|
6378
|
+
};
|
|
6379
|
+
function apiUrl(sidecar, path4) {
|
|
6380
|
+
const url = new URL(sidecar.url);
|
|
6381
|
+
url.pathname = path4;
|
|
6382
|
+
url.search = "";
|
|
6383
|
+
url.searchParams.set("token", sidecar.token);
|
|
6384
|
+
return url.toString();
|
|
6385
|
+
}
|
|
6386
|
+
function errorMessage(parsed, fallback) {
|
|
6387
|
+
if (parsed && typeof parsed === "object" && "error" in parsed) {
|
|
6388
|
+
const error = parsed.error;
|
|
6389
|
+
if (typeof error === "string" && error.trim()) return error;
|
|
6390
|
+
}
|
|
6391
|
+
return fallback;
|
|
6392
|
+
}
|
|
6393
|
+
async function postJson(sidecar, path4, body) {
|
|
6394
|
+
const response = await fetch(apiUrl(sidecar, path4), {
|
|
6395
|
+
method: "POST",
|
|
6396
|
+
headers: {
|
|
6397
|
+
"content-type": "application/json",
|
|
6398
|
+
"x-ui-token": sidecar.token
|
|
6399
|
+
},
|
|
6400
|
+
body: JSON.stringify(body)
|
|
6401
|
+
});
|
|
6402
|
+
const text2 = await response.text();
|
|
6403
|
+
let parsed = {};
|
|
6404
|
+
if (text2) {
|
|
6405
|
+
try {
|
|
6406
|
+
parsed = JSON.parse(text2);
|
|
6407
|
+
} catch {
|
|
6408
|
+
parsed = { error: text2 };
|
|
6409
|
+
}
|
|
6410
|
+
}
|
|
6411
|
+
if (!response.ok) {
|
|
6412
|
+
throw new ListenApiError(errorMessage(parsed, `HTTP ${response.status}`), response.status);
|
|
6425
6413
|
}
|
|
6426
|
-
|
|
6427
|
-
await copyFile(bundledLauncherFile, layout.launcherFile);
|
|
6428
|
-
return true;
|
|
6414
|
+
return parsed;
|
|
6429
6415
|
}
|
|
6430
|
-
async function
|
|
6431
|
-
|
|
6432
|
-
if (existing && await ensureLauncherFresh(layout)) return existing;
|
|
6433
|
-
const staged = await (deps.stage ?? stageVersion)({ layout, targetVersion: runningVersion });
|
|
6434
|
-
if (!staged.ok) throw new Error(`failed to seed versions store: ${staged.error}`);
|
|
6435
|
-
if (!existing) {
|
|
6436
|
-
await writeCurrent(layout, { version: runningVersion, dir: staged.dir });
|
|
6437
|
-
}
|
|
6438
|
-
const ok = await ensureLauncherFresh(layout);
|
|
6439
|
-
if (!ok) throw new Error("bundled dist/launcher.js not found; cannot adopt launcher mode");
|
|
6440
|
-
const pointer = await readCurrent(layout);
|
|
6441
|
-
if (!pointer) throw new Error("version pointer missing after seeding");
|
|
6442
|
-
return pointer;
|
|
6416
|
+
async function joinListenProfile(sidecar, profile2) {
|
|
6417
|
+
await postJson(sidecar, "/api/profiles/start", { profile: profile2 });
|
|
6443
6418
|
}
|
|
6444
|
-
function
|
|
6445
|
-
|
|
6419
|
+
async function leaveListenProfile(sidecar, profile2) {
|
|
6420
|
+
await postJson(sidecar, "/api/profiles/stop", { profile: profile2 });
|
|
6421
|
+
}
|
|
6422
|
+
async function listListenBots(sidecar) {
|
|
6423
|
+
const response = await fetch(apiUrl(sidecar, "/api/bots"), {
|
|
6424
|
+
headers: { "x-ui-token": sidecar.token }
|
|
6425
|
+
});
|
|
6426
|
+
if (!response.ok) throw new ListenApiError(`HTTP ${response.status}`, response.status);
|
|
6427
|
+
const parsed = await response.json();
|
|
6428
|
+
if (!parsed || typeof parsed !== "object" || !("bots" in parsed) || !Array.isArray(parsed.bots)) {
|
|
6429
|
+
return [];
|
|
6430
|
+
}
|
|
6431
|
+
const names = [];
|
|
6432
|
+
for (const bot of parsed.bots) {
|
|
6433
|
+
if (bot && typeof bot === "object" && "profileName" in bot && typeof bot.profileName === "string") {
|
|
6434
|
+
names.push({ profileName: bot.profileName });
|
|
6435
|
+
}
|
|
6436
|
+
}
|
|
6437
|
+
return names;
|
|
6446
6438
|
}
|
|
6447
6439
|
|
|
6448
6440
|
// src/cli/commands/service.ts
|
|
@@ -6717,6 +6709,19 @@ async function runServiceStart(opts = {}) {
|
|
|
6717
6709
|
await adapter.install();
|
|
6718
6710
|
await reportReadyAfter("started", profile2, adapter.start, serviceId, port, opts.webUi);
|
|
6719
6711
|
}
|
|
6712
|
+
async function runKillCli(target) {
|
|
6713
|
+
if (!target) {
|
|
6714
|
+
console.error("\u7528\u6CD5: xiaojiu-agent-bridge kill <uid\u3001\u8FDB\u7A0B \u6216\u5E8F\u53F7>");
|
|
6715
|
+
process.exit(1);
|
|
6716
|
+
}
|
|
6717
|
+
const entry = resolveTarget(target);
|
|
6718
|
+
if (!entry) {
|
|
6719
|
+
console.error(`\u2717 \u6CA1\u627E\u5230\u5339\u914D\u7684 bot:${target}`);
|
|
6720
|
+
console.error(" \u7528 `xiaojiu-agent-bridge ps` \u770B\u53EF\u9009\u76EE\u6807\u3002");
|
|
6721
|
+
process.exit(1);
|
|
6722
|
+
}
|
|
6723
|
+
await runServiceStop({ profile: entry.profileName });
|
|
6724
|
+
}
|
|
6720
6725
|
async function runServiceStop(opts = {}) {
|
|
6721
6726
|
const { profile: profile2 } = await resolveServiceTarget(opts);
|
|
6722
6727
|
const runtime = await maybeResolveProfileRuntime(profile2);
|
|
@@ -6745,17 +6750,42 @@ async function runServiceStop(opts = {}) {
|
|
|
6745
6750
|
printStopped(profile2, entry, listen3.pid);
|
|
6746
6751
|
return;
|
|
6747
6752
|
}
|
|
6748
|
-
await
|
|
6753
|
+
await stopLauncherSupervisor(entry);
|
|
6754
|
+
await stopPidTolerant(listen3.pid);
|
|
6749
6755
|
await removeListenSidecar(listenSidecarFile(port, runtime?.appPaths.rootDir));
|
|
6750
6756
|
await forceReleaseHostLock(listenLockFile(port, runtime?.appPaths.rootDir));
|
|
6751
|
-
|
|
6752
|
-
if (adapter?.fileExists()) await adapter.stopAndDisableAutostart();
|
|
6757
|
+
await stopOwningServices(profile2, port);
|
|
6753
6758
|
printStopped(profile2, entry, listen3.pid);
|
|
6754
6759
|
return;
|
|
6755
6760
|
}
|
|
6756
|
-
if (entry)
|
|
6761
|
+
if (entry) {
|
|
6762
|
+
await stopLauncherSupervisor(entry);
|
|
6763
|
+
await stopProcessEntry(entry);
|
|
6764
|
+
}
|
|
6757
6765
|
printStopped(profile2, entry, entry?.pid);
|
|
6758
6766
|
}
|
|
6767
|
+
async function stopLauncherSupervisor(entry) {
|
|
6768
|
+
const launcherPid = entry?.launcherPid;
|
|
6769
|
+
if (typeof launcherPid !== "number" || !isAlive(launcherPid)) return;
|
|
6770
|
+
try {
|
|
6771
|
+
await stopPidTolerant(launcherPid);
|
|
6772
|
+
} catch (err) {
|
|
6773
|
+
log.warn("service", "launcher-stop-failed", { pid: launcherPid, err: String(err) });
|
|
6774
|
+
}
|
|
6775
|
+
}
|
|
6776
|
+
async function stopPidTolerant(pid) {
|
|
6777
|
+
try {
|
|
6778
|
+
await stopProcessEntry({ pid });
|
|
6779
|
+
} catch (err) {
|
|
6780
|
+
if (err.code !== "ESRCH") throw err;
|
|
6781
|
+
}
|
|
6782
|
+
}
|
|
6783
|
+
async function stopOwningServices(profile2, port) {
|
|
6784
|
+
for (const serviceId of /* @__PURE__ */ new Set([listenServiceId(port), profile2])) {
|
|
6785
|
+
const adapter = getServiceAdapter(serviceId);
|
|
6786
|
+
if (adapter?.fileExists()) await adapter.stopAndDisableAutostart();
|
|
6787
|
+
}
|
|
6788
|
+
}
|
|
6759
6789
|
async function runServiceRestart(opts = {}) {
|
|
6760
6790
|
await runServiceStop(opts);
|
|
6761
6791
|
await runServiceStart(opts);
|
|
@@ -6858,15 +6888,15 @@ function agentDisplay(agentKind) {
|
|
|
6858
6888
|
// src/cli/commands/start.ts
|
|
6859
6889
|
import dns from "dns";
|
|
6860
6890
|
import os from "os";
|
|
6861
|
-
import { readdir as
|
|
6862
|
-
import { join as
|
|
6863
|
-
import { createInterface as
|
|
6891
|
+
import { readdir as readdir14 } from "fs/promises";
|
|
6892
|
+
import { join as join32 } from "path";
|
|
6893
|
+
import { createInterface as createInterface11 } from "readline";
|
|
6864
6894
|
|
|
6865
6895
|
// src/agent/claude/adapter.ts
|
|
6866
6896
|
import { mkdtempSync, rmSync, writeFileSync as writeFileSync3 } from "fs";
|
|
6867
6897
|
import { tmpdir as tmpdir3 } from "os";
|
|
6868
|
-
import { join as
|
|
6869
|
-
import { createInterface as
|
|
6898
|
+
import { join as join18 } from "path";
|
|
6899
|
+
import { createInterface as createInterface4 } from "readline";
|
|
6870
6900
|
|
|
6871
6901
|
// src/agent/system-prompt.ts
|
|
6872
6902
|
import { createHash as createHash2 } from "crypto";
|
|
@@ -6956,17 +6986,210 @@ function hiddenSystemPromptFingerprint(identity, overlay = {}) {
|
|
|
6956
6986
|
// src/agent/types.ts
|
|
6957
6987
|
var CLAUDE_DEFAULT_PERMISSION_MODE = "bypassPermissions";
|
|
6958
6988
|
|
|
6959
|
-
// src/agent/
|
|
6989
|
+
// src/agent/claude/side-query.ts
|
|
6990
|
+
import { readdir as readdir7, rm as rm14 } from "fs/promises";
|
|
6991
|
+
import { homedir as homedir5 } from "os";
|
|
6992
|
+
import { join as join17 } from "path";
|
|
6993
|
+
|
|
6994
|
+
// src/agent/btw-prompt.ts
|
|
6995
|
+
var BTW_DEFAULT_QUESTION = "\u8BF7\u7528\u51E0\u884C\u8BF4\u660E\u5F53\u524D\u8FDB\u5C55\u3001\u6B63\u5728\u505A\u4EC0\u4E48\u3001\u4E0B\u4E00\u6B65\uFF1B\u4E0D\u8981\u52A8\u624B\u3002";
|
|
6996
|
+
function buildBtwPrompt(question) {
|
|
6997
|
+
const body = question.trim() || BTW_DEFAULT_QUESTION;
|
|
6998
|
+
return [
|
|
6999
|
+
"<btw>",
|
|
7000
|
+
"Ephemeral side question for current session.",
|
|
7001
|
+
"Answer briefly, directly; use conversation context already provided.",
|
|
7002
|
+
"NEVER use tools.",
|
|
7003
|
+
"NEVER ask follow-up questions.",
|
|
7004
|
+
"Question:",
|
|
7005
|
+
body,
|
|
7006
|
+
"</btw>"
|
|
7007
|
+
].join("\n");
|
|
7008
|
+
}
|
|
7009
|
+
|
|
7010
|
+
// src/agent/jsonl-side-query.ts
|
|
6960
7011
|
import { createInterface as createInterface2 } from "readline";
|
|
7012
|
+
|
|
7013
|
+
// src/core/deferred.ts
|
|
7014
|
+
function deferred() {
|
|
7015
|
+
let resolve5 = () => {
|
|
7016
|
+
};
|
|
7017
|
+
const promise = new Promise((r) => {
|
|
7018
|
+
resolve5 = r;
|
|
7019
|
+
});
|
|
7020
|
+
return { promise, resolve: resolve5 };
|
|
7021
|
+
}
|
|
7022
|
+
|
|
7023
|
+
// src/agent/jsonl-side-query.ts
|
|
7024
|
+
var TEXT_MAX = 8e3;
|
|
7025
|
+
var STDERR_MAX = 16384;
|
|
7026
|
+
async function runJsonlSideQuery(spec) {
|
|
7027
|
+
const child = spawnProcess(spec.binary, spec.args, {
|
|
7028
|
+
cwd: spec.cwd,
|
|
7029
|
+
env: spec.env ? mergeProcessEnv(process.env, spec.env) : process.env,
|
|
7030
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
7031
|
+
detached: process.platform !== "win32"
|
|
7032
|
+
});
|
|
7033
|
+
const stderr = [];
|
|
7034
|
+
let stderrBytes = 0;
|
|
7035
|
+
child.stderr.on("data", (chunk) => {
|
|
7036
|
+
if (stderrBytes >= STDERR_MAX) return;
|
|
7037
|
+
stderrBytes += chunk.length;
|
|
7038
|
+
stderr.push(chunk);
|
|
7039
|
+
});
|
|
7040
|
+
let spawnError;
|
|
7041
|
+
child.once("error", (err) => {
|
|
7042
|
+
spawnError = err instanceof Error ? err : new Error(String(err));
|
|
7043
|
+
});
|
|
7044
|
+
let aborted = false;
|
|
7045
|
+
const onAbort = () => {
|
|
7046
|
+
aborted = true;
|
|
7047
|
+
killProcessTree(child, true);
|
|
7048
|
+
};
|
|
7049
|
+
spec.signal.addEventListener("abort", onAbort, { once: true });
|
|
7050
|
+
if (spec.signal.aborted) onAbort();
|
|
7051
|
+
let streamed = "";
|
|
7052
|
+
let finalText = "";
|
|
7053
|
+
let sessionId;
|
|
7054
|
+
let threadId;
|
|
7055
|
+
let failure;
|
|
7056
|
+
child.stdin.on("error", () => {
|
|
7057
|
+
});
|
|
7058
|
+
child.stdin.end(spec.prompt, "utf8");
|
|
7059
|
+
try {
|
|
7060
|
+
if (child.pid) {
|
|
7061
|
+
const rl = createInterface2({ input: child.stdout, crlfDelay: Infinity });
|
|
7062
|
+
try {
|
|
7063
|
+
for await (const line of rl) {
|
|
7064
|
+
const trimmed = line.trim();
|
|
7065
|
+
if (!trimmed) continue;
|
|
7066
|
+
let raw;
|
|
7067
|
+
try {
|
|
7068
|
+
raw = JSON.parse(trimmed);
|
|
7069
|
+
} catch {
|
|
7070
|
+
continue;
|
|
7071
|
+
}
|
|
7072
|
+
for (const evt of spec.translate(raw)) {
|
|
7073
|
+
if (evt.type === "system") {
|
|
7074
|
+
sessionId ??= evt.sessionId;
|
|
7075
|
+
threadId ??= evt.threadId;
|
|
7076
|
+
} else if (evt.type === "text") {
|
|
7077
|
+
if (streamed.length < TEXT_MAX) streamed += evt.delta;
|
|
7078
|
+
} else if (evt.type === "final_text") {
|
|
7079
|
+
finalText = evt.content;
|
|
7080
|
+
} else if (evt.type === "error") {
|
|
7081
|
+
failure = evt.message;
|
|
7082
|
+
}
|
|
7083
|
+
}
|
|
7084
|
+
}
|
|
7085
|
+
} finally {
|
|
7086
|
+
rl.close();
|
|
7087
|
+
}
|
|
7088
|
+
}
|
|
7089
|
+
} catch (err) {
|
|
7090
|
+
failure ??= err instanceof Error ? err.message : String(err);
|
|
7091
|
+
} finally {
|
|
7092
|
+
spec.signal.removeEventListener("abort", onAbort);
|
|
7093
|
+
await waitForChildExit(child, 2e3);
|
|
7094
|
+
if (child.exitCode === null && child.signalCode === null) killProcessTree(child, true);
|
|
7095
|
+
}
|
|
7096
|
+
const text2 = (finalText || streamed).trim().slice(0, TEXT_MAX);
|
|
7097
|
+
const result = { text: text2 };
|
|
7098
|
+
if (sessionId) result.sessionId = sessionId;
|
|
7099
|
+
if (threadId) result.threadId = threadId;
|
|
7100
|
+
if (aborted) {
|
|
7101
|
+
result.error = "aborted";
|
|
7102
|
+
return result;
|
|
7103
|
+
}
|
|
7104
|
+
if (spawnError) {
|
|
7105
|
+
result.error = `failed to spawn ${spec.agent}: ${spawnError.message}`;
|
|
7106
|
+
return result;
|
|
7107
|
+
}
|
|
7108
|
+
if (failure && !text2) {
|
|
7109
|
+
result.error = failure;
|
|
7110
|
+
return result;
|
|
7111
|
+
}
|
|
7112
|
+
if (!text2) {
|
|
7113
|
+
const detail = Buffer.concat(stderr).toString("utf8").trim().replace(/\s+/g, " ").slice(0, 300);
|
|
7114
|
+
result.error = detail || `${spec.agent} \u6CA1\u6709\u8FD4\u56DE\u7B54\u6848`;
|
|
7115
|
+
}
|
|
7116
|
+
return result;
|
|
7117
|
+
}
|
|
7118
|
+
function waitForChildExit(child, timeoutMs) {
|
|
7119
|
+
if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve(true);
|
|
7120
|
+
const { promise, resolve: resolve5 } = deferred();
|
|
7121
|
+
let settled = false;
|
|
7122
|
+
const finish = (exited) => {
|
|
7123
|
+
if (settled) return;
|
|
7124
|
+
settled = true;
|
|
7125
|
+
clearTimeout(timer);
|
|
7126
|
+
resolve5(exited);
|
|
7127
|
+
};
|
|
7128
|
+
const timer = setTimeout(() => finish(false), timeoutMs);
|
|
7129
|
+
child.once("exit", () => finish(true));
|
|
7130
|
+
return promise;
|
|
7131
|
+
}
|
|
7132
|
+
|
|
7133
|
+
// src/session/btw-sessions.ts
|
|
7134
|
+
var ids = /* @__PURE__ */ new Map();
|
|
7135
|
+
function markBtwSession(agentKind, sessionId) {
|
|
7136
|
+
let set = ids.get(agentKind);
|
|
7137
|
+
if (!set) {
|
|
7138
|
+
set = /* @__PURE__ */ new Set();
|
|
7139
|
+
ids.set(agentKind, set);
|
|
7140
|
+
}
|
|
7141
|
+
set.add(sessionId);
|
|
7142
|
+
if (set.size > 200) {
|
|
7143
|
+
const oldest = set.values().next().value;
|
|
7144
|
+
if (oldest !== void 0) set.delete(oldest);
|
|
7145
|
+
}
|
|
7146
|
+
}
|
|
7147
|
+
function isBtwSession(agentKind, sessionId) {
|
|
7148
|
+
return ids.get(agentKind)?.has(sessionId) ?? false;
|
|
7149
|
+
}
|
|
7150
|
+
|
|
7151
|
+
// src/agent/claude/session-paths.ts
|
|
7152
|
+
import { readdir as readdir6, stat as stat4 } from "fs/promises";
|
|
7153
|
+
import { homedir as homedir4 } from "os";
|
|
7154
|
+
import { join as join16 } from "path";
|
|
7155
|
+
function claudeProjectDir(cwd, projectsRoot = join16(homedir4(), ".claude", "projects")) {
|
|
7156
|
+
return join16(projectsRoot, cwd.replace(/[^A-Za-z0-9]/g, "-"));
|
|
7157
|
+
}
|
|
7158
|
+
async function latestClaudeSessionId(cwd, projectsRoot) {
|
|
7159
|
+
const dir = claudeProjectDir(cwd, projectsRoot);
|
|
7160
|
+
let files;
|
|
7161
|
+
try {
|
|
7162
|
+
files = (await readdir6(dir)).filter((file) => file.endsWith(".jsonl"));
|
|
7163
|
+
} catch {
|
|
7164
|
+
return void 0;
|
|
7165
|
+
}
|
|
7166
|
+
let newest;
|
|
7167
|
+
for (const file of files) {
|
|
7168
|
+
try {
|
|
7169
|
+
const info = await stat4(join16(dir, file));
|
|
7170
|
+
if (!newest || info.mtimeMs > newest.mtime) {
|
|
7171
|
+
newest = { id: file.replace(/\.jsonl$/, ""), mtime: info.mtimeMs };
|
|
7172
|
+
}
|
|
7173
|
+
} catch {
|
|
7174
|
+
continue;
|
|
7175
|
+
}
|
|
7176
|
+
}
|
|
7177
|
+
return newest?.id;
|
|
7178
|
+
}
|
|
7179
|
+
|
|
7180
|
+
// src/agent/jsonl-adapter.ts
|
|
7181
|
+
import { createInterface as createInterface3 } from "readline";
|
|
6961
7182
|
var JsonlAgentAdapter = class {
|
|
6962
7183
|
id;
|
|
6963
7184
|
displayName;
|
|
7185
|
+
sideQuery;
|
|
6964
7186
|
options;
|
|
6965
7187
|
botIdentity;
|
|
6966
7188
|
constructor(options) {
|
|
6967
7189
|
this.options = options;
|
|
6968
7190
|
this.id = options.id;
|
|
6969
7191
|
this.displayName = options.displayName;
|
|
7192
|
+
if (options.sideQuery) this.sideQuery = options.sideQuery;
|
|
6970
7193
|
}
|
|
6971
7194
|
setBotIdentity(identity) {
|
|
6972
7195
|
this.botIdentity = identity;
|
|
@@ -7034,7 +7257,7 @@ var JsonlAgentAdapter = class {
|
|
|
7034
7257
|
yield { type: "error", message: `failed to spawn ${this.id}`, terminationReason: "failed" };
|
|
7035
7258
|
return;
|
|
7036
7259
|
}
|
|
7037
|
-
const rl =
|
|
7260
|
+
const rl = createInterface3({ input: child.stdout });
|
|
7038
7261
|
let terminal = false;
|
|
7039
7262
|
let sessionSeen;
|
|
7040
7263
|
let invalidJsonCount = 0;
|
|
@@ -7256,6 +7479,55 @@ function* translateEvent(raw) {
|
|
|
7256
7479
|
}
|
|
7257
7480
|
}
|
|
7258
7481
|
|
|
7482
|
+
// src/agent/claude/side-query.ts
|
|
7483
|
+
function buildClaudeSideQueryArgs(input) {
|
|
7484
|
+
return [
|
|
7485
|
+
"-p",
|
|
7486
|
+
"--output-format",
|
|
7487
|
+
"stream-json",
|
|
7488
|
+
"--verbose",
|
|
7489
|
+
"--resume",
|
|
7490
|
+
input.sessionId,
|
|
7491
|
+
"--fork-session",
|
|
7492
|
+
"--tools",
|
|
7493
|
+
""
|
|
7494
|
+
];
|
|
7495
|
+
}
|
|
7496
|
+
async function deleteClaudeSessionFile(sessionId, projectsRoot = join17(homedir5(), ".claude", "projects")) {
|
|
7497
|
+
let dirs;
|
|
7498
|
+
try {
|
|
7499
|
+
dirs = await readdir7(projectsRoot, { withFileTypes: true });
|
|
7500
|
+
} catch {
|
|
7501
|
+
return;
|
|
7502
|
+
}
|
|
7503
|
+
for (const dir of dirs) {
|
|
7504
|
+
if (!dir.isDirectory()) continue;
|
|
7505
|
+
const base = join17(projectsRoot, dir.name, sessionId);
|
|
7506
|
+
await rm14(`${base}.jsonl`, { force: true, maxRetries: 5, retryDelay: 25 }).catch(() => {
|
|
7507
|
+
});
|
|
7508
|
+
await rm14(base, { recursive: true, force: true, maxRetries: 5, retryDelay: 25 }).catch(() => {
|
|
7509
|
+
});
|
|
7510
|
+
}
|
|
7511
|
+
}
|
|
7512
|
+
async function runClaudeSideQuery(input) {
|
|
7513
|
+
const sessionId = input.sessionId ?? await latestClaudeSessionId(input.cwd, input.projectsRoot);
|
|
7514
|
+
if (!sessionId) return { text: "", error: "\u4F1A\u8BDD\u5C1A\u672A\u5EFA\u7ACB" };
|
|
7515
|
+
const result = await runJsonlSideQuery({
|
|
7516
|
+
agent: "claude",
|
|
7517
|
+
binary: input.binary,
|
|
7518
|
+
args: buildClaudeSideQueryArgs({ sessionId }),
|
|
7519
|
+
cwd: input.cwd,
|
|
7520
|
+
prompt: buildBtwPrompt(input.question),
|
|
7521
|
+
translate: (raw) => [...translateEvent(raw)],
|
|
7522
|
+
signal: input.signal
|
|
7523
|
+
});
|
|
7524
|
+
if (result.sessionId && result.sessionId !== sessionId) {
|
|
7525
|
+
markBtwSession("claude", result.sessionId);
|
|
7526
|
+
await deleteClaudeSessionFile(result.sessionId, input.projectsRoot);
|
|
7527
|
+
}
|
|
7528
|
+
return result.error ? { text: result.text, error: result.error } : { text: result.text };
|
|
7529
|
+
}
|
|
7530
|
+
|
|
7259
7531
|
// src/agent/claude/adapter.ts
|
|
7260
7532
|
var ClaudeAdapter = class {
|
|
7261
7533
|
id = "claude";
|
|
@@ -7268,6 +7540,15 @@ var ClaudeAdapter = class {
|
|
|
7268
7540
|
setBotIdentity(identity) {
|
|
7269
7541
|
this.botIdentity = identity;
|
|
7270
7542
|
}
|
|
7543
|
+
async sideQuery(opts) {
|
|
7544
|
+
return runClaudeSideQuery({
|
|
7545
|
+
binary: this.binary,
|
|
7546
|
+
cwd: opts.cwd,
|
|
7547
|
+
...opts.sessionId ? { sessionId: opts.sessionId } : {},
|
|
7548
|
+
question: opts.question,
|
|
7549
|
+
signal: opts.signal
|
|
7550
|
+
});
|
|
7551
|
+
}
|
|
7271
7552
|
async isAvailable() {
|
|
7272
7553
|
return (await this.checkAvailability()).ok;
|
|
7273
7554
|
}
|
|
@@ -7400,7 +7681,7 @@ async function* createEventStream(child, stderrChunks, getError) {
|
|
|
7400
7681
|
};
|
|
7401
7682
|
return;
|
|
7402
7683
|
}
|
|
7403
|
-
const rl =
|
|
7684
|
+
const rl = createInterface4({ input: child.stdout, crlfDelay: Infinity });
|
|
7404
7685
|
let sawStdout = false;
|
|
7405
7686
|
let silentExitTimer;
|
|
7406
7687
|
const closeSilentStdout = () => {
|
|
@@ -7461,8 +7742,8 @@ async function* createEventStream(child, stderrChunks, getError) {
|
|
|
7461
7742
|
}
|
|
7462
7743
|
}
|
|
7463
7744
|
function writeSystemPromptFile(content) {
|
|
7464
|
-
const dir = mkdtempSync(
|
|
7465
|
-
const path4 =
|
|
7745
|
+
const dir = mkdtempSync(join18(tmpdir3(), "xiaojiu-claude-"));
|
|
7746
|
+
const path4 = join18(dir, "append-system-prompt.md");
|
|
7466
7747
|
writeFileSync3(path4, content, "utf8");
|
|
7467
7748
|
return {
|
|
7468
7749
|
path: path4,
|
|
@@ -7479,8 +7760,8 @@ function isWindowsCommandNotFoundLine(line) {
|
|
|
7479
7760
|
}
|
|
7480
7761
|
|
|
7481
7762
|
// src/agent/codex/adapter.ts
|
|
7482
|
-
import { createInterface as
|
|
7483
|
-
import { join as
|
|
7763
|
+
import { createInterface as createInterface5 } from "readline";
|
|
7764
|
+
import { join as join20 } from "path";
|
|
7484
7765
|
|
|
7485
7766
|
// src/runtime/errors.ts
|
|
7486
7767
|
var RunRejected = class extends Error {
|
|
@@ -7547,6 +7828,11 @@ function buildCodexArgs(input) {
|
|
|
7547
7828
|
];
|
|
7548
7829
|
}
|
|
7549
7830
|
|
|
7831
|
+
// src/agent/codex/side-query.ts
|
|
7832
|
+
import { readdir as readdir8, rm as rm15 } from "fs/promises";
|
|
7833
|
+
import { homedir as homedir6 } from "os";
|
|
7834
|
+
import { join as join19 } from "path";
|
|
7835
|
+
|
|
7550
7836
|
// src/agent/codex/jsonl.ts
|
|
7551
7837
|
var CodexJsonlTranslator = class {
|
|
7552
7838
|
threadId;
|
|
@@ -7792,6 +8078,66 @@ function truncate(value, max) {
|
|
|
7792
8078
|
return value.length > max ? value.slice(0, max) : value;
|
|
7793
8079
|
}
|
|
7794
8080
|
|
|
8081
|
+
// src/agent/codex/side-query.ts
|
|
8082
|
+
function buildCodexSideQueryArgs(threadId) {
|
|
8083
|
+
return [
|
|
8084
|
+
"exec",
|
|
8085
|
+
"fork",
|
|
8086
|
+
threadId,
|
|
8087
|
+
"--json",
|
|
8088
|
+
"--sandbox",
|
|
8089
|
+
"read-only",
|
|
8090
|
+
"-c",
|
|
8091
|
+
'approval_policy="never"',
|
|
8092
|
+
"--skip-git-repo-check",
|
|
8093
|
+
"-"
|
|
8094
|
+
];
|
|
8095
|
+
}
|
|
8096
|
+
async function deleteCodexThreadRollout(threadId, codexHome = process.env.CODEX_HOME || join19(homedir6(), ".codex")) {
|
|
8097
|
+
const root = join19(codexHome, "sessions");
|
|
8098
|
+
const queue = [{ dir: root, depth: 0 }];
|
|
8099
|
+
while (queue.length > 0) {
|
|
8100
|
+
const current = queue.pop();
|
|
8101
|
+
if (!current) break;
|
|
8102
|
+
let entries;
|
|
8103
|
+
try {
|
|
8104
|
+
entries = await readdir8(current.dir, { withFileTypes: true });
|
|
8105
|
+
} catch {
|
|
8106
|
+
continue;
|
|
8107
|
+
}
|
|
8108
|
+
for (const entry of entries) {
|
|
8109
|
+
const path4 = join19(current.dir, entry.name);
|
|
8110
|
+
if (entry.isDirectory()) {
|
|
8111
|
+
if (current.depth < 4) queue.push({ dir: path4, depth: current.depth + 1 });
|
|
8112
|
+
continue;
|
|
8113
|
+
}
|
|
8114
|
+
if (entry.name.startsWith("rollout-") && entry.name.endsWith(`-${threadId}.jsonl`)) {
|
|
8115
|
+
await rm15(path4, { force: true, maxRetries: 5, retryDelay: 25 }).catch(() => {
|
|
8116
|
+
});
|
|
8117
|
+
}
|
|
8118
|
+
}
|
|
8119
|
+
}
|
|
8120
|
+
}
|
|
8121
|
+
async function runCodexSideQuery(input) {
|
|
8122
|
+
if (!input.threadId) return { text: "", error: "\u4F1A\u8BDD\u5C1A\u672A\u5EFA\u7ACB" };
|
|
8123
|
+
const translator = new CodexJsonlTranslator();
|
|
8124
|
+
const result = await runJsonlSideQuery({
|
|
8125
|
+
agent: "codex",
|
|
8126
|
+
binary: input.binary,
|
|
8127
|
+
args: buildCodexSideQueryArgs(input.threadId),
|
|
8128
|
+
cwd: input.cwd,
|
|
8129
|
+
...input.env ? { env: input.env } : {},
|
|
8130
|
+
prompt: buildBtwPrompt(input.question),
|
|
8131
|
+
translate: (raw) => translator.translate(raw),
|
|
8132
|
+
signal: input.signal
|
|
8133
|
+
});
|
|
8134
|
+
if (result.threadId && result.threadId !== input.threadId) {
|
|
8135
|
+
markBtwSession("codex", result.threadId);
|
|
8136
|
+
await deleteCodexThreadRollout(result.threadId, input.codexHome);
|
|
8137
|
+
}
|
|
8138
|
+
return result.error ? { text: result.text, error: result.error } : { text: result.text };
|
|
8139
|
+
}
|
|
8140
|
+
|
|
7795
8141
|
// src/agent/codex/adapter.ts
|
|
7796
8142
|
var CodexAdapter = class {
|
|
7797
8143
|
id = "codex";
|
|
@@ -7818,6 +8164,17 @@ var CodexAdapter = class {
|
|
|
7818
8164
|
setBotIdentity(identity) {
|
|
7819
8165
|
this.botIdentity = identity;
|
|
7820
8166
|
}
|
|
8167
|
+
async sideQuery(opts) {
|
|
8168
|
+
const codexHome = this.codexHome ?? (this.inheritCodexHome ? void 0 : join20(this.profileStateDir, "codex-home"));
|
|
8169
|
+
return runCodexSideQuery({
|
|
8170
|
+
binary: this.binary,
|
|
8171
|
+
cwd: opts.cwd,
|
|
8172
|
+
...opts.threadId ? { threadId: opts.threadId } : {},
|
|
8173
|
+
question: opts.question,
|
|
8174
|
+
signal: opts.signal,
|
|
8175
|
+
...codexHome ? { codexHome, env: { CODEX_HOME: codexHome } } : {}
|
|
8176
|
+
});
|
|
8177
|
+
}
|
|
7821
8178
|
async isAvailable() {
|
|
7822
8179
|
return (await this.checkAvailability()).ok;
|
|
7823
8180
|
}
|
|
@@ -7859,7 +8216,7 @@ var CodexAdapter = class {
|
|
|
7859
8216
|
if (this.codexHome) {
|
|
7860
8217
|
envOverrides.CODEX_HOME = this.codexHome;
|
|
7861
8218
|
} else if (!this.inheritCodexHome) {
|
|
7862
|
-
envOverrides.CODEX_HOME =
|
|
8219
|
+
envOverrides.CODEX_HOME = join20(this.profileStateDir, "codex-home");
|
|
7863
8220
|
}
|
|
7864
8221
|
const child = spawnProcess(this.binary, args, {
|
|
7865
8222
|
cwd: opts.cwd,
|
|
@@ -7968,7 +8325,7 @@ async function* createEventStream2(child, stderrChunks, getError, getStopReason)
|
|
|
7968
8325
|
};
|
|
7969
8326
|
return;
|
|
7970
8327
|
}
|
|
7971
|
-
const rl =
|
|
8328
|
+
const rl = createInterface5({ input: child.stdout, crlfDelay: Infinity });
|
|
7972
8329
|
let sawStdout = false;
|
|
7973
8330
|
let silentExitTimer;
|
|
7974
8331
|
const closeSilentStdout = () => {
|
|
@@ -8034,10 +8391,10 @@ function isWindowsCommandNotFoundLine2(line) {
|
|
|
8034
8391
|
}
|
|
8035
8392
|
|
|
8036
8393
|
// src/bot/channel.ts
|
|
8037
|
-
import { dirname as
|
|
8394
|
+
import { dirname as dirname20, join as join27 } from "path";
|
|
8038
8395
|
|
|
8039
8396
|
// src/channel/channel.ts
|
|
8040
|
-
import { join as
|
|
8397
|
+
import { join as join21 } from "path";
|
|
8041
8398
|
|
|
8042
8399
|
// src/channel/xiaojiu/dedupe-store.ts
|
|
8043
8400
|
import { readFile as readFile13 } from "fs/promises";
|
|
@@ -8746,7 +9103,7 @@ var XiaojiuChannel = class {
|
|
|
8746
9103
|
sendMessageApiVersion: options.sendMessageApiVersion
|
|
8747
9104
|
});
|
|
8748
9105
|
this.dedupe = new XiaojiuDedupeStore(
|
|
8749
|
-
options.dedupeFile ??
|
|
9106
|
+
options.dedupeFile ?? join21(process.cwd(), ".xiaojiu-webhook-events.json"),
|
|
8750
9107
|
options.dedupeTtlMs ? { ttlMs: options.dedupeTtlMs } : {}
|
|
8751
9108
|
);
|
|
8752
9109
|
this.throttleMs = Math.max(250, options.streamThrottleMs ?? 250);
|
|
@@ -9112,8 +9469,8 @@ function fitTextToBudget(text2, max) {
|
|
|
9112
9469
|
const available = max - STREAM_TRUNCATION_MARKER.length;
|
|
9113
9470
|
const headLength = Math.ceil(available / 2);
|
|
9114
9471
|
const tailLength = available - headLength;
|
|
9115
|
-
const
|
|
9116
|
-
return `${text2.slice(0, headLength)}${STREAM_TRUNCATION_MARKER}${
|
|
9472
|
+
const tail2 = tailLength > 0 ? text2.slice(-tailLength) : "";
|
|
9473
|
+
return `${text2.slice(0, headLength)}${STREAM_TRUNCATION_MARKER}${tail2}`;
|
|
9117
9474
|
}
|
|
9118
9475
|
function streamingMarkdownCard(markdown) {
|
|
9119
9476
|
return xiaojiuCard("\u5B9E\u65F6\u8F93\u51FA", [xiaojiuMarkdown(markdown)]);
|
|
@@ -9294,7 +9651,7 @@ function safeJsonStringify(value) {
|
|
|
9294
9651
|
|
|
9295
9652
|
// src/commands/index.ts
|
|
9296
9653
|
import { randomUUID } from "crypto";
|
|
9297
|
-
import { dirname as
|
|
9654
|
+
import { dirname as dirname19 } from "path";
|
|
9298
9655
|
|
|
9299
9656
|
// src/commands/mention-text.ts
|
|
9300
9657
|
function stripMatchedMentions(text2, mentions) {
|
|
@@ -9317,6 +9674,98 @@ function mentionNames(mentions) {
|
|
|
9317
9674
|
return names;
|
|
9318
9675
|
}
|
|
9319
9676
|
|
|
9677
|
+
// src/bot/side-query.ts
|
|
9678
|
+
var TIMEOUT_MS = 9e4;
|
|
9679
|
+
var COOLDOWN_MS = 1e4;
|
|
9680
|
+
var MAX_CONCURRENT = 2;
|
|
9681
|
+
var inFlight = /* @__PURE__ */ new Set();
|
|
9682
|
+
var lastAskedAt = /* @__PURE__ */ new Map();
|
|
9683
|
+
var active2 = 0;
|
|
9684
|
+
async function runSideQuery(input) {
|
|
9685
|
+
const now = input.now ?? Date.now;
|
|
9686
|
+
const run = input.agent.sideQuery;
|
|
9687
|
+
if (!run) {
|
|
9688
|
+
return {
|
|
9689
|
+
ok: false,
|
|
9690
|
+
code: "unsupported",
|
|
9691
|
+
message: `\u5F53\u524D agent\uFF08${input.agent.displayName}\uFF09\u6CA1\u6709\u65C1\u8DEF\u63D0\u95EE\u80FD\u529B\u3002`
|
|
9692
|
+
};
|
|
9693
|
+
}
|
|
9694
|
+
const live = input.progress?.active(input.scope);
|
|
9695
|
+
const stored = input.sessions.getRaw(input.scope);
|
|
9696
|
+
const catalogEntry = input.sessionCatalog && input.sessionCatalogIdentity ? input.sessionCatalog.activeFor(input.sessionCatalogIdentity) : void 0;
|
|
9697
|
+
const sessionId = live?.sessionId ?? stored?.sessionId;
|
|
9698
|
+
const threadId = live?.threadId ?? catalogEntry?.threadId;
|
|
9699
|
+
if (inFlight.has(input.key)) {
|
|
9700
|
+
return { ok: false, code: "busy", message: "\u4E0A\u4E00\u6761\u65C1\u8DEF\u63D0\u95EE\u8FD8\u5728\u56DE\u7B54\uFF0C\u7B49\u5B83\u7ED3\u675F\u518D\u95EE\u3002" };
|
|
9701
|
+
}
|
|
9702
|
+
const cooldownMs = input.cooldownMs ?? COOLDOWN_MS;
|
|
9703
|
+
const startedAt = now();
|
|
9704
|
+
const last = lastAskedAt.get(input.key);
|
|
9705
|
+
if (last !== void 0 && startedAt - last < cooldownMs) {
|
|
9706
|
+
const waitSeconds = Math.ceil((cooldownMs - (startedAt - last)) / 1e3);
|
|
9707
|
+
return { ok: false, code: "cooldown", message: `\u521A\u95EE\u8FC7\uFF0C${waitSeconds}s \u540E\u518D\u8BD5\u3002` };
|
|
9708
|
+
}
|
|
9709
|
+
if (active2 >= MAX_CONCURRENT) {
|
|
9710
|
+
return { ok: false, code: "pool-full", message: "\u540C\u65F6\u8FDB\u884C\u7684\u65C1\u8DEF\u63D0\u95EE\u5DF2\u8FBE\u4E0A\u9650\uFF0C\u7A0D\u540E\u518D\u8BD5\u3002" };
|
|
9711
|
+
}
|
|
9712
|
+
const cwd = live?.cwd ?? input.cwd;
|
|
9713
|
+
if (!cwd) {
|
|
9714
|
+
return { ok: false, code: "failed", message: "\u627E\u4E0D\u5230\u8FD9\u4E2A\u4F1A\u8BDD\u7684\u5DE5\u4F5C\u76EE\u5F55\uFF0C\u65E0\u6CD5\u65C1\u8DEF\u63D0\u95EE\u3002" };
|
|
9715
|
+
}
|
|
9716
|
+
inFlight.add(input.key);
|
|
9717
|
+
lastAskedAt.set(input.key, startedAt);
|
|
9718
|
+
active2 += 1;
|
|
9719
|
+
const controller = new AbortController();
|
|
9720
|
+
const timer = setTimeout(() => controller.abort(), input.timeoutMs ?? TIMEOUT_MS);
|
|
9721
|
+
log.info("btw", "start", {
|
|
9722
|
+
scope: input.scope,
|
|
9723
|
+
agent: input.agent.id,
|
|
9724
|
+
hasSession: Boolean(sessionId),
|
|
9725
|
+
hasThread: Boolean(threadId),
|
|
9726
|
+
questionChars: input.question.length
|
|
9727
|
+
});
|
|
9728
|
+
try {
|
|
9729
|
+
const result = await run({
|
|
9730
|
+
question: input.question,
|
|
9731
|
+
cwd,
|
|
9732
|
+
...sessionId ? { sessionId } : {},
|
|
9733
|
+
...threadId ? { threadId } : {},
|
|
9734
|
+
signal: controller.signal
|
|
9735
|
+
});
|
|
9736
|
+
const durationMs = now() - startedAt;
|
|
9737
|
+
const text2 = result.text.trim();
|
|
9738
|
+
if (text2) {
|
|
9739
|
+
log.info("btw", "done", {
|
|
9740
|
+
scope: input.scope,
|
|
9741
|
+
agent: input.agent.id,
|
|
9742
|
+
durationMs,
|
|
9743
|
+
chars: text2.length,
|
|
9744
|
+
partial: Boolean(result.error)
|
|
9745
|
+
});
|
|
9746
|
+
reportMetric("btw_ms", durationMs, { agent: input.agent.id });
|
|
9747
|
+
return result.error ? { ok: false, code: "failed", message: result.error, partial: text2 } : { ok: true, text: text2 };
|
|
9748
|
+
}
|
|
9749
|
+
const aborted = controller.signal.aborted;
|
|
9750
|
+
const message = result.error === "aborted" || aborted ? "\u65C1\u8DEF\u63D0\u95EE\u8D85\u65F6\uFF0C\u5DF2\u53D6\u6D88\u3002" : result.error ?? "\u6CA1\u6709\u62FF\u5230\u7B54\u6848\u3002";
|
|
9751
|
+
log.warn("btw", "fail", {
|
|
9752
|
+
scope: input.scope,
|
|
9753
|
+
agent: input.agent.id,
|
|
9754
|
+
durationMs,
|
|
9755
|
+
code: aborted ? "timeout" : "failed",
|
|
9756
|
+
err: result.error
|
|
9757
|
+
});
|
|
9758
|
+
return { ok: false, code: aborted ? "timeout" : "failed", message };
|
|
9759
|
+
} catch (err) {
|
|
9760
|
+
log.fail("btw", err, { scope: input.scope, agent: input.agent.id });
|
|
9761
|
+
return { ok: false, code: "failed", message: err instanceof Error ? err.message : String(err) };
|
|
9762
|
+
} finally {
|
|
9763
|
+
clearTimeout(timer);
|
|
9764
|
+
inFlight.delete(input.key);
|
|
9765
|
+
active2 -= 1;
|
|
9766
|
+
}
|
|
9767
|
+
}
|
|
9768
|
+
|
|
9320
9769
|
// src/card/config-card.ts
|
|
9321
9770
|
function accessMarkdown(opts, expanded) {
|
|
9322
9771
|
const teamMode = opts.mode === "team";
|
|
@@ -9827,6 +10276,7 @@ function helpCard(agentName = "Agent") {
|
|
|
9827
10276
|
"- `/ws list|save <name>|use <name>|remove <name>` \u2014 \u5DE5\u4F5C\u76EE\u5F55",
|
|
9828
10277
|
"- `/config` \u2014 \u8C03\u6574\u504F\u597D\u548C\u8BBF\u95EE\u63A7\u5236\uFF1B`/config set api <v1|v2>` \u76F4\u63A5\u5207\u6362\u53D1\u6D88\u606F\u63A5\u53E3\u7248\u672C",
|
|
9829
10278
|
"- `/status` \u2014 \u5F53\u524D\u72B6\u6001",
|
|
10279
|
+
"- `/btw [\u95EE\u9898]` \u2014 \u5411\u6B63\u5728\u8DD1\u7684\u4EFB\u52A1\u65C1\u8DEF\u63D0\u95EE\uFF08\u8BFB\u4F1A\u8BDD\u4E0A\u4E0B\u6587\u3001\u4E0D\u6267\u884C\u5DE5\u5177\u3001\u4E0D\u5199\u5386\u53F2\uFF09",
|
|
9830
10280
|
"- `/myid` \u2014 \u4EE5\u5361\u7247\u663E\u793A\u5F53\u524D\u7FA4\u7EC4\u3001\u9891\u9053\u548C\u8BDD\u9898 id",
|
|
9831
10281
|
"- `/agent <claude|codex|pi|opencode|omp>` \u2014 \u7A7A\u95F2\u65F6\u5207\u6362\u672C profile \u7684 Coding Agent",
|
|
9832
10282
|
"- `/stop` \u2014 \u7ED3\u675F\u5F53\u524D\u6B63\u5728\u8DD1\u7684\u4EFB\u52A1\uFF08\u4E5F\u53EF\u70B9\u5361\u7247\u5E95\u90E8 \u23F9 \u7EC8\u6B62 \u6309\u94AE\uFF09",
|
|
@@ -9961,7 +10411,7 @@ function deny(reason) {
|
|
|
9961
10411
|
}
|
|
9962
10412
|
|
|
9963
10413
|
// src/config/config-ops.ts
|
|
9964
|
-
import { dirname as
|
|
10414
|
+
import { dirname as dirname18 } from "path";
|
|
9965
10415
|
async function saveAccessConfig(state, mutate) {
|
|
9966
10416
|
try {
|
|
9967
10417
|
return await withConfigFileLock(state.configPath, async () => {
|
|
@@ -10505,10 +10955,9 @@ function finalizeIfRunning(state) {
|
|
|
10505
10955
|
|
|
10506
10956
|
// src/session/history.ts
|
|
10507
10957
|
import { createReadStream } from "fs";
|
|
10508
|
-
import { readdir as
|
|
10509
|
-
import {
|
|
10510
|
-
import {
|
|
10511
|
-
import { createInterface as createInterface5 } from "readline";
|
|
10958
|
+
import { readdir as readdir9, stat as stat5 } from "fs/promises";
|
|
10959
|
+
import { join as join22 } from "path";
|
|
10960
|
+
import { createInterface as createInterface6 } from "readline";
|
|
10512
10961
|
|
|
10513
10962
|
// src/session/preview.ts
|
|
10514
10963
|
var DEFAULT_PREVIEW_MAX_CHARS = 80;
|
|
@@ -10542,27 +10991,23 @@ function truncatePreview(input, maxChars) {
|
|
|
10542
10991
|
}
|
|
10543
10992
|
|
|
10544
10993
|
// src/session/history.ts
|
|
10545
|
-
function encodeCwd(cwd) {
|
|
10546
|
-
return cwd.replace(/[^A-Za-z0-9]/g, "-");
|
|
10547
|
-
}
|
|
10548
|
-
function claudeProjectDir(cwd) {
|
|
10549
|
-
return join18(homedir4(), ".claude", "projects", encodeCwd(cwd));
|
|
10550
|
-
}
|
|
10551
10994
|
async function listRecentSessions(cwd, limit = 5) {
|
|
10552
10995
|
const dir = claudeProjectDir(cwd);
|
|
10553
10996
|
let files;
|
|
10554
10997
|
try {
|
|
10555
|
-
files = await
|
|
10998
|
+
files = await readdir9(dir);
|
|
10556
10999
|
} catch (err) {
|
|
10557
11000
|
if (err.code === "ENOENT") return [];
|
|
10558
11001
|
throw err;
|
|
10559
11002
|
}
|
|
10560
|
-
const jsonls = files.filter(
|
|
11003
|
+
const jsonls = files.filter(
|
|
11004
|
+
(f) => f.endsWith(".jsonl") && !isBtwSession("claude", f.replace(/\.jsonl$/, ""))
|
|
11005
|
+
);
|
|
10561
11006
|
const withStats = await Promise.all(
|
|
10562
11007
|
jsonls.map(async (f) => {
|
|
10563
|
-
const path4 =
|
|
11008
|
+
const path4 = join22(dir, f);
|
|
10564
11009
|
try {
|
|
10565
|
-
const st = await
|
|
11010
|
+
const st = await stat5(path4);
|
|
10566
11011
|
return { file: f, path: path4, mtime: st.mtimeMs };
|
|
10567
11012
|
} catch {
|
|
10568
11013
|
return null;
|
|
@@ -10580,7 +11025,7 @@ async function listRecentSessions(cwd, limit = 5) {
|
|
|
10580
11025
|
}
|
|
10581
11026
|
async function summarize(path4) {
|
|
10582
11027
|
const stream2 = createReadStream(path4, { encoding: "utf8" });
|
|
10583
|
-
const rl =
|
|
11028
|
+
const rl = createInterface6({ input: stream2 });
|
|
10584
11029
|
let preview = "";
|
|
10585
11030
|
let lineCount = 0;
|
|
10586
11031
|
try {
|
|
@@ -10630,8 +11075,8 @@ function formatRelTime(mtime) {
|
|
|
10630
11075
|
}
|
|
10631
11076
|
|
|
10632
11077
|
// src/session/codex-history.ts
|
|
10633
|
-
import { createInterface as
|
|
10634
|
-
import { join as
|
|
11078
|
+
import { createInterface as createInterface7 } from "readline";
|
|
11079
|
+
import { join as join23 } from "path";
|
|
10635
11080
|
var CodexHistoryError = class extends Error {
|
|
10636
11081
|
code;
|
|
10637
11082
|
constructor(code, message, options) {
|
|
@@ -10654,7 +11099,7 @@ async function listCodexThreadHistory(options) {
|
|
|
10654
11099
|
const stderrChunks = [];
|
|
10655
11100
|
let settled = false;
|
|
10656
11101
|
const result = await new Promise((resolve5, reject4) => {
|
|
10657
|
-
const rl =
|
|
11102
|
+
const rl = createInterface7({ input: child.stdout, crlfDelay: Infinity });
|
|
10658
11103
|
let timer;
|
|
10659
11104
|
const fail = (err) => {
|
|
10660
11105
|
if (settled) return;
|
|
@@ -10738,15 +11183,15 @@ ${JSON.stringify(listRequest(options))}
|
|
|
10738
11183
|
fail(err);
|
|
10739
11184
|
}
|
|
10740
11185
|
});
|
|
10741
|
-
await
|
|
10742
|
-
return result;
|
|
11186
|
+
await waitForChildExit2(child, 250);
|
|
11187
|
+
return result.filter((entry) => !isBtwSession("codex", entry.threadId));
|
|
10743
11188
|
}
|
|
10744
11189
|
function spawnCodexAppServer(options) {
|
|
10745
11190
|
const envOverrides = {};
|
|
10746
11191
|
if (options.codexHome) {
|
|
10747
11192
|
envOverrides.CODEX_HOME = options.codexHome;
|
|
10748
11193
|
} else if (options.inheritCodexHome === false) {
|
|
10749
|
-
envOverrides.CODEX_HOME =
|
|
11194
|
+
envOverrides.CODEX_HOME = join23(options.profileStateDir, "codex-home");
|
|
10750
11195
|
}
|
|
10751
11196
|
return spawnProcess(options.binary, ["app-server", "--listen", "stdio://"], {
|
|
10752
11197
|
env: mergeProcessEnv(process.env, envOverrides),
|
|
@@ -10814,7 +11259,7 @@ function normalizeThread(input) {
|
|
|
10814
11259
|
...stringValue2(raw.name) ? { name: stringValue2(raw.name) } : {}
|
|
10815
11260
|
};
|
|
10816
11261
|
}
|
|
10817
|
-
async function
|
|
11262
|
+
async function waitForChildExit2(child, timeoutMs) {
|
|
10818
11263
|
if (child.exitCode !== null || child.signalCode !== null) return;
|
|
10819
11264
|
await new Promise((resolve5) => {
|
|
10820
11265
|
const timer = setTimeout(() => {
|
|
@@ -11022,11 +11467,11 @@ async function fetchKnownChats(channel) {
|
|
|
11022
11467
|
}
|
|
11023
11468
|
|
|
11024
11469
|
// src/platform/home-path.ts
|
|
11025
|
-
import { homedir as
|
|
11470
|
+
import { homedir as homedir7 } from "os";
|
|
11026
11471
|
import { isAbsolute as isAbsolute2 } from "path";
|
|
11027
11472
|
function expandTilde(p3) {
|
|
11028
|
-
if (p3 === "~") return
|
|
11029
|
-
if (p3.startsWith("~/")) return `${
|
|
11473
|
+
if (p3 === "~") return homedir7();
|
|
11474
|
+
if (p3.startsWith("~/")) return `${homedir7()}${p3.slice(1)}`;
|
|
11030
11475
|
return p3;
|
|
11031
11476
|
}
|
|
11032
11477
|
function isAbsoluteOrTilde(p3) {
|
|
@@ -11049,6 +11494,7 @@ var handlers = {
|
|
|
11049
11494
|
"/ws": handleWs,
|
|
11050
11495
|
"/resume": handleResume,
|
|
11051
11496
|
"/status": handleStatus,
|
|
11497
|
+
"/btw": handleBtw,
|
|
11052
11498
|
"/myid": handleMyId,
|
|
11053
11499
|
"/help": handleHelp,
|
|
11054
11500
|
"/config": handleConfig,
|
|
@@ -11077,6 +11523,13 @@ var ADMIN_COMMANDS = /* @__PURE__ */ new Set([
|
|
|
11077
11523
|
function isAdminCommand(cmd) {
|
|
11078
11524
|
return ADMIN_COMMANDS.has(cmd.startsWith("/") ? cmd : `/${cmd}`);
|
|
11079
11525
|
}
|
|
11526
|
+
var READ_ONLY_COMMANDS = /* @__PURE__ */ new Set(["/btw", "/status", "/help", "/myid"]);
|
|
11527
|
+
function isReadOnlyCommandInvocation(content, mentions) {
|
|
11528
|
+
const trimmed = stripMatchedMentions(content, mentions).trim();
|
|
11529
|
+
if (!trimmed.startsWith("/")) return false;
|
|
11530
|
+
const cmd = trimmed.split(/\s+/)[0] ?? "";
|
|
11531
|
+
return READ_ONLY_COMMANDS.has(cmd);
|
|
11532
|
+
}
|
|
11080
11533
|
async function tryHandleCommand(ctx) {
|
|
11081
11534
|
const trimmed = stripMatchedMentions(ctx.msg.content, ctx.msg.mentions).trim();
|
|
11082
11535
|
if (!trimmed.startsWith("/")) return false;
|
|
@@ -11560,6 +12013,75 @@ async function handleStatus(_args, ctx) {
|
|
|
11560
12013
|
});
|
|
11561
12014
|
await ctx.channel.send(commandSendChatId(ctx), { card }, commandReplyOptions(ctx));
|
|
11562
12015
|
}
|
|
12016
|
+
async function handleBtw(args, ctx) {
|
|
12017
|
+
if (!ctx.activeRuns.get(ctx.scope)) {
|
|
12018
|
+
await reply(ctx, "\u5F53\u524D\u6CA1\u6709\u8FD0\u884C\u4E2D\u7684\u4EFB\u52A1\u3002");
|
|
12019
|
+
return;
|
|
12020
|
+
}
|
|
12021
|
+
const attempt = await runSideQuery({
|
|
12022
|
+
agent: ctx.agent,
|
|
12023
|
+
...ctx.runProgress ? { progress: ctx.runProgress } : {},
|
|
12024
|
+
sessions: ctx.sessions,
|
|
12025
|
+
...ctx.sessionCatalog ? { sessionCatalog: ctx.sessionCatalog } : {},
|
|
12026
|
+
...ctx.sessionCatalogIdentity ? { sessionCatalogIdentity: ctx.sessionCatalogIdentity } : {},
|
|
12027
|
+
scope: ctx.scope,
|
|
12028
|
+
key: `${ctx.controls.profile}:${ctx.scope}`,
|
|
12029
|
+
...effectiveWorkspaceCwd(ctx) ? { cwd: effectiveWorkspaceCwd(ctx) } : {},
|
|
12030
|
+
question: args.trim()
|
|
12031
|
+
});
|
|
12032
|
+
if (attempt.ok) {
|
|
12033
|
+
await reply(
|
|
12034
|
+
ctx,
|
|
12035
|
+
`\u{1F6F0}\uFE0F **\u65C1\u8DEF\u63D0\u95EE**\uFF08\u4E0D\u8FDB\u5165\u4F1A\u8BDD\u5386\u53F2\uFF09
|
|
12036
|
+
|
|
12037
|
+
${attempt.text}
|
|
12038
|
+
|
|
12039
|
+
_\u2014 /btw \u4FA7\u67E5\u8BE2\uFF0C\u672A\u5199\u5165\u4F1A\u8BDD_`
|
|
12040
|
+
);
|
|
12041
|
+
return;
|
|
12042
|
+
}
|
|
12043
|
+
const lines = [`\u274C ${attempt.message}`];
|
|
12044
|
+
if (attempt.partial) lines.push("", attempt.partial);
|
|
12045
|
+
const liveLine = describeLiveRunLine(ctx);
|
|
12046
|
+
if (liveLine) lines.push("", liveLine);
|
|
12047
|
+
await reply(ctx, lines.join("\n"));
|
|
12048
|
+
}
|
|
12049
|
+
function describeLiveRunLine(ctx) {
|
|
12050
|
+
const live = ctx.runProgress?.active(ctx.scope);
|
|
12051
|
+
if (!live) return "";
|
|
12052
|
+
const now = Date.now();
|
|
12053
|
+
return `_\u4E3B\u4EFB\u52A1\u4ECD\u5728\u8DD1\uFF1A\u5DF2 ${formatDuration(now - live.startedAt)}\uFF0C\u6700\u540E\u6D3B\u52A8 ${formatAgo(now - live.lastEventAt)}\uFF0C${describeCurrentAction(live, now)}_`;
|
|
12054
|
+
}
|
|
12055
|
+
function describeCurrentAction(live, now) {
|
|
12056
|
+
if (live.toolsInFlight.length > 0) {
|
|
12057
|
+
return live.toolsInFlight.map((tool) => `\u5DE5\u5177 \`${escapeCode2(tool.name)}\` ${formatDuration(now - tool.startedAt)}`).join("\u3001");
|
|
12058
|
+
}
|
|
12059
|
+
switch (live.phase) {
|
|
12060
|
+
case "starting":
|
|
12061
|
+
return "\u7B49\u5F85 agent \u9996\u6761\u4E8B\u4EF6";
|
|
12062
|
+
case "thinking":
|
|
12063
|
+
return "\u601D\u8003\u4E2D";
|
|
12064
|
+
case "text":
|
|
12065
|
+
return "\u5199\u56DE\u590D\u4E2D";
|
|
12066
|
+
case "tool":
|
|
12067
|
+
return live.lastTool ? `\u4E0A\u4E00\u4E2A\u5DE5\u5177 \`${escapeCode2(live.lastTool.name)}\` ${live.lastTool.ok ? "\u5DF2\u5B8C\u6210" : "\u5931\u8D25"}` : "\u7B49\u5F85\u4E0B\u4E00\u6B65";
|
|
12068
|
+
}
|
|
12069
|
+
}
|
|
12070
|
+
function escapeCode2(text2) {
|
|
12071
|
+
return text2.replace(/`/g, "'");
|
|
12072
|
+
}
|
|
12073
|
+
function formatDuration(ms) {
|
|
12074
|
+
const totalSeconds = Math.max(0, Math.round(ms / 1e3));
|
|
12075
|
+
if (totalSeconds < 60) return `${totalSeconds}s`;
|
|
12076
|
+
const minutes = Math.floor(totalSeconds / 60);
|
|
12077
|
+
if (minutes < 60) {
|
|
12078
|
+
const seconds = totalSeconds % 60;
|
|
12079
|
+
return seconds ? `${minutes}m${seconds}s` : `${minutes}m`;
|
|
12080
|
+
}
|
|
12081
|
+
const hours = Math.floor(minutes / 60);
|
|
12082
|
+
const rest = minutes % 60;
|
|
12083
|
+
return rest ? `${hours}h${rest}m` : `${hours}h`;
|
|
12084
|
+
}
|
|
11563
12085
|
async function handleMyId(_args, ctx) {
|
|
11564
12086
|
const card = myIdCard({
|
|
11565
12087
|
groupId: ctx.msg.threadId ?? ctx.msg.chatId,
|
|
@@ -12598,7 +13120,7 @@ async function submitConfig(ctx) {
|
|
|
12598
13120
|
}
|
|
12599
13121
|
function commandProfilePaths(ctx) {
|
|
12600
13122
|
return resolveAppPaths({
|
|
12601
|
-
rootDir:
|
|
13123
|
+
rootDir: dirname19(ctx.controls.configPath),
|
|
12602
13124
|
profile: ctx.controls.profile
|
|
12603
13125
|
});
|
|
12604
13126
|
}
|
|
@@ -12722,6 +13244,7 @@ async function handleCardAction(deps) {
|
|
|
12722
13244
|
agent: deps.agent,
|
|
12723
13245
|
processPool: deps.processPool,
|
|
12724
13246
|
runExecutor: deps.runExecutor,
|
|
13247
|
+
runProgress: deps.runProgress,
|
|
12725
13248
|
controls: deps.controls,
|
|
12726
13249
|
formValue,
|
|
12727
13250
|
fromCardAction: true
|
|
@@ -12793,14 +13316,14 @@ function forwardToAgent(deps, payload, formValue, scope, threadId, mode) {
|
|
|
12793
13316
|
}
|
|
12794
13317
|
function verifyBridgeToken(deps, payload, scope, action) {
|
|
12795
13318
|
const token = typeof payload.bridge_token === "string" ? payload.bridge_token : "";
|
|
12796
|
-
const
|
|
12797
|
-
if (!deps.callbackAuth || !token || !
|
|
13319
|
+
const active3 = deps.activeRuns.get(scope);
|
|
13320
|
+
if (!deps.callbackAuth || !token || !active3) {
|
|
12798
13321
|
log.info("card-action", "skip-callback-auth-missing", { scope, action });
|
|
12799
13322
|
log.warn("callback", "denied", { scope, action, reason: "missing-token-or-run" });
|
|
12800
13323
|
return false;
|
|
12801
13324
|
}
|
|
12802
13325
|
const result = deps.callbackAuth.verify(token, {
|
|
12803
|
-
runId:
|
|
13326
|
+
runId: active3.run.runId,
|
|
12804
13327
|
scope,
|
|
12805
13328
|
chatId: deps.evt.chatId,
|
|
12806
13329
|
operatorOpenId: deps.evt.operator.openId,
|
|
@@ -12909,8 +13432,8 @@ var CallbackAuth = class {
|
|
|
12909
13432
|
return { ok: true, payload };
|
|
12910
13433
|
}
|
|
12911
13434
|
signingKey() {
|
|
12912
|
-
const
|
|
12913
|
-
const key =
|
|
13435
|
+
const active3 = this.keys.filter((key2) => !key2.retired);
|
|
13436
|
+
const key = active3.at(-1);
|
|
12914
13437
|
if (!key) throw new Error("no active callback signing key");
|
|
12915
13438
|
return key;
|
|
12916
13439
|
}
|
|
@@ -13040,8 +13563,8 @@ function footerLine(status) {
|
|
|
13040
13563
|
// src/media/cache.ts
|
|
13041
13564
|
import { createHash as createHash4 } from "crypto";
|
|
13042
13565
|
import { createReadStream as createReadStream2 } from "fs";
|
|
13043
|
-
import { mkdir as mkdir16, open as open3, readdir as
|
|
13044
|
-
import { join as
|
|
13566
|
+
import { mkdir as mkdir16, open as open3, readdir as readdir10, rename as rename3, rm as rm16, stat as stat6, writeFile as writeFile9 } from "fs/promises";
|
|
13567
|
+
import { join as join24 } from "path";
|
|
13045
13568
|
|
|
13046
13569
|
// src/media/attachment.ts
|
|
13047
13570
|
var DEFAULT_POLICY = {
|
|
@@ -13177,7 +13700,7 @@ var MediaCache = class {
|
|
|
13177
13700
|
return null;
|
|
13178
13701
|
}
|
|
13179
13702
|
const kind = r.type;
|
|
13180
|
-
const tmpPath =
|
|
13703
|
+
const tmpPath = join24(
|
|
13181
13704
|
this.rootDir,
|
|
13182
13705
|
`.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`
|
|
13183
13706
|
);
|
|
@@ -13200,14 +13723,14 @@ var MediaCache = class {
|
|
|
13200
13723
|
await writeFile9(tmpPath, new Uint8Array(await response.arrayBuffer()));
|
|
13201
13724
|
contentType = response.headers.get("content-type")?.split(";")[0]?.trim();
|
|
13202
13725
|
}
|
|
13203
|
-
const tmpStat = await
|
|
13726
|
+
const tmpStat = await stat6(tmpPath);
|
|
13204
13727
|
const hash = await hashFile(tmpPath);
|
|
13205
13728
|
const mime = await sniffImageMime(tmpPath) ?? contentType ?? defaultMime(kind);
|
|
13206
13729
|
const ext = safeExtensionForMime(mime);
|
|
13207
|
-
const absPath =
|
|
13730
|
+
const absPath = join24(this.rootDir, `${hash}.${ext}`);
|
|
13208
13731
|
try {
|
|
13209
|
-
await
|
|
13210
|
-
await
|
|
13732
|
+
await stat6(absPath);
|
|
13733
|
+
await rm16(tmpPath, { force: true });
|
|
13211
13734
|
log.info("media", "cache-hit", { path: absPath });
|
|
13212
13735
|
} catch {
|
|
13213
13736
|
await rename3(tmpPath, absPath);
|
|
@@ -13263,9 +13786,9 @@ async function sniffImageMime(path4) {
|
|
|
13263
13786
|
}
|
|
13264
13787
|
async function listFiles(root) {
|
|
13265
13788
|
const out = [];
|
|
13266
|
-
const entries = await
|
|
13789
|
+
const entries = await readdir10(root, { withFileTypes: true }).catch(() => []);
|
|
13267
13790
|
for (const entry of entries) {
|
|
13268
|
-
const full =
|
|
13791
|
+
const full = join24(root, entry.name);
|
|
13269
13792
|
if (entry.isDirectory()) {
|
|
13270
13793
|
out.push(...await listFiles(full));
|
|
13271
13794
|
} else if (entry.isFile()) {
|
|
@@ -13285,20 +13808,20 @@ async function enforceCacheMaxBytes(root, maxBytes, protectedPaths) {
|
|
|
13285
13808
|
if (!Number.isFinite(maxBytes) || maxBytes <= 0) return;
|
|
13286
13809
|
const files = await Promise.all(
|
|
13287
13810
|
(await listFiles(root)).map(async (path4) => {
|
|
13288
|
-
const fileStat = await
|
|
13811
|
+
const fileStat = await stat6(path4);
|
|
13289
13812
|
return { path: path4, size: fileStat.size, mtimeMs: fileStat.mtimeMs };
|
|
13290
13813
|
})
|
|
13291
13814
|
);
|
|
13292
13815
|
let total = files.reduce((sum, file) => sum + file.size, 0);
|
|
13293
13816
|
for (const file of files.filter((item) => !protectedPaths.has(item.path)).sort((a, b) => a.mtimeMs - b.mtimeMs)) {
|
|
13294
13817
|
if (total <= maxBytes) break;
|
|
13295
|
-
await
|
|
13818
|
+
await rm16(file.path, { force: true });
|
|
13296
13819
|
total -= file.size;
|
|
13297
13820
|
}
|
|
13298
13821
|
}
|
|
13299
13822
|
async function removeRejectedResolvedFiles(attachments) {
|
|
13300
13823
|
await Promise.all(
|
|
13301
|
-
attachments.filter((attachment) => attachment.decision !== "accepted").map((attachment) =>
|
|
13824
|
+
attachments.filter((attachment) => attachment.decision !== "accepted").map((attachment) => rm16(attachment.absPath, { force: true }))
|
|
13302
13825
|
);
|
|
13303
13826
|
}
|
|
13304
13827
|
|
|
@@ -13540,6 +14063,7 @@ var RunExecutor = class {
|
|
|
13540
14063
|
createRunId;
|
|
13541
14064
|
now;
|
|
13542
14065
|
postDoneExitGraceMs;
|
|
14066
|
+
progress;
|
|
13543
14067
|
constructor(deps) {
|
|
13544
14068
|
this.agent = deps.agent;
|
|
13545
14069
|
this.pool = deps.pool;
|
|
@@ -13547,6 +14071,7 @@ var RunExecutor = class {
|
|
|
13547
14071
|
this.createRunId = deps.createRunId ?? randomUUID2;
|
|
13548
14072
|
this.now = deps.now ?? Date.now;
|
|
13549
14073
|
this.postDoneExitGraceMs = deps.postDoneExitGraceMs ?? DEFAULT_POST_DONE_EXIT_GRACE_MS;
|
|
14074
|
+
this.progress = deps.progress;
|
|
13550
14075
|
}
|
|
13551
14076
|
async submit(input) {
|
|
13552
14077
|
const submittedAt = this.now();
|
|
@@ -13649,10 +14174,20 @@ var RunExecutor = class {
|
|
|
13649
14174
|
);
|
|
13650
14175
|
}
|
|
13651
14176
|
let cleaned = false;
|
|
14177
|
+
this.progress?.begin({
|
|
14178
|
+
scope: input.scopeId,
|
|
14179
|
+
runId,
|
|
14180
|
+
startedAt,
|
|
14181
|
+
sessionId: input.sessionId,
|
|
14182
|
+
threadId: input.threadId,
|
|
14183
|
+
model: input.model,
|
|
14184
|
+
cwd: input.policy.cwdRealpath
|
|
14185
|
+
});
|
|
13652
14186
|
const cleanup = async (waitForExit2) => {
|
|
13653
14187
|
if (cleaned) return;
|
|
13654
14188
|
cleaned = true;
|
|
13655
14189
|
this.activeRuns.unregister(input.scopeId, run);
|
|
14190
|
+
this.progress?.clear(input.scopeId);
|
|
13656
14191
|
release();
|
|
13657
14192
|
if (waitForExit2) {
|
|
13658
14193
|
const exited = await run.waitForExit(this.postDoneExitGraceMs);
|
|
@@ -13674,7 +14209,9 @@ var RunExecutor = class {
|
|
|
13674
14209
|
dimensions,
|
|
13675
14210
|
startedAt,
|
|
13676
14211
|
now: this.now,
|
|
13677
|
-
onEvent: input.onEvent
|
|
14212
|
+
onEvent: input.onEvent,
|
|
14213
|
+
progress: this.progress,
|
|
14214
|
+
scope: input.scopeId
|
|
13678
14215
|
}), async () => {
|
|
13679
14216
|
await cleanup(!handle2.interrupted);
|
|
13680
14217
|
});
|
|
@@ -13698,6 +14235,7 @@ function observeRunEvents(events, opts) {
|
|
|
13698
14235
|
async *[Symbol.asyncIterator]() {
|
|
13699
14236
|
for await (const event of events) {
|
|
13700
14237
|
await opts.onEvent?.(event);
|
|
14238
|
+
opts.progress?.record(opts.scope, event);
|
|
13701
14239
|
if (event.type === "done") {
|
|
13702
14240
|
log.info("run", "completed", {
|
|
13703
14241
|
...opts.dimensions,
|
|
@@ -13794,7 +14332,7 @@ function isTerminalEvent(event) {
|
|
|
13794
14332
|
// src/session/context-store.ts
|
|
13795
14333
|
import { createHash as createHash5 } from "crypto";
|
|
13796
14334
|
import { readFile as readFile15 } from "fs/promises";
|
|
13797
|
-
import { join as
|
|
14335
|
+
import { join as join25 } from "path";
|
|
13798
14336
|
var MAX_MESSAGES = 25;
|
|
13799
14337
|
var MAX_MESSAGE_CHARS = 8e3;
|
|
13800
14338
|
var MAX_HISTORY_CHARS = 64e3;
|
|
@@ -13859,7 +14397,7 @@ var ConversationContextStore = class {
|
|
|
13859
14397
|
identity.cwdRealpath,
|
|
13860
14398
|
identity.policyFingerprint
|
|
13861
14399
|
])).digest("hex");
|
|
13862
|
-
return
|
|
14400
|
+
return join25(this.profileDir, "context", `${hash}.json`);
|
|
13863
14401
|
}
|
|
13864
14402
|
async load(identity) {
|
|
13865
14403
|
const path4 = this.path(identity);
|
|
@@ -13894,8 +14432,8 @@ var ConversationContextStore = class {
|
|
|
13894
14432
|
|
|
13895
14433
|
// src/memory/store.ts
|
|
13896
14434
|
import { createHash as createHash6, randomUUID as randomUUID3 } from "crypto";
|
|
13897
|
-
import { mkdir as mkdir17, readdir as
|
|
13898
|
-
import { join as
|
|
14435
|
+
import { mkdir as mkdir17, readdir as readdir11, realpath as realpath5, stat as stat7, writeFile as writeFile10 } from "fs/promises";
|
|
14436
|
+
import { join as join26 } from "path";
|
|
13899
14437
|
import * as lockfile5 from "proper-lockfile";
|
|
13900
14438
|
var initializations = /* @__PURE__ */ new Map();
|
|
13901
14439
|
var README_NAME = "README.md";
|
|
@@ -13925,7 +14463,7 @@ var WorkspaceMemoryStore = class {
|
|
|
13925
14463
|
maxNotes;
|
|
13926
14464
|
maxBytes;
|
|
13927
14465
|
constructor(profileDir, limits = {}) {
|
|
13928
|
-
this.root =
|
|
14466
|
+
this.root = join26(profileDir, "memory");
|
|
13929
14467
|
this.maxNotes = limits.maxNotes ?? 200;
|
|
13930
14468
|
this.maxBytes = limits.maxBytes ?? 1024 * 1024;
|
|
13931
14469
|
}
|
|
@@ -13933,10 +14471,10 @@ var WorkspaceMemoryStore = class {
|
|
|
13933
14471
|
const directory = await this.ensureDirectory(cwdRealpath);
|
|
13934
14472
|
let noteCount = 0;
|
|
13935
14473
|
let totalBytes = 0;
|
|
13936
|
-
for (const entry of await
|
|
14474
|
+
for (const entry of await readdir11(directory, { withFileTypes: true })) {
|
|
13937
14475
|
if (entry.name === README_NAME || !entry.isFile() || entry.name.startsWith(".README.md.tmp-")) continue;
|
|
13938
14476
|
try {
|
|
13939
|
-
const info = await
|
|
14477
|
+
const info = await stat7(join26(directory, entry.name));
|
|
13940
14478
|
noteCount += 1;
|
|
13941
14479
|
totalBytes += info.size;
|
|
13942
14480
|
} catch (err) {
|
|
@@ -13957,7 +14495,7 @@ var WorkspaceMemoryStore = class {
|
|
|
13957
14495
|
/** Creates a new note; capacity reporting is advisory, not a concurrent hard quota. */
|
|
13958
14496
|
async appendNote(cwdRealpath, content) {
|
|
13959
14497
|
const directory = await this.ensureDirectory(cwdRealpath);
|
|
13960
|
-
const path4 =
|
|
14498
|
+
const path4 = join26(directory, `${randomUUID3()}.md`);
|
|
13961
14499
|
await writeFile10(path4, content, { encoding: "utf8", flag: "wx", mode: 384 });
|
|
13962
14500
|
return path4;
|
|
13963
14501
|
}
|
|
@@ -13965,11 +14503,11 @@ var WorkspaceMemoryStore = class {
|
|
|
13965
14503
|
const resolved = await realpath5(cwdRealpath);
|
|
13966
14504
|
const canonical = process.platform === "win32" ? resolved.toLowerCase() : resolved;
|
|
13967
14505
|
const hash = createHash6("sha256").update(canonical).digest("hex");
|
|
13968
|
-
const directory =
|
|
14506
|
+
const directory = join26(this.root, hash);
|
|
13969
14507
|
await mkdir17(directory, { recursive: true, mode: 448 });
|
|
13970
|
-
const readmePath =
|
|
14508
|
+
const readmePath = join26(directory, README_NAME);
|
|
13971
14509
|
try {
|
|
13972
|
-
await
|
|
14510
|
+
await stat7(readmePath);
|
|
13973
14511
|
} catch (err) {
|
|
13974
14512
|
if (err.code !== "ENOENT") throw err;
|
|
13975
14513
|
const existing = initializations.get(directory);
|
|
@@ -13983,7 +14521,7 @@ var WorkspaceMemoryStore = class {
|
|
|
13983
14521
|
});
|
|
13984
14522
|
try {
|
|
13985
14523
|
try {
|
|
13986
|
-
await
|
|
14524
|
+
await stat7(readmePath);
|
|
13987
14525
|
} catch (readmeError) {
|
|
13988
14526
|
if (readmeError.code !== "ENOENT") throw readmeError;
|
|
13989
14527
|
await writeFileAtomic(readmePath, README, { mode: 384 });
|
|
@@ -14434,6 +14972,95 @@ function fallbackReason(err) {
|
|
|
14434
14972
|
return UNKNOWN_REASON;
|
|
14435
14973
|
}
|
|
14436
14974
|
|
|
14975
|
+
// src/bot/run-progress.ts
|
|
14976
|
+
var TAIL_MAX = 240;
|
|
14977
|
+
var MAX_TOOLS_IN_FLIGHT = 8;
|
|
14978
|
+
var RunProgressRegistry = class {
|
|
14979
|
+
constructor(now = Date.now) {
|
|
14980
|
+
this.now = now;
|
|
14981
|
+
}
|
|
14982
|
+
now;
|
|
14983
|
+
live = /* @__PURE__ */ new Map();
|
|
14984
|
+
begin(input) {
|
|
14985
|
+
this.live.set(input.scope, {
|
|
14986
|
+
scope: input.scope,
|
|
14987
|
+
runId: input.runId,
|
|
14988
|
+
startedAt: input.startedAt,
|
|
14989
|
+
lastEventAt: input.startedAt,
|
|
14990
|
+
phase: "starting",
|
|
14991
|
+
sessionId: input.sessionId,
|
|
14992
|
+
threadId: input.threadId,
|
|
14993
|
+
model: input.model,
|
|
14994
|
+
cwd: input.cwd,
|
|
14995
|
+
toolsInFlight: [],
|
|
14996
|
+
toolCalls: 0,
|
|
14997
|
+
thinkingTail: "",
|
|
14998
|
+
textTail: "",
|
|
14999
|
+
usage: { inputTokens: 0, outputTokens: 0, cachedInputTokens: 0, costUsd: 0 }
|
|
15000
|
+
});
|
|
15001
|
+
}
|
|
15002
|
+
/** Fold one agent event into the live entry. No-op when the scope isn't running. */
|
|
15003
|
+
record(scope, event) {
|
|
15004
|
+
const entry = this.live.get(scope);
|
|
15005
|
+
if (!entry) return;
|
|
15006
|
+
const at = this.now();
|
|
15007
|
+
entry.lastEventAt = at;
|
|
15008
|
+
switch (event.type) {
|
|
15009
|
+
case "system":
|
|
15010
|
+
if (event.sessionId) entry.sessionId = event.sessionId;
|
|
15011
|
+
if (event.threadId) entry.threadId = event.threadId;
|
|
15012
|
+
if (event.model) entry.model = event.model;
|
|
15013
|
+
if (event.cwd) entry.cwd = event.cwd;
|
|
15014
|
+
return;
|
|
15015
|
+
case "thinking":
|
|
15016
|
+
entry.phase = "thinking";
|
|
15017
|
+
entry.thinkingTail = tail(entry.thinkingTail + event.delta);
|
|
15018
|
+
return;
|
|
15019
|
+
case "text":
|
|
15020
|
+
entry.phase = "text";
|
|
15021
|
+
entry.textTail = tail(entry.textTail + event.delta);
|
|
15022
|
+
return;
|
|
15023
|
+
case "final_text":
|
|
15024
|
+
entry.phase = "text";
|
|
15025
|
+
entry.textTail = tail(event.content);
|
|
15026
|
+
return;
|
|
15027
|
+
case "tool_use":
|
|
15028
|
+
entry.phase = "tool";
|
|
15029
|
+
entry.toolCalls += 1;
|
|
15030
|
+
entry.toolsInFlight.push({ id: event.id, name: event.name, startedAt: at });
|
|
15031
|
+
if (entry.toolsInFlight.length > MAX_TOOLS_IN_FLIGHT) entry.toolsInFlight.shift();
|
|
15032
|
+
return;
|
|
15033
|
+
case "tool_result": {
|
|
15034
|
+
const index = entry.toolsInFlight.findIndex((tool2) => tool2.id === event.id);
|
|
15035
|
+
const tool = index >= 0 ? entry.toolsInFlight.splice(index, 1)[0] : void 0;
|
|
15036
|
+
entry.lastTool = { name: tool?.name ?? "tool", ok: !event.isError, at };
|
|
15037
|
+
return;
|
|
15038
|
+
}
|
|
15039
|
+
case "usage":
|
|
15040
|
+
if (event.inputTokens !== void 0) entry.usage.inputTokens += event.inputTokens;
|
|
15041
|
+
if (event.outputTokens !== void 0) entry.usage.outputTokens += event.outputTokens;
|
|
15042
|
+
if (event.cachedInputTokens !== void 0) entry.usage.cachedInputTokens += event.cachedInputTokens;
|
|
15043
|
+
if (event.costUsd !== void 0) entry.usage.costUsd += event.costUsd;
|
|
15044
|
+
return;
|
|
15045
|
+
case "done":
|
|
15046
|
+
case "error":
|
|
15047
|
+
this.live.delete(scope);
|
|
15048
|
+
return;
|
|
15049
|
+
}
|
|
15050
|
+
}
|
|
15051
|
+
/** Drop the entry when a run ends without a terminal event (stop before EOF). */
|
|
15052
|
+
clear(scope) {
|
|
15053
|
+
this.live.delete(scope);
|
|
15054
|
+
}
|
|
15055
|
+
/** Live snapshot, or undefined when nothing is running for the scope. */
|
|
15056
|
+
active(scope) {
|
|
15057
|
+
return this.live.get(scope);
|
|
15058
|
+
}
|
|
15059
|
+
};
|
|
15060
|
+
function tail(text2) {
|
|
15061
|
+
return text2.length > TAIL_MAX ? text2.slice(-TAIL_MAX) : text2;
|
|
15062
|
+
}
|
|
15063
|
+
|
|
14437
15064
|
// src/bot/quote.ts
|
|
14438
15065
|
async function fetchQuotedContext(channel, messageId, opts) {
|
|
14439
15066
|
try {
|
|
@@ -14619,13 +15246,13 @@ function fitCotLines(lines) {
|
|
|
14619
15246
|
tailBodyLength = next;
|
|
14620
15247
|
}
|
|
14621
15248
|
for (; start <= visualLines.length; start += 1) {
|
|
14622
|
-
const
|
|
15249
|
+
const tail2 = visualLines.slice(start);
|
|
14623
15250
|
const openingFence = fenceLengthAt(visualLines, start);
|
|
14624
|
-
const closingFence = fenceLengthAfter(
|
|
15251
|
+
const closingFence = fenceLengthAfter(tail2, openingFence);
|
|
14625
15252
|
const fitted = [
|
|
14626
15253
|
omission,
|
|
14627
15254
|
...openingFence ? ["`".repeat(openingFence)] : [],
|
|
14628
|
-
...
|
|
15255
|
+
...tail2,
|
|
14629
15256
|
...closingFence ? ["`".repeat(closingFence)] : []
|
|
14630
15257
|
];
|
|
14631
15258
|
if (fitted.join("\n").length <= COT_CARD_BODY_MAX) return fitted;
|
|
@@ -15031,12 +15658,13 @@ async function startChannel(deps) {
|
|
|
15031
15658
|
const activeRuns = new ActiveRuns(notifyBusyChanged);
|
|
15032
15659
|
const chatModeCache = new ChatModeCache();
|
|
15033
15660
|
const pool = new ProcessPool(() => getMaxConcurrentRuns(controls.cfg));
|
|
15034
|
-
const
|
|
15035
|
-
const
|
|
15661
|
+
const progress = new RunProgressRegistry();
|
|
15662
|
+
const executor = new RunExecutor({ agent, pool, activeRuns, progress });
|
|
15663
|
+
const profileDir = deps.appPaths?.mediaDir ? dirname20(deps.appPaths.mediaDir) : void 0;
|
|
15036
15664
|
const contextStore = profileDir ? new ConversationContextStore(profileDir) : void 0;
|
|
15037
15665
|
const memory = profileDir ? new WorkspaceMemoryStore(profileDir) : void 0;
|
|
15038
15666
|
const appSecret = await resolveAppSecret(cfg, deps.appPaths);
|
|
15039
|
-
const callbackNonceStore = deps.appPaths?.mediaDir ? new CallbackNonceStore(
|
|
15667
|
+
const callbackNonceStore = deps.appPaths?.mediaDir ? new CallbackNonceStore(join27(dirname20(deps.appPaths.mediaDir), "callback-nonces.json")) : void 0;
|
|
15040
15668
|
await callbackNonceStore?.load();
|
|
15041
15669
|
const callbackAuth = callbackNonceStore ? new CallbackAuth({
|
|
15042
15670
|
keys: [{ version: 1, secret: appSecret }],
|
|
@@ -15065,7 +15693,7 @@ async function startChannel(deps) {
|
|
|
15065
15693
|
webhookServer,
|
|
15066
15694
|
webhookBodyLimitBytes: cfg.webhook.bodyLimitBytes,
|
|
15067
15695
|
dedupeTtlMs: cfg.webhook.dedupeTtlMs,
|
|
15068
|
-
dedupeFile: deps.appPaths?.mediaDir ?
|
|
15696
|
+
dedupeFile: deps.appPaths?.mediaDir ? join27(dirname20(deps.appPaths.mediaDir), "webhook-events.json") : void 0,
|
|
15069
15697
|
streamThrottleMs: 250,
|
|
15070
15698
|
sendMessageApiVersion: () => getSendMessageApiVersion(controls.cfg)
|
|
15071
15699
|
});
|
|
@@ -15148,7 +15776,8 @@ async function startChannel(deps) {
|
|
|
15148
15776
|
logThreadModeOverride,
|
|
15149
15777
|
lastRunCompletedAtByScope,
|
|
15150
15778
|
executor,
|
|
15151
|
-
pool
|
|
15779
|
+
pool,
|
|
15780
|
+
runProgress: progress
|
|
15152
15781
|
})
|
|
15153
15782
|
).catch((err) => log.fail("intake", err));
|
|
15154
15783
|
},
|
|
@@ -15167,6 +15796,7 @@ async function startChannel(deps) {
|
|
|
15167
15796
|
agent,
|
|
15168
15797
|
processPool: pool,
|
|
15169
15798
|
runExecutor: executor,
|
|
15799
|
+
runProgress: progress,
|
|
15170
15800
|
controls,
|
|
15171
15801
|
pending,
|
|
15172
15802
|
chatModeCache,
|
|
@@ -15310,6 +15940,7 @@ async function intakeMessage(deps) {
|
|
|
15310
15940
|
logThreadModeOverride,
|
|
15311
15941
|
executor,
|
|
15312
15942
|
pool,
|
|
15943
|
+
runProgress,
|
|
15313
15944
|
lastRunCompletedAtByScope
|
|
15314
15945
|
} = deps;
|
|
15315
15946
|
const preview = msg.content.length > 80 ? `${msg.content.slice(0, 80)}\u2026` : msg.content;
|
|
@@ -15415,10 +16046,11 @@ async function intakeMessage(deps) {
|
|
|
15415
16046
|
}),
|
|
15416
16047
|
runExecutor: executor,
|
|
15417
16048
|
processPool: pool,
|
|
16049
|
+
runProgress,
|
|
15418
16050
|
controls
|
|
15419
16051
|
});
|
|
15420
16052
|
if (handled) {
|
|
15421
|
-
const dropped = pending.cancel(scope);
|
|
16053
|
+
const dropped = isReadOnlyCommandInvocation(emsg.content, emsg.mentions) ? [] : pending.cancel(scope);
|
|
15422
16054
|
log.info("intake", "command", { scope, droppedPending: dropped.length });
|
|
15423
16055
|
return;
|
|
15424
16056
|
}
|
|
@@ -16462,9 +17094,55 @@ function startAutoUpdateScheduler(deps) {
|
|
|
16462
17094
|
};
|
|
16463
17095
|
}
|
|
16464
17096
|
|
|
17097
|
+
// src/selfupdate/launcher-capabilities.ts
|
|
17098
|
+
import { readFileSync as readFileSync6 } from "fs";
|
|
17099
|
+
var REQUIRED_LAUNCHER_CAPABILITIES = [];
|
|
17100
|
+
function inspectLauncherCapabilities(bootFile, required = REQUIRED_LAUNCHER_CAPABILITIES) {
|
|
17101
|
+
const boot = readBootRecord(bootFile);
|
|
17102
|
+
const reported = boot?.launcher !== void 0;
|
|
17103
|
+
const capabilities = boot?.launcher?.capabilities ?? [];
|
|
17104
|
+
return {
|
|
17105
|
+
reported,
|
|
17106
|
+
capabilities,
|
|
17107
|
+
missing: required.filter((capability) => !capabilities.includes(capability)),
|
|
17108
|
+
...typeof boot?.version === "string" ? { bootVersion: boot.version } : {}
|
|
17109
|
+
};
|
|
17110
|
+
}
|
|
17111
|
+
function formatLauncherCapabilityWarning(diagnostics, options) {
|
|
17112
|
+
if (diagnostics.missing.length === 0) return void 0;
|
|
17113
|
+
const legacy = diagnostics.reported ? "" : "\uFF08\u65E7 launcher \u672A\u4E0A\u62A5\u80FD\u529B\uFF09";
|
|
17114
|
+
const fix = options.refreshed ? "\u5DF2\u5237\u65B0 launcher \u526F\u672C\uFF0C\u91CD\u542F\u540E\u53F0\u670D\u52A1\u540E\u751F\u6548\uFF1A`xiaojiu-agent-bridge restart`\u3002" : `\u65E0\u6CD5\u5237\u65B0 launcher \u526F\u672C\uFF1A\u91CD\u65B0\u5B89\u88C5\u540E\u518D\u91CD\u542F\u670D\u52A1\uFF1A${manualLauncherUpdateCommand()}`;
|
|
17115
|
+
return `\u26A0 launcher \u7F3A\u5C11\u80FD\u529B ${diagnostics.missing.join(", ")}${legacy}\u3002${fix}`;
|
|
17116
|
+
}
|
|
17117
|
+
function manualLauncherUpdateCommand() {
|
|
17118
|
+
return `npm install -g ${packageName}@latest --registry=${REGISTRY_URL}`;
|
|
17119
|
+
}
|
|
17120
|
+
function launcherCapabilitiesLine(diagnostics) {
|
|
17121
|
+
if (!diagnostics.reported) return "legacy (boot.json has no launcher field)";
|
|
17122
|
+
return diagnostics.capabilities.length > 0 ? diagnostics.capabilities.join(", ") : "(none)";
|
|
17123
|
+
}
|
|
17124
|
+
function readBootRecord(file) {
|
|
17125
|
+
try {
|
|
17126
|
+
const parsed = JSON.parse(readFileSync6(file, "utf8"));
|
|
17127
|
+
if (typeof parsed !== "object" || parsed === null) return void 0;
|
|
17128
|
+
const version3 = "version" in parsed ? parsed.version : void 0;
|
|
17129
|
+
const record5 = {};
|
|
17130
|
+
if (typeof version3 === "string") record5.version = version3;
|
|
17131
|
+
if ("launcher" in parsed && typeof parsed.launcher === "object" && parsed.launcher !== null) {
|
|
17132
|
+
const raw = "capabilities" in parsed.launcher ? parsed.launcher.capabilities : void 0;
|
|
17133
|
+
record5.launcher = {
|
|
17134
|
+
capabilities: Array.isArray(raw) ? raw.filter((item) => typeof item === "string") : []
|
|
17135
|
+
};
|
|
17136
|
+
}
|
|
17137
|
+
return record5;
|
|
17138
|
+
} catch {
|
|
17139
|
+
return void 0;
|
|
17140
|
+
}
|
|
17141
|
+
}
|
|
17142
|
+
|
|
16465
17143
|
// src/cli/commands/migrate-launcher.ts
|
|
16466
17144
|
import { readFile as readFile16 } from "fs/promises";
|
|
16467
|
-
import { join as
|
|
17145
|
+
import { join as join28 } from "path";
|
|
16468
17146
|
var RETRY_AFTER_MS = 24 * 60 * 60 * 1e3;
|
|
16469
17147
|
async function maybeMigrateServiceToLauncher(opts) {
|
|
16470
17148
|
const env = opts.env ?? process.env;
|
|
@@ -16472,7 +17150,7 @@ async function maybeMigrateServiceToLauncher(opts) {
|
|
|
16472
17150
|
if (!getAutoUpdateEnabled(opts.cfg)) return { migrated: false, reason: "auto-update disabled" };
|
|
16473
17151
|
if (isAutoUpdateEnvDisabled(env)) return { migrated: false, reason: "update checks disabled" };
|
|
16474
17152
|
const layout = updateLayout(opts.rootDir);
|
|
16475
|
-
const markerFile =
|
|
17153
|
+
const markerFile = join28(layout.updateDir, "launcher-migration.json");
|
|
16476
17154
|
const lastAttempt = await readFile16(markerFile, "utf8").then((text2) => {
|
|
16477
17155
|
const parsed = JSON.parse(text2);
|
|
16478
17156
|
return typeof parsed === "object" && parsed !== null && "attemptedAt" in parsed && typeof parsed.attemptedAt === "string" ? Date.parse(parsed.attemptedAt) : Number.NaN;
|
|
@@ -17469,7 +18147,7 @@ function asRecord4(body) {
|
|
|
17469
18147
|
}
|
|
17470
18148
|
|
|
17471
18149
|
// src/ui/fleet.ts
|
|
17472
|
-
function listBots(supervisor,
|
|
18150
|
+
function listBots(supervisor, version3, now) {
|
|
17473
18151
|
return supervisor.list().map((s) => ({
|
|
17474
18152
|
id: s.profile,
|
|
17475
18153
|
profileName: s.profile,
|
|
@@ -17477,7 +18155,7 @@ function listBots(supervisor, version2, now) {
|
|
|
17477
18155
|
botName: s.botName,
|
|
17478
18156
|
appId: s.appId,
|
|
17479
18157
|
pid: s.pid,
|
|
17480
|
-
version:
|
|
18158
|
+
version: version3,
|
|
17481
18159
|
startedAt: s.startedAt,
|
|
17482
18160
|
uptimeMs: s.startedAt ? Math.max(0, now - Date.parse(s.startedAt)) : 0
|
|
17483
18161
|
}));
|
|
@@ -17711,7 +18389,10 @@ async function route(req, res, deps, url) {
|
|
|
17711
18389
|
hosted: true,
|
|
17712
18390
|
version: deps.version,
|
|
17713
18391
|
activeProfile: await readActiveProfile(deps.rootDir),
|
|
17714
|
-
online: sup.list().length
|
|
18392
|
+
online: sup.list().length,
|
|
18393
|
+
// Launcher ↔ child handshake; a legacy boot record reports
|
|
18394
|
+
// `reported: false` instead of failing the console.
|
|
18395
|
+
launcher: inspectLauncherCapabilities(updateLayout(deps.rootDir ?? paths.rootDir).bootStateFile)
|
|
17715
18396
|
});
|
|
17716
18397
|
return;
|
|
17717
18398
|
}
|
|
@@ -17965,8 +18646,8 @@ var WebhookRequestError2 = class extends Error {
|
|
|
17965
18646
|
};
|
|
17966
18647
|
|
|
17967
18648
|
// src/agent/model-discovery.ts
|
|
17968
|
-
import { createInterface as
|
|
17969
|
-
import { join as
|
|
18649
|
+
import { createInterface as createInterface8 } from "readline";
|
|
18650
|
+
import { join as join29 } from "path";
|
|
17970
18651
|
var DEFAULT_TIMEOUT_MS3 = 5e3;
|
|
17971
18652
|
async function discoverModels(agentKind, options) {
|
|
17972
18653
|
if (!options) return supportedModels(agentKind);
|
|
@@ -18082,7 +18763,7 @@ async function listCodexModels(options) {
|
|
|
18082
18763
|
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS3;
|
|
18083
18764
|
let settled = false;
|
|
18084
18765
|
return new Promise((resolve5, reject4) => {
|
|
18085
|
-
const rl =
|
|
18766
|
+
const rl = createInterface8({ input: child.stdout, crlfDelay: Infinity });
|
|
18086
18767
|
const timer = setTimeout(() => fail(new Error("codex model discovery timed out")), timeoutMs);
|
|
18087
18768
|
const cleanup = (kill) => {
|
|
18088
18769
|
if (settled) return;
|
|
@@ -18139,7 +18820,7 @@ ${JSON.stringify({ method: "model/list", id: 2, params: { includeHidden: false,
|
|
|
18139
18820
|
function spawnCodexAppServer2(options) {
|
|
18140
18821
|
const envOverrides = {};
|
|
18141
18822
|
if (options.codexHome) envOverrides.CODEX_HOME = options.codexHome;
|
|
18142
|
-
else if (options.inheritCodexHome === false) envOverrides.CODEX_HOME =
|
|
18823
|
+
else if (options.inheritCodexHome === false) envOverrides.CODEX_HOME = join29(options.profileStateDir, "codex-home");
|
|
18143
18824
|
return spawnProcess(options.binary, ["app-server", "--listen", "stdio://"], {
|
|
18144
18825
|
env: mergeProcessEnv(process.env, envOverrides),
|
|
18145
18826
|
stdio: ["pipe", "pipe", "pipe"]
|
|
@@ -18436,6 +19117,124 @@ function* translateEvent2(raw) {
|
|
|
18436
19117
|
yield* genericJsonEvent(raw);
|
|
18437
19118
|
}
|
|
18438
19119
|
|
|
19120
|
+
// src/agent/pi/side-query.ts
|
|
19121
|
+
import { mkdtemp as mkdtemp2, readdir as readdir12, readFile as readFile21, rm as rm17, stat as stat8 } from "fs/promises";
|
|
19122
|
+
import { homedir as homedir8, tmpdir as tmpdir4 } from "os";
|
|
19123
|
+
import { join as join30 } from "path";
|
|
19124
|
+
function buildPiSideQueryArgs(input) {
|
|
19125
|
+
return [
|
|
19126
|
+
"-p",
|
|
19127
|
+
"--mode",
|
|
19128
|
+
"json",
|
|
19129
|
+
"--fork",
|
|
19130
|
+
input.sessionFile,
|
|
19131
|
+
"--session-dir",
|
|
19132
|
+
input.sessionDir,
|
|
19133
|
+
"--no-tools"
|
|
19134
|
+
];
|
|
19135
|
+
}
|
|
19136
|
+
async function findPiSessionFile(sessionId, sessionsRoot = join30(homedir8(), ".pi", "agent", "sessions")) {
|
|
19137
|
+
let dirs;
|
|
19138
|
+
try {
|
|
19139
|
+
dirs = await readdir12(sessionsRoot, { withFileTypes: true });
|
|
19140
|
+
} catch {
|
|
19141
|
+
return void 0;
|
|
19142
|
+
}
|
|
19143
|
+
for (const dir of dirs) {
|
|
19144
|
+
if (!dir.isDirectory()) continue;
|
|
19145
|
+
const cwdDir = join30(sessionsRoot, dir.name);
|
|
19146
|
+
let files;
|
|
19147
|
+
try {
|
|
19148
|
+
files = await readdir12(cwdDir);
|
|
19149
|
+
} catch {
|
|
19150
|
+
continue;
|
|
19151
|
+
}
|
|
19152
|
+
const hit = files.find((file) => file.endsWith(".jsonl") && file.includes(sessionId));
|
|
19153
|
+
if (hit) return join30(cwdDir, hit);
|
|
19154
|
+
}
|
|
19155
|
+
return void 0;
|
|
19156
|
+
}
|
|
19157
|
+
async function findLatestPiSessionFile(cwd, sessionsRoot = join30(homedir8(), ".pi", "agent", "sessions")) {
|
|
19158
|
+
const candidates = [];
|
|
19159
|
+
let dirs;
|
|
19160
|
+
try {
|
|
19161
|
+
dirs = await readdir12(sessionsRoot, { withFileTypes: true });
|
|
19162
|
+
} catch {
|
|
19163
|
+
return void 0;
|
|
19164
|
+
}
|
|
19165
|
+
for (const dir of dirs) {
|
|
19166
|
+
if (!dir.isDirectory()) continue;
|
|
19167
|
+
const base = join30(sessionsRoot, dir.name);
|
|
19168
|
+
let files;
|
|
19169
|
+
try {
|
|
19170
|
+
files = await readdir12(base);
|
|
19171
|
+
} catch {
|
|
19172
|
+
continue;
|
|
19173
|
+
}
|
|
19174
|
+
for (const file of files) {
|
|
19175
|
+
if (!file.endsWith(".jsonl")) continue;
|
|
19176
|
+
const path4 = join30(base, file);
|
|
19177
|
+
try {
|
|
19178
|
+
candidates.push({ file: path4, mtime: (await stat8(path4)).mtimeMs });
|
|
19179
|
+
} catch {
|
|
19180
|
+
continue;
|
|
19181
|
+
}
|
|
19182
|
+
}
|
|
19183
|
+
}
|
|
19184
|
+
candidates.sort((a, b) => b.mtime - a.mtime);
|
|
19185
|
+
for (const candidate of candidates.slice(0, 10)) {
|
|
19186
|
+
const header = await readSessionHeader(candidate.file);
|
|
19187
|
+
if (header?.type === "session" && sameCwd(header.cwd, cwd)) return candidate.file;
|
|
19188
|
+
}
|
|
19189
|
+
return void 0;
|
|
19190
|
+
}
|
|
19191
|
+
async function readSessionHeader(file) {
|
|
19192
|
+
try {
|
|
19193
|
+
const text2 = await readFile21(file, "utf8");
|
|
19194
|
+
for (const line of text2.split("\n").slice(0, 5)) {
|
|
19195
|
+
if (!line.trim()) continue;
|
|
19196
|
+
try {
|
|
19197
|
+
return JSON.parse(line);
|
|
19198
|
+
} catch {
|
|
19199
|
+
continue;
|
|
19200
|
+
}
|
|
19201
|
+
}
|
|
19202
|
+
} catch {
|
|
19203
|
+
return void 0;
|
|
19204
|
+
}
|
|
19205
|
+
return void 0;
|
|
19206
|
+
}
|
|
19207
|
+
function sameCwd(left, right) {
|
|
19208
|
+
if (typeof left !== "string") return false;
|
|
19209
|
+
const normalize = (value) => value.replace(/\\/g, "/").replace(/\/+$/, "").toLowerCase();
|
|
19210
|
+
return normalize(left) === normalize(right);
|
|
19211
|
+
}
|
|
19212
|
+
async function runPiSideQuery(input) {
|
|
19213
|
+
const sessionFile = input.sessionId ? await findPiSessionFile(input.sessionId, input.sessionsRoot) : await findLatestPiSessionFile(input.cwd, input.sessionsRoot);
|
|
19214
|
+
if (!sessionFile) {
|
|
19215
|
+
return {
|
|
19216
|
+
text: "",
|
|
19217
|
+
error: input.sessionId ? `\u627E\u4E0D\u5230 Pi \u4F1A\u8BDD ${input.sessionId.slice(0, 8)}\u2026` : "\u4F1A\u8BDD\u5C1A\u672A\u5EFA\u7ACB"
|
|
19218
|
+
};
|
|
19219
|
+
}
|
|
19220
|
+
const sessionDir = await mkdtemp2(join30(tmpdir4(), "xiaojiu-pi-btw-"));
|
|
19221
|
+
try {
|
|
19222
|
+
const result = await runJsonlSideQuery({
|
|
19223
|
+
agent: "pi",
|
|
19224
|
+
binary: input.binary,
|
|
19225
|
+
args: buildPiSideQueryArgs({ sessionFile, sessionDir }),
|
|
19226
|
+
cwd: input.cwd,
|
|
19227
|
+
prompt: buildBtwPrompt(input.question),
|
|
19228
|
+
translate: (raw) => [...translateEvent2(raw)],
|
|
19229
|
+
signal: input.signal
|
|
19230
|
+
});
|
|
19231
|
+
return result.error ? { text: result.text, error: result.error } : { text: result.text };
|
|
19232
|
+
} finally {
|
|
19233
|
+
await rm17(sessionDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 25 }).catch(() => {
|
|
19234
|
+
});
|
|
19235
|
+
}
|
|
19236
|
+
}
|
|
19237
|
+
|
|
18439
19238
|
// src/agent/pi/adapter.ts
|
|
18440
19239
|
var PiAdapter = class extends JsonlAgentAdapter {
|
|
18441
19240
|
constructor(options = {}) {
|
|
@@ -18444,7 +19243,14 @@ var PiAdapter = class extends JsonlAgentAdapter {
|
|
|
18444
19243
|
displayName: "Pi",
|
|
18445
19244
|
binary: options.binary ?? "pi",
|
|
18446
19245
|
buildArgs: buildPiArgs,
|
|
18447
|
-
translate: (raw) => [...translateEvent2(raw)]
|
|
19246
|
+
translate: (raw) => [...translateEvent2(raw)],
|
|
19247
|
+
sideQuery: (opts) => runPiSideQuery({
|
|
19248
|
+
binary: options.binary ?? "pi",
|
|
19249
|
+
cwd: opts.cwd,
|
|
19250
|
+
...opts.sessionId ? { sessionId: opts.sessionId } : {},
|
|
19251
|
+
question: opts.question,
|
|
19252
|
+
signal: opts.signal
|
|
19253
|
+
})
|
|
18448
19254
|
});
|
|
18449
19255
|
}
|
|
18450
19256
|
};
|
|
@@ -18599,6 +19405,113 @@ function* translateEvent3(raw) {
|
|
|
18599
19405
|
yield* genericJsonEvent(raw);
|
|
18600
19406
|
}
|
|
18601
19407
|
|
|
19408
|
+
// src/agent/opencode/side-query.ts
|
|
19409
|
+
import { randomBytes as randomBytes6 } from "crypto";
|
|
19410
|
+
import { createInterface as createInterface9 } from "readline";
|
|
19411
|
+
var ANSWER_MAX = 8e3;
|
|
19412
|
+
var READY_TIMEOUT_MS = 2e4;
|
|
19413
|
+
function buildOpenCodeServeArgs() {
|
|
19414
|
+
return ["serve", "--port", "0", "--stdio"];
|
|
19415
|
+
}
|
|
19416
|
+
async function runOpenCodeSideQuery(input) {
|
|
19417
|
+
if (!input.sessionId) return { text: "", error: "\u4F1A\u8BDD\u5C1A\u672A\u5EFA\u7ACB" };
|
|
19418
|
+
const password2 = randomBytes6(32).toString("base64url");
|
|
19419
|
+
const child = spawnProcess(input.binary, buildOpenCodeServeArgs(), {
|
|
19420
|
+
cwd: input.cwd,
|
|
19421
|
+
env: { ...process.env, OPENCODE_PASSWORD: password2 },
|
|
19422
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
19423
|
+
detached: process.platform !== "win32"
|
|
19424
|
+
});
|
|
19425
|
+
let stderr = "";
|
|
19426
|
+
child.stderr.on("data", (chunk) => {
|
|
19427
|
+
if (stderr.length < 4e3) stderr += chunk.toString("utf8");
|
|
19428
|
+
});
|
|
19429
|
+
let spawnError;
|
|
19430
|
+
child.once("error", (err) => {
|
|
19431
|
+
spawnError = err instanceof Error ? err : new Error(String(err));
|
|
19432
|
+
});
|
|
19433
|
+
child.stdin.on("error", () => {
|
|
19434
|
+
});
|
|
19435
|
+
const { promise, resolve: resolve5 } = deferred();
|
|
19436
|
+
let settled = false;
|
|
19437
|
+
const settle = (result) => {
|
|
19438
|
+
if (settled) return;
|
|
19439
|
+
settled = true;
|
|
19440
|
+
clearTimeout(readyTimer);
|
|
19441
|
+
resolve5(result);
|
|
19442
|
+
};
|
|
19443
|
+
const onAbort = () => {
|
|
19444
|
+
killProcessTree(child, true);
|
|
19445
|
+
settle({ text: "", error: "aborted" });
|
|
19446
|
+
};
|
|
19447
|
+
input.signal.addEventListener("abort", onAbort, { once: true });
|
|
19448
|
+
const readyTimer = setTimeout(() => {
|
|
19449
|
+
killProcessTree(child, true);
|
|
19450
|
+
settle({ text: "", error: "opencode serve \u672A\u5C31\u7EEA" });
|
|
19451
|
+
}, READY_TIMEOUT_MS);
|
|
19452
|
+
const rl = createInterface9({ input: child.stdout, crlfDelay: Infinity });
|
|
19453
|
+
let started = false;
|
|
19454
|
+
rl.on("line", (line) => {
|
|
19455
|
+
if (started) return;
|
|
19456
|
+
const trimmed = line.trim();
|
|
19457
|
+
if (!trimmed.startsWith("{")) return;
|
|
19458
|
+
let url;
|
|
19459
|
+
try {
|
|
19460
|
+
const parsed = JSON.parse(trimmed);
|
|
19461
|
+
if (typeof parsed.url === "string") url = parsed.url;
|
|
19462
|
+
} catch {
|
|
19463
|
+
return;
|
|
19464
|
+
}
|
|
19465
|
+
if (!url) return;
|
|
19466
|
+
started = true;
|
|
19467
|
+
clearTimeout(readyTimer);
|
|
19468
|
+
void requestGenerate({ url, password: password2, cwd: input.cwd, sessionId: input.sessionId, question: input.question }).then((result) => settle(result)).catch((err) => settle({ text: "", error: err instanceof Error ? err.message : String(err) }));
|
|
19469
|
+
});
|
|
19470
|
+
child.once("exit", (code) => {
|
|
19471
|
+
rl.close();
|
|
19472
|
+
if (!started) {
|
|
19473
|
+
const detail = stderr.trim().replace(/\s+/g, " ").slice(0, 300);
|
|
19474
|
+
settle({
|
|
19475
|
+
text: "",
|
|
19476
|
+
error: spawnError?.message ?? (detail || `opencode serve \u9000\u51FA\uFF08code ${code ?? "null"}\uFF09`)
|
|
19477
|
+
});
|
|
19478
|
+
}
|
|
19479
|
+
});
|
|
19480
|
+
try {
|
|
19481
|
+
return await promise;
|
|
19482
|
+
} finally {
|
|
19483
|
+
input.signal.removeEventListener("abort", onAbort);
|
|
19484
|
+
rl.close();
|
|
19485
|
+
child.stdin.end();
|
|
19486
|
+
if (child.exitCode === null && child.signalCode === null) killProcessTree(child, true);
|
|
19487
|
+
}
|
|
19488
|
+
}
|
|
19489
|
+
async function requestGenerate(input) {
|
|
19490
|
+
const authorization = `Basic ${Buffer.from(`opencode:${input.password}`).toString("base64")}`;
|
|
19491
|
+
const response = await fetch(`${input.url}/api/session/${encodeURIComponent(input.sessionId)}/generate`, {
|
|
19492
|
+
method: "POST",
|
|
19493
|
+
headers: {
|
|
19494
|
+
authorization,
|
|
19495
|
+
"content-type": "application/json",
|
|
19496
|
+
"x-opencode-directory": input.cwd
|
|
19497
|
+
},
|
|
19498
|
+
body: JSON.stringify({ prompt: input.question })
|
|
19499
|
+
});
|
|
19500
|
+
const body = await response.text();
|
|
19501
|
+
if (!response.ok) {
|
|
19502
|
+
return { text: "", error: `opencode generate ${response.status}: ${body.trim().slice(0, 300)}` };
|
|
19503
|
+
}
|
|
19504
|
+
let text2;
|
|
19505
|
+
try {
|
|
19506
|
+
const parsed = JSON.parse(body);
|
|
19507
|
+
if (typeof parsed.data?.text === "string") text2 = parsed.data.text;
|
|
19508
|
+
} catch {
|
|
19509
|
+
return { text: "", error: `opencode generate \u8FD4\u56DE\u4E86\u975E JSON \u5185\u5BB9: ${body.trim().slice(0, 200)}` };
|
|
19510
|
+
}
|
|
19511
|
+
const answer = text2?.trim().slice(0, ANSWER_MAX);
|
|
19512
|
+
return answer ? { text: answer } : { text: "", error: "opencode \u6CA1\u6709\u8FD4\u56DE\u7B54\u6848" };
|
|
19513
|
+
}
|
|
19514
|
+
|
|
18602
19515
|
// src/agent/opencode/adapter.ts
|
|
18603
19516
|
var OpenCodeAdapter = class extends JsonlAgentAdapter {
|
|
18604
19517
|
constructor(options = {}) {
|
|
@@ -18608,7 +19521,14 @@ var OpenCodeAdapter = class extends JsonlAgentAdapter {
|
|
|
18608
19521
|
binary: options.binary ?? "opencode",
|
|
18609
19522
|
buildArgs: buildOpenCodeArgs,
|
|
18610
19523
|
buildEnv: buildOpenCodeEnv,
|
|
18611
|
-
translate: (raw) => [...translateEvent3(raw)]
|
|
19524
|
+
translate: (raw) => [...translateEvent3(raw)],
|
|
19525
|
+
sideQuery: (opts) => runOpenCodeSideQuery({
|
|
19526
|
+
binary: options.binary ?? "opencode",
|
|
19527
|
+
cwd: opts.cwd,
|
|
19528
|
+
...opts.sessionId ? { sessionId: opts.sessionId } : {},
|
|
19529
|
+
question: opts.question,
|
|
19530
|
+
signal: opts.signal
|
|
19531
|
+
})
|
|
18612
19532
|
});
|
|
18613
19533
|
}
|
|
18614
19534
|
};
|
|
@@ -18679,6 +19599,168 @@ function* translateEvent4(raw) {
|
|
|
18679
19599
|
yield* genericJsonEvent(raw);
|
|
18680
19600
|
}
|
|
18681
19601
|
|
|
19602
|
+
// src/agent/omp/side-query.ts
|
|
19603
|
+
import { readFile as readFile22, readdir as readdir13, stat as stat9 } from "fs/promises";
|
|
19604
|
+
import { homedir as homedir9 } from "os";
|
|
19605
|
+
import { join as join31 } from "path";
|
|
19606
|
+
import { createInterface as createInterface10 } from "readline";
|
|
19607
|
+
var ANSWER_MAX2 = 8e3;
|
|
19608
|
+
var READY_TIMEOUT_MS2 = 2e4;
|
|
19609
|
+
function buildOmpRpcArgs(input) {
|
|
19610
|
+
return ["--mode", "rpc", "--resume=" + input.sessionId, "--cwd", input.cwd, "--no-ui"];
|
|
19611
|
+
}
|
|
19612
|
+
async function findLatestOmpSessionId(cwd, sessionsRoot = join31(homedir9(), ".omp", "agent", "sessions")) {
|
|
19613
|
+
let dirs;
|
|
19614
|
+
try {
|
|
19615
|
+
dirs = await readdir13(sessionsRoot, { withFileTypes: true });
|
|
19616
|
+
} catch {
|
|
19617
|
+
return void 0;
|
|
19618
|
+
}
|
|
19619
|
+
const candidates = [];
|
|
19620
|
+
for (const dir of dirs) {
|
|
19621
|
+
if (!dir.isDirectory()) continue;
|
|
19622
|
+
const base = join31(sessionsRoot, dir.name);
|
|
19623
|
+
let files;
|
|
19624
|
+
try {
|
|
19625
|
+
files = await readdir13(base);
|
|
19626
|
+
} catch {
|
|
19627
|
+
continue;
|
|
19628
|
+
}
|
|
19629
|
+
for (const file of files) {
|
|
19630
|
+
if (!file.endsWith(".jsonl")) continue;
|
|
19631
|
+
const path4 = join31(base, file);
|
|
19632
|
+
try {
|
|
19633
|
+
candidates.push({ file: path4, mtime: (await stat9(path4)).mtimeMs });
|
|
19634
|
+
} catch {
|
|
19635
|
+
continue;
|
|
19636
|
+
}
|
|
19637
|
+
}
|
|
19638
|
+
}
|
|
19639
|
+
candidates.sort((a, b) => b.mtime - a.mtime);
|
|
19640
|
+
for (const candidate of candidates.slice(0, 10)) {
|
|
19641
|
+
let header;
|
|
19642
|
+
try {
|
|
19643
|
+
for (const line of (await readFile22(candidate.file, "utf8")).split("\n").slice(0, 5)) {
|
|
19644
|
+
if (!line.trim()) continue;
|
|
19645
|
+
try {
|
|
19646
|
+
header = JSON.parse(line);
|
|
19647
|
+
break;
|
|
19648
|
+
} catch {
|
|
19649
|
+
continue;
|
|
19650
|
+
}
|
|
19651
|
+
}
|
|
19652
|
+
} catch {
|
|
19653
|
+
continue;
|
|
19654
|
+
}
|
|
19655
|
+
if (header?.type === "session" && typeof header.id === "string" && sameCwd2(header.cwd, cwd)) {
|
|
19656
|
+
return header.id;
|
|
19657
|
+
}
|
|
19658
|
+
}
|
|
19659
|
+
return void 0;
|
|
19660
|
+
}
|
|
19661
|
+
function sameCwd2(left, right) {
|
|
19662
|
+
if (typeof left !== "string") return false;
|
|
19663
|
+
const normalize = (value) => value.replace(/\\/g, "/").replace(/\/+$/, "").toLowerCase();
|
|
19664
|
+
return normalize(left) === normalize(right);
|
|
19665
|
+
}
|
|
19666
|
+
async function runOmpSideQuery(input) {
|
|
19667
|
+
const sessionId = input.sessionId ?? await findLatestOmpSessionId(input.cwd, input.sessionsRoot);
|
|
19668
|
+
if (!sessionId) return { text: "", error: "\u4F1A\u8BDD\u5C1A\u672A\u5EFA\u7ACB" };
|
|
19669
|
+
const child = spawnProcess(input.binary, buildOmpRpcArgs({ sessionId, cwd: input.cwd }), {
|
|
19670
|
+
cwd: input.cwd,
|
|
19671
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
19672
|
+
detached: process.platform !== "win32"
|
|
19673
|
+
});
|
|
19674
|
+
let stderr = "";
|
|
19675
|
+
child.stderr.on("data", (chunk) => {
|
|
19676
|
+
if (stderr.length < 4e3) stderr += chunk.toString("utf8");
|
|
19677
|
+
});
|
|
19678
|
+
let spawnError;
|
|
19679
|
+
child.once("error", (err) => {
|
|
19680
|
+
spawnError = err instanceof Error ? err : new Error(String(err));
|
|
19681
|
+
});
|
|
19682
|
+
child.stdin.on("error", () => {
|
|
19683
|
+
});
|
|
19684
|
+
const { promise, resolve: resolve5 } = deferred();
|
|
19685
|
+
let settled = false;
|
|
19686
|
+
const settle = (result) => {
|
|
19687
|
+
if (settled) return;
|
|
19688
|
+
settled = true;
|
|
19689
|
+
clearTimeout(deadline);
|
|
19690
|
+
resolve5(result);
|
|
19691
|
+
};
|
|
19692
|
+
const onAbort = () => {
|
|
19693
|
+
killProcessTree(child, true);
|
|
19694
|
+
settle({ text: "", error: "aborted" });
|
|
19695
|
+
};
|
|
19696
|
+
input.signal.addEventListener("abort", onAbort, { once: true });
|
|
19697
|
+
const deadline = setTimeout(() => {
|
|
19698
|
+
killProcessTree(child, true);
|
|
19699
|
+
settle({ text: "", error: "timeout" });
|
|
19700
|
+
}, READY_TIMEOUT_MS2 + 7e4);
|
|
19701
|
+
let ready = false;
|
|
19702
|
+
let answer = "";
|
|
19703
|
+
const rl = createInterface10({ input: child.stdout, crlfDelay: Infinity });
|
|
19704
|
+
rl.on("line", (line) => {
|
|
19705
|
+
const trimmed = line.trim();
|
|
19706
|
+
if (!trimmed) return;
|
|
19707
|
+
let frame;
|
|
19708
|
+
try {
|
|
19709
|
+
frame = JSON.parse(trimmed);
|
|
19710
|
+
} catch {
|
|
19711
|
+
return;
|
|
19712
|
+
}
|
|
19713
|
+
if (frame.type === "ready") {
|
|
19714
|
+
ready = true;
|
|
19715
|
+
try {
|
|
19716
|
+
child.stdin.write(JSON.stringify({ id: "btw", type: "btw", question: input.question }) + "\n");
|
|
19717
|
+
} catch {
|
|
19718
|
+
}
|
|
19719
|
+
return;
|
|
19720
|
+
}
|
|
19721
|
+
if (frame.type === "response" && frame.success === false) {
|
|
19722
|
+
settle({ text: "", error: frame.error || "omp \u62D2\u7EDD\u4E86\u65C1\u8DEF\u63D0\u95EE" });
|
|
19723
|
+
return;
|
|
19724
|
+
}
|
|
19725
|
+
if (frame.type === "btw_record") {
|
|
19726
|
+
const record5 = frame.record ?? {};
|
|
19727
|
+
if (record5.answer) answer = record5.answer;
|
|
19728
|
+
if (record5.status === "complete") {
|
|
19729
|
+
settle({ text: answer.trim().slice(0, ANSWER_MAX2) });
|
|
19730
|
+
} else if (record5.status === "error" || record5.status === "cancelled" || record5.status === "interrupted") {
|
|
19731
|
+
settle({ text: answer.trim().slice(0, ANSWER_MAX2), error: record5.error || `btw ${record5.status}` });
|
|
19732
|
+
}
|
|
19733
|
+
}
|
|
19734
|
+
});
|
|
19735
|
+
rl.on("close", () => {
|
|
19736
|
+
if (settled) return;
|
|
19737
|
+
const detail = stderr.trim().replace(/\s+/g, " ").slice(0, 300);
|
|
19738
|
+
if (answer.trim()) {
|
|
19739
|
+
settle({ text: answer.trim().slice(0, ANSWER_MAX2) });
|
|
19740
|
+
return;
|
|
19741
|
+
}
|
|
19742
|
+
settle({
|
|
19743
|
+
text: "",
|
|
19744
|
+
error: spawnError?.message ?? (detail || `omp rpc \u63D0\u524D\u9000\u51FA\uFF08code ${child.exitCode ?? "null"}\uFF09`)
|
|
19745
|
+
});
|
|
19746
|
+
});
|
|
19747
|
+
const readyTimer = setTimeout(() => {
|
|
19748
|
+
if (!ready) {
|
|
19749
|
+
killProcessTree(child, true);
|
|
19750
|
+
settle({ text: "", error: "omp rpc \u672A\u5C31\u7EEA" });
|
|
19751
|
+
}
|
|
19752
|
+
}, READY_TIMEOUT_MS2);
|
|
19753
|
+
try {
|
|
19754
|
+
return await promise;
|
|
19755
|
+
} finally {
|
|
19756
|
+
clearTimeout(readyTimer);
|
|
19757
|
+
input.signal.removeEventListener("abort", onAbort);
|
|
19758
|
+
rl.close();
|
|
19759
|
+
child.stdin.end();
|
|
19760
|
+
if (child.exitCode === null && child.signalCode === null) killProcessTree(child, true);
|
|
19761
|
+
}
|
|
19762
|
+
}
|
|
19763
|
+
|
|
18682
19764
|
// src/agent/omp/adapter.ts
|
|
18683
19765
|
var OmpAdapter = class extends JsonlAgentAdapter {
|
|
18684
19766
|
constructor(options = {}) {
|
|
@@ -18687,7 +19769,14 @@ var OmpAdapter = class extends JsonlAgentAdapter {
|
|
|
18687
19769
|
displayName: "OMP",
|
|
18688
19770
|
binary: options.binary ?? "omp",
|
|
18689
19771
|
buildArgs: buildOmpArgs,
|
|
18690
|
-
translate: (raw) => [...translateEvent4(raw)]
|
|
19772
|
+
translate: (raw) => [...translateEvent4(raw)],
|
|
19773
|
+
sideQuery: (opts) => runOmpSideQuery({
|
|
19774
|
+
binary: options.binary ?? "omp",
|
|
19775
|
+
cwd: opts.cwd,
|
|
19776
|
+
...opts.sessionId ? { sessionId: opts.sessionId } : {},
|
|
19777
|
+
question: opts.question,
|
|
19778
|
+
signal: opts.signal
|
|
19779
|
+
})
|
|
18691
19780
|
});
|
|
18692
19781
|
}
|
|
18693
19782
|
};
|
|
@@ -18809,7 +19898,8 @@ var ManagedProfile = class {
|
|
|
18809
19898
|
version,
|
|
18810
19899
|
registryFile: this.appPaths.userRegistryFile,
|
|
18811
19900
|
webhookPort: this.cfg.webhook.port,
|
|
18812
|
-
webhookPath: await advertisedWebhookPath(this.appPaths.profile, this.cfg, this.configPath)
|
|
19901
|
+
webhookPath: await advertisedWebhookPath(this.appPaths.profile, this.cfg, this.configPath),
|
|
19902
|
+
launcherPid: launcherPidFromEnv()
|
|
18813
19903
|
});
|
|
18814
19904
|
setStdoutProfileUid(this.profile, this.entry.id);
|
|
18815
19905
|
this.controls = this.makeControls(this.appPaths, this.cfg, this.profileConfig);
|
|
@@ -19287,6 +20377,7 @@ async function runStart(opts) {
|
|
|
19287
20377
|
console.log(`${stdoutTsPrefix()}\u2713 profile\u300C${appPaths2.profile}\u300D\u5DF2\u4E0A\u7EBF${mode}`);
|
|
19288
20378
|
console.log(` \u8FDB\u7A0B: ${process.pid}${uid ? ` uid: ${uid}` : ""} webhook: ${webhook}`);
|
|
19289
20379
|
markBootReady();
|
|
20380
|
+
if (isUnderLauncher()) void refreshLauncherOnBoot(updateLayout(appPaths2.rootDir));
|
|
19290
20381
|
await parkWithShutdown(supervisor, appPaths2, uiServer, listenLock, port, (requestExit) => {
|
|
19291
20382
|
if (!isUnderLauncher() || !getAutoUpdateEnabled(cfg) || isAutoUpdateEnvDisabled()) return;
|
|
19292
20383
|
startAutoUpdateScheduler({
|
|
@@ -19298,17 +20389,34 @@ async function runStart(opts) {
|
|
|
19298
20389
|
log.info("self-update", "scheduler-started", { profile: appPaths2.profile });
|
|
19299
20390
|
});
|
|
19300
20391
|
}
|
|
20392
|
+
async function refreshLauncherOnBoot(layout) {
|
|
20393
|
+
let refreshed = false;
|
|
20394
|
+
try {
|
|
20395
|
+
refreshed = await ensureLauncherFresh(layout);
|
|
20396
|
+
} catch (err) {
|
|
20397
|
+
log.warn("self-update", "launcher-refresh-failed", { err: err instanceof Error ? err.message : String(err) });
|
|
20398
|
+
}
|
|
20399
|
+
const diagnostics = inspectLauncherCapabilities(layout.bootStateFile);
|
|
20400
|
+
if (diagnostics.missing.length === 0) return;
|
|
20401
|
+
log.warn("self-update", "launcher-capabilities-missing", {
|
|
20402
|
+
missing: diagnostics.missing,
|
|
20403
|
+
reported: diagnostics.reported,
|
|
20404
|
+
refreshed
|
|
20405
|
+
});
|
|
20406
|
+
const warning = formatLauncherCapabilityWarning(diagnostics, { refreshed });
|
|
20407
|
+
if (warning) console.warn(`${stdoutTsPrefix()}${warning}`);
|
|
20408
|
+
}
|
|
19301
20409
|
async function collectProfileLogDirs(rootDir) {
|
|
19302
20410
|
const dirs = [];
|
|
19303
20411
|
let profiles;
|
|
19304
20412
|
try {
|
|
19305
|
-
profiles = await
|
|
20413
|
+
profiles = await readdir14(join32(rootDir, "profiles"));
|
|
19306
20414
|
} catch {
|
|
19307
20415
|
return dirs;
|
|
19308
20416
|
}
|
|
19309
20417
|
for (const profile2 of profiles) {
|
|
19310
|
-
dirs.push(
|
|
19311
|
-
dirs.push(
|
|
20418
|
+
dirs.push(join32(rootDir, "profiles", profile2, "logs"));
|
|
20419
|
+
dirs.push(join32(rootDir, "profiles", profile2, "logs", "daemon"));
|
|
19312
20420
|
}
|
|
19313
20421
|
return dirs;
|
|
19314
20422
|
}
|
|
@@ -19401,7 +20509,7 @@ async function confirmStopRuntimeLockProcess(err) {
|
|
|
19401
20509
|
`\u5F53\u524D ${err.kind === "profile" ? "profile" : "app"} \u5DF2\u6709 bridge \u8FDB\u7A0B\u5360\u7528\uFF1B\u975E\u4EA4\u4E92\u6A21\u5F0F\u65E0\u6CD5\u786E\u8BA4\u505C\u6B62\uFF0C\u8BF7\u5148\u7528 \`xiaojiu-agent-bridge ps\` \u67E5\u770B\u5E76\u7528 \`xiaojiu-agent-bridge kill <bot id>\` \u505C\u6B62\u540E\u91CD\u8BD5`
|
|
19402
20510
|
);
|
|
19403
20511
|
}
|
|
19404
|
-
const rl =
|
|
20512
|
+
const rl = createInterface11({ input: process.stdin, output: process.stdout });
|
|
19405
20513
|
try {
|
|
19406
20514
|
const answer = (await new Promise(
|
|
19407
20515
|
(resolve5) => rl.question("\u662F\u5426\u505C\u6B62\u65E7\u8FDB\u7A0B\u5E76\u91CD\u65B0\u542F\u52A8? [y/N]: ", resolve5)
|
|
@@ -19462,15 +20570,62 @@ function openBrowser(url) {
|
|
|
19462
20570
|
}
|
|
19463
20571
|
}
|
|
19464
20572
|
|
|
20573
|
+
// src/cli/commands/doctor.ts
|
|
20574
|
+
import { existsSync as existsSync11 } from "fs";
|
|
20575
|
+
import { join as join33 } from "path";
|
|
20576
|
+
async function runDoctor(options = {}) {
|
|
20577
|
+
const log2 = options.log ?? ((message) => process.stdout.write(`${message}
|
|
20578
|
+
`));
|
|
20579
|
+
const rootDir = options.rootDir ?? paths.rootDir;
|
|
20580
|
+
const layout = updateLayout(rootDir);
|
|
20581
|
+
const running = resolveInstall({ rootDir, ...options.pkgDir ? { pkgDir: options.pkgDir } : {} });
|
|
20582
|
+
const diagnostics = inspectLauncherCapabilities(
|
|
20583
|
+
options.bootFile ?? layout.bootStateFile,
|
|
20584
|
+
options.required
|
|
20585
|
+
);
|
|
20586
|
+
const pointer = await readCurrent(layout);
|
|
20587
|
+
log2(`bootstrap (npm global): ${version}`);
|
|
20588
|
+
log2(`running (pointer): ${running.version}`);
|
|
20589
|
+
log2(`launcher capabilities: ${launcherCapabilitiesLine(diagnostics)}`);
|
|
20590
|
+
log2(`missing for running: ${diagnostics.missing.length > 0 ? diagnostics.missing.join(", ") : "(none)"}`);
|
|
20591
|
+
if (!pointer) {
|
|
20592
|
+
log2("pointer: absent (using the invoked package)");
|
|
20593
|
+
} else if (running.source === "checkout") {
|
|
20594
|
+
log2(`pointer: ignored (git checkout runs its own tree; pointer=${pointer.version})`);
|
|
20595
|
+
} else if (running.source === "pointer") {
|
|
20596
|
+
log2(`pointer: ok (${pointer.dir})`);
|
|
20597
|
+
} else {
|
|
20598
|
+
log2(`pointer: broken \u2192 falls back to bootstrap (${pointer.version} at ${pointer.dir})`);
|
|
20599
|
+
}
|
|
20600
|
+
const target = pointer ? packageDirOf(pointer.dir) : void 0;
|
|
20601
|
+
if (target && !existsSync11(join33(target, "package.json")) && running.source !== "checkout") {
|
|
20602
|
+
log2(" \u6307\u9488\u76EE\u6807\u7F3A\u5C11 package.json\uFF0Clauncher \u4F1A\u56DE\u9000\u5230\u81EA\u8EAB\u5B89\u88C5");
|
|
20603
|
+
}
|
|
20604
|
+
if (!diagnostics.reported) {
|
|
20605
|
+
log2(" launcher \u526F\u672C\u5C1A\u672A\u4E0A\u62A5\u80FD\u529B\uFF1B`xiaojiu-agent-bridge restart` \u540E\u5237\u65B0");
|
|
20606
|
+
}
|
|
20607
|
+
if (diagnostics.missing.length > 0) {
|
|
20608
|
+
const warning = formatLauncherCapabilityWarning(diagnostics, { refreshed: true });
|
|
20609
|
+
if (warning) log2(` ${warning}`);
|
|
20610
|
+
log2(` \u82E5\u91CD\u542F\u540E\u4ECD\u7F3A\u5931\uFF1A${manualLauncherUpdateCommand()}`);
|
|
20611
|
+
}
|
|
20612
|
+
if (running.source === "bootstrap" && pointer && pointer.version !== running.version) {
|
|
20613
|
+
log2(` \u6307\u9488 ${pointer.version} \u4E0D\u53EF\u542F\u52A8\uFF0C\u5F53\u524D\u5B9E\u9645\u8FD0\u884C bootstrap ${running.version}\uFF08${packageName}\uFF09`);
|
|
20614
|
+
}
|
|
20615
|
+
}
|
|
20616
|
+
|
|
19465
20617
|
// src/cli/index.ts
|
|
19466
20618
|
var program = new Command();
|
|
19467
|
-
program.name("xiaojiu-agent-bridge").description(`Bridge Xiaojiu IM with local CLI coding agents (${packageName})`).version(version, "-v, --version");
|
|
20619
|
+
program.name("xiaojiu-agent-bridge").description(`Bridge Xiaojiu IM with local CLI coding agents (${packageName})`).version(resolveInstall().version, "-v, --version");
|
|
19468
20620
|
program.command("update").description("Check npm for a newer version, show highlights, and install it").option("--check", "only print the available update; do not run npm install").action(async (opts) => {
|
|
19469
20621
|
await runUpdateCheck({ checkOnly: opts.check === true });
|
|
19470
20622
|
});
|
|
19471
20623
|
program.command("changelog [version]").description("Show release notes for the installed version").action(async (requestedVersion) => {
|
|
19472
20624
|
await runChangelog(requestedVersion);
|
|
19473
20625
|
});
|
|
20626
|
+
program.command("doctor").description("Show bootstrap, launcher, and running version state (read-only)").action(async () => {
|
|
20627
|
+
await runDoctor();
|
|
20628
|
+
});
|
|
19474
20629
|
program.command("run").description("Run the bridge in the foreground").option("-c, --config <path>", "path to config file").option("--profile <name>", "profile name to run").option("--web-ui", "open the local web console on this bot listen process").option("--agent <kind>", "agent kind for a new profile (claude, codex, pi, opencode, or omp)").option("--workspace <path>", "initial working directory for first-run profile bootstrap").option("--app-id <id>", "Xiaojiu App ID").option("--app-secret <secret>", "Xiaojiu App Secret; prefer interactive input on shared machines").option("--owner <staffNo>", "Bot Owner staff number (GZ + 4 digits, e.g. GZ1133)").option("-H, --host <host>", "Webhook listen host (default: 0.0.0.0)").option("-p, --port <port>", "Webhook listen port (default: 9699)", parsePort).option("--path-secret <secret>", "Webhook path secret; a random value is generated when omitted").option("--public-path <path>", "shared callback path for all profiles (routes by appId)", normalizeWebhookPath).action(async (opts) => {
|
|
19475
20630
|
await runStart(opts);
|
|
19476
20631
|
});
|