@saltpub/xiaojiu-agent-bridge 0.1.8 → 0.1.9
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 +16 -1
- package/README.md +167 -166
- package/dist/cli.js +1295 -305
- package/package.json +3 -3
package/dist/cli.js
CHANGED
|
@@ -656,7 +656,6 @@ import { homedir as homedir2 } from "os";
|
|
|
656
656
|
import { join as join4 } from "path";
|
|
657
657
|
import { createHash } from "crypto";
|
|
658
658
|
var SERVICE_NAME = "xiaojiu-agent-bridge.bot";
|
|
659
|
-
var SUPERVISOR_SERVICE_ID = "supervisor";
|
|
660
659
|
function serviceProfileId(profile2) {
|
|
661
660
|
const trimmed = profile2.trim();
|
|
662
661
|
if (!trimmed) throw new Error("profile name is required for service id");
|
|
@@ -1246,7 +1245,7 @@ function getServiceAdapter(profile2 = "claude", runArgs = ["run"], launch) {
|
|
|
1246
1245
|
}
|
|
1247
1246
|
|
|
1248
1247
|
// src/runtime/locks.ts
|
|
1249
|
-
import { chmod as chmod2, mkdir as mkdir5, readFile, unlink, writeFile as writeFile4 } from "fs/promises";
|
|
1248
|
+
import { chmod as chmod2, mkdir as mkdir5, readFile, rm as rm5, unlink, writeFile as writeFile4 } from "fs/promises";
|
|
1250
1249
|
import { dirname as dirname6 } from "path";
|
|
1251
1250
|
import * as lockfile from "proper-lockfile";
|
|
1252
1251
|
|
|
@@ -1680,6 +1679,24 @@ async function acquireProfileRuntimeLock(paths2, agentKind) {
|
|
|
1680
1679
|
function runtimeLockMetaFile(target) {
|
|
1681
1680
|
return `${target}.meta.json`;
|
|
1682
1681
|
}
|
|
1682
|
+
async function breakDeadRuntimeLock(target) {
|
|
1683
|
+
const meta = await readRuntimeLockMeta(target);
|
|
1684
|
+
if (!meta || pidAlive(meta.pid)) return false;
|
|
1685
|
+
await unlink(runtimeLockMetaFile(target)).catch(() => {
|
|
1686
|
+
});
|
|
1687
|
+
await rm5(`${target}.lock`, { recursive: true, force: true }).catch(() => {
|
|
1688
|
+
});
|
|
1689
|
+
return true;
|
|
1690
|
+
}
|
|
1691
|
+
function pidAlive(pid) {
|
|
1692
|
+
try {
|
|
1693
|
+
process.kill(pid, 0);
|
|
1694
|
+
return true;
|
|
1695
|
+
} catch (err) {
|
|
1696
|
+
const code = err.code;
|
|
1697
|
+
return code === "EPERM" || code === "EACCES";
|
|
1698
|
+
}
|
|
1699
|
+
}
|
|
1683
1700
|
async function readRuntimeLockMeta(target) {
|
|
1684
1701
|
try {
|
|
1685
1702
|
const parsed = JSON.parse(await readFile(runtimeLockMetaFile(target), "utf8"));
|
|
@@ -1817,7 +1834,8 @@ async function register(args) {
|
|
|
1817
1834
|
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1818
1835
|
version: args.version,
|
|
1819
1836
|
...typeof args.webhookPort === "number" ? { webhookPort: args.webhookPort } : {},
|
|
1820
|
-
...args.webhookPath ? { webhookPath: args.webhookPath } : {}
|
|
1837
|
+
...args.webhookPath ? { webhookPath: args.webhookPath } : {},
|
|
1838
|
+
...typeof args.launcherPid === "number" ? { launcherPid: args.launcherPid } : {}
|
|
1821
1839
|
};
|
|
1822
1840
|
await withRegistryFileLock(registryFile, async () => {
|
|
1823
1841
|
const { entries: live } = await readForWriteState(registryFile);
|
|
@@ -2005,13 +2023,13 @@ function fsyncDirSync(path4) {
|
|
|
2005
2023
|
|
|
2006
2024
|
// src/runtime/listen-sidecar.ts
|
|
2007
2025
|
import { createServer } from "net";
|
|
2008
|
-
import { mkdir as mkdir8, readdir as readdir2, readFile as readFile2, rm as
|
|
2026
|
+
import { mkdir as mkdir8, readdir as readdir2, readFile as readFile2, rm as rm8 } from "fs/promises";
|
|
2009
2027
|
import { dirname as dirname9, join as join7 } from "path";
|
|
2010
2028
|
|
|
2011
2029
|
// src/core/logger.ts
|
|
2012
2030
|
import { AsyncLocalStorage } from "async_hooks";
|
|
2013
2031
|
import { createWriteStream, mkdirSync as mkdirSync2 } from "fs";
|
|
2014
|
-
import { readdir, rename, rm as
|
|
2032
|
+
import { readdir, rename, rm as rm6, stat } from "fs/promises";
|
|
2015
2033
|
import { join as join6 } from "path";
|
|
2016
2034
|
|
|
2017
2035
|
// src/core/telemetry.ts
|
|
@@ -2587,7 +2605,7 @@ async function gcOldLogs(extraDirs = []) {
|
|
|
2587
2605
|
const fileMs = Date.parse(`${m[1]}-${m[2]}-${m[3]}T00:00:00Z`);
|
|
2588
2606
|
if (Number.isNaN(fileMs) || fileMs >= cutoff) continue;
|
|
2589
2607
|
try {
|
|
2590
|
-
await
|
|
2608
|
+
await rm6(join6(dir, name));
|
|
2591
2609
|
removed++;
|
|
2592
2610
|
} catch {
|
|
2593
2611
|
}
|
|
@@ -2610,7 +2628,7 @@ async function rotateIfOversized(path4) {
|
|
|
2610
2628
|
}
|
|
2611
2629
|
if (st.size <= DAEMON_LOG_MAX_BYTES) return;
|
|
2612
2630
|
const oldPath = `${path4}.old`;
|
|
2613
|
-
await
|
|
2631
|
+
await rm6(oldPath, { force: true }).catch(() => void 0);
|
|
2614
2632
|
await rename(path4, oldPath);
|
|
2615
2633
|
log.info("logger", "daemon-log-rotated", { rotatedBytes: st.size });
|
|
2616
2634
|
}
|
|
@@ -2655,7 +2673,7 @@ function sanitizeTelemetryError(err) {
|
|
|
2655
2673
|
}
|
|
2656
2674
|
|
|
2657
2675
|
// src/runtime/host-lock.ts
|
|
2658
|
-
import { mkdir as mkdir7, rm as
|
|
2676
|
+
import { mkdir as mkdir7, rm as rm7, writeFile as writeFile6 } from "fs/promises";
|
|
2659
2677
|
import { dirname as dirname8 } from "path";
|
|
2660
2678
|
import * as lockfile3 from "proper-lockfile";
|
|
2661
2679
|
async function acquireHostLock(target) {
|
|
@@ -2676,7 +2694,7 @@ async function acquireHostLock(target) {
|
|
|
2676
2694
|
}
|
|
2677
2695
|
async function forceReleaseHostLock(target) {
|
|
2678
2696
|
await lockfile3.unlock(target, { realpath: false }).catch(() => void 0);
|
|
2679
|
-
await
|
|
2697
|
+
await rm7(`${target}.lock`, { recursive: true, force: true }).catch(() => void 0);
|
|
2680
2698
|
}
|
|
2681
2699
|
|
|
2682
2700
|
// src/runtime/listen-sidecar.ts
|
|
@@ -2703,7 +2721,7 @@ async function readListenSidecar(file) {
|
|
|
2703
2721
|
}
|
|
2704
2722
|
}
|
|
2705
2723
|
async function removeListenSidecar(file) {
|
|
2706
|
-
await
|
|
2724
|
+
await rm8(file, { force: true }).catch(
|
|
2707
2725
|
(err) => log.warn("listen", "sidecar-remove-failed", { err: String(err) })
|
|
2708
2726
|
);
|
|
2709
2727
|
}
|
|
@@ -2783,7 +2801,7 @@ async function waitForListenOwner(port, host, rootDir, graceMs) {
|
|
|
2783
2801
|
}
|
|
2784
2802
|
|
|
2785
2803
|
// src/ui/sidecar.ts
|
|
2786
|
-
import { readFile as readFile3, rm as
|
|
2804
|
+
import { readFile as readFile3, rm as rm9 } from "fs/promises";
|
|
2787
2805
|
import { dirname as dirname10 } from "path";
|
|
2788
2806
|
import { mkdir as mkdir9 } from "fs/promises";
|
|
2789
2807
|
async function writeUiSidecar(uiFile, handle2, startedAt) {
|
|
@@ -2808,7 +2826,7 @@ async function readUiSidecar(uiFile) {
|
|
|
2808
2826
|
}
|
|
2809
2827
|
}
|
|
2810
2828
|
async function removeUiSidecar(uiFile) {
|
|
2811
|
-
await
|
|
2829
|
+
await rm9(uiFile, { force: true }).catch(
|
|
2812
2830
|
(err) => log.warn("ui", "sidecar-remove-failed", { err: String(err) })
|
|
2813
2831
|
);
|
|
2814
2832
|
}
|
|
@@ -3150,12 +3168,12 @@ function stringList(value) {
|
|
|
3150
3168
|
}
|
|
3151
3169
|
|
|
3152
3170
|
// src/selfupdate/stage.ts
|
|
3153
|
-
import { mkdir as mkdir11, mkdtemp, open as open2, readFile as readFile6, rm as
|
|
3171
|
+
import { mkdir as mkdir11, mkdtemp, open as open2, readFile as readFile6, rm as rm11 } from "fs/promises";
|
|
3154
3172
|
import { tmpdir } from "os";
|
|
3155
3173
|
import { join as join9 } from "path";
|
|
3156
3174
|
|
|
3157
3175
|
// src/selfupdate/store.ts
|
|
3158
|
-
import { mkdir as mkdir10, readdir as readdir4, readFile as readFile5, rm as
|
|
3176
|
+
import { mkdir as mkdir10, readdir as readdir4, readFile as readFile5, rm as rm10 } from "fs/promises";
|
|
3159
3177
|
import { dirname as dirname11, join as join8 } from "path";
|
|
3160
3178
|
function updateLayout(rootDir) {
|
|
3161
3179
|
return {
|
|
@@ -3224,7 +3242,7 @@ async function gcVersions(layout, keep = 3) {
|
|
|
3224
3242
|
const dir = join8(layout.versionsDir, name);
|
|
3225
3243
|
if (!/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(name)) {
|
|
3226
3244
|
if (!protectedDirs.has(dir)) {
|
|
3227
|
-
await
|
|
3245
|
+
await rm10(dir, { recursive: true, force: true, maxRetries: 5 });
|
|
3228
3246
|
removed.push(dir);
|
|
3229
3247
|
}
|
|
3230
3248
|
continue;
|
|
@@ -3233,7 +3251,7 @@ async function gcVersions(layout, keep = 3) {
|
|
|
3233
3251
|
}
|
|
3234
3252
|
const dirs = valid.sort((a, b) => compareVersions(a.name, b.name)).reverse().map((entry) => entry.dir);
|
|
3235
3253
|
for (const dir of dirs.slice(Math.max(keep - protectedDirs.size, 0))) {
|
|
3236
|
-
await
|
|
3254
|
+
await rm10(dir, { recursive: true, force: true, maxRetries: 5 });
|
|
3237
3255
|
removed.push(dir);
|
|
3238
3256
|
}
|
|
3239
3257
|
return removed;
|
|
@@ -3263,7 +3281,7 @@ async function stageVersion(deps) {
|
|
|
3263
3281
|
log2("stage.reuse", { version: targetVersion, dir });
|
|
3264
3282
|
return { ok: true, dir, reused: true };
|
|
3265
3283
|
}
|
|
3266
|
-
await
|
|
3284
|
+
await rm11(dir, { recursive: true, force: true, maxRetries: 5 });
|
|
3267
3285
|
const registryArgs = [`--registry=${REGISTRY_URL}`];
|
|
3268
3286
|
if (name.startsWith("@")) registryArgs.push(`--${name.split("/")[0]}:registry=${REGISTRY_URL}`);
|
|
3269
3287
|
const result = await (deps.runNpm ?? runNpm)([
|
|
@@ -3277,17 +3295,17 @@ async function stageVersion(deps) {
|
|
|
3277
3295
|
...registryArgs
|
|
3278
3296
|
]);
|
|
3279
3297
|
if (result.code !== 0) {
|
|
3280
|
-
await
|
|
3298
|
+
await rm11(dir, { recursive: true, force: true, maxRetries: 5 });
|
|
3281
3299
|
return { ok: false, error: `npm install failed (${result.code}): ${(result.stderr ?? "").trim().slice(0, 300)}` };
|
|
3282
3300
|
}
|
|
3283
3301
|
if (!await installedVersionMatches(pkgDir, targetVersion)) {
|
|
3284
|
-
await
|
|
3302
|
+
await rm11(dir, { recursive: true, force: true, maxRetries: 5 });
|
|
3285
3303
|
return { ok: false, error: `staged package.json does not report ${targetVersion}` };
|
|
3286
3304
|
}
|
|
3287
3305
|
try {
|
|
3288
3306
|
await (deps.runSmoke ?? smokeTest)(pkgDir, targetVersion);
|
|
3289
3307
|
} catch (err) {
|
|
3290
|
-
await
|
|
3308
|
+
await rm11(dir, { recursive: true, force: true, maxRetries: 5 });
|
|
3291
3309
|
return { ok: false, error: `smoke test failed: ${err instanceof Error ? err.message : String(err)}` };
|
|
3292
3310
|
}
|
|
3293
3311
|
log2("stage.installed", { version: targetVersion, dir });
|
|
@@ -3314,7 +3332,7 @@ async function acquireStageLock(layout) {
|
|
|
3314
3332
|
await handle2.writeFile(JSON.stringify({ pid: process.pid, at: (/* @__PURE__ */ new Date()).toISOString() }));
|
|
3315
3333
|
await handle2.close();
|
|
3316
3334
|
return async () => {
|
|
3317
|
-
await
|
|
3335
|
+
await rm11(layout.stageLockFile, { force: true });
|
|
3318
3336
|
};
|
|
3319
3337
|
} catch (err) {
|
|
3320
3338
|
if (err.code !== "EEXIST") throw err;
|
|
@@ -3324,7 +3342,7 @@ async function acquireStageLock(layout) {
|
|
|
3324
3342
|
return !Number.isFinite(at) || Date.now() - at > STAGE_LOCK_STALE_MS;
|
|
3325
3343
|
}).catch(() => true);
|
|
3326
3344
|
if (!stale) return void 0;
|
|
3327
|
-
await
|
|
3345
|
+
await rm11(layout.stageLockFile, { force: true });
|
|
3328
3346
|
}
|
|
3329
3347
|
}
|
|
3330
3348
|
return void 0;
|
|
@@ -3376,7 +3394,7 @@ async function smokeTest(pkgDir, expectedVersion) {
|
|
|
3376
3394
|
});
|
|
3377
3395
|
});
|
|
3378
3396
|
} finally {
|
|
3379
|
-
await
|
|
3397
|
+
await rm11(fakeHome, { recursive: true, force: true, maxRetries: 5 });
|
|
3380
3398
|
}
|
|
3381
3399
|
}
|
|
3382
3400
|
|
|
@@ -3620,75 +3638,6 @@ async function writeState(state) {
|
|
|
3620
3638
|
}
|
|
3621
3639
|
}
|
|
3622
3640
|
|
|
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
3641
|
// src/cli/commands/ps.ts
|
|
3693
3642
|
function runPs() {
|
|
3694
3643
|
const live = readAndPrune().filter((entry) => isAlive(entry.pid));
|
|
@@ -3712,99 +3661,6 @@ function runPs() {
|
|
|
3712
3661
|
const headers = { idx: "#", uid: "uid", pid: "\u8FDB\u7A0B", webhook: "webhook", online: "\u5728\u7EBF" };
|
|
3713
3662
|
printTable([headers, ...rows]);
|
|
3714
3663
|
}
|
|
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
3664
|
async function stopProcessEntry(entry, timeoutMs = 2e3) {
|
|
3809
3665
|
process.kill(entry.pid, "SIGTERM");
|
|
3810
3666
|
const deadline = Date.now() + timeoutMs;
|
|
@@ -3951,7 +3807,7 @@ async function listSecretIds(storePaths = paths) {
|
|
|
3951
3807
|
}
|
|
3952
3808
|
|
|
3953
3809
|
// src/config/profile-store.ts
|
|
3954
|
-
import { chmod as chmod3, mkdir as mkdir12, readFile as readFile9, rename as rename2, rm as
|
|
3810
|
+
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";
|
|
3955
3811
|
import { dirname as dirname12, join as join10 } from "path";
|
|
3956
3812
|
import * as lockfile4 from "proper-lockfile";
|
|
3957
3813
|
async function loadRootConfig(path4) {
|
|
@@ -4146,7 +4002,7 @@ async function removeProfile(root, profile2, rootDir, opts = {}) {
|
|
|
4146
4002
|
await rename2(stagedTo, profileDir);
|
|
4147
4003
|
},
|
|
4148
4004
|
cleanup: async () => {
|
|
4149
|
-
await
|
|
4005
|
+
await rm12(stagedTo, { recursive: true, force: true });
|
|
4150
4006
|
await rmdir(trashDir2).catch(() => {
|
|
4151
4007
|
});
|
|
4152
4008
|
}
|
|
@@ -4246,9 +4102,9 @@ async function isLogOnlyProfileState(rootDir, profile2) {
|
|
|
4246
4102
|
return false;
|
|
4247
4103
|
}
|
|
4248
4104
|
}
|
|
4249
|
-
function profileSort(a, b,
|
|
4250
|
-
if (a ===
|
|
4251
|
-
if (b ===
|
|
4105
|
+
function profileSort(a, b, active3) {
|
|
4106
|
+
if (a === active3) return -1;
|
|
4107
|
+
if (b === active3) return 1;
|
|
4252
4108
|
return a.localeCompare(b);
|
|
4253
4109
|
}
|
|
4254
4110
|
|
|
@@ -4288,12 +4144,12 @@ async function runSecretsGet() {
|
|
|
4288
4144
|
console.error(`secrets get: invalid stdin JSON: ${err.message}`);
|
|
4289
4145
|
process.exit(2);
|
|
4290
4146
|
}
|
|
4291
|
-
const
|
|
4147
|
+
const ids2 = req.ids ?? [];
|
|
4292
4148
|
const resp = {
|
|
4293
4149
|
protocolVersion: PROTOCOL_VERSION,
|
|
4294
4150
|
values: {}
|
|
4295
4151
|
};
|
|
4296
|
-
for (const id of
|
|
4152
|
+
for (const id of ids2) {
|
|
4297
4153
|
try {
|
|
4298
4154
|
const v = await resolveSecretAcrossProfiles(id);
|
|
4299
4155
|
if (v !== void 0) {
|
|
@@ -4323,14 +4179,14 @@ async function runSecretsSet(appId, opts = {}) {
|
|
|
4323
4179
|
}
|
|
4324
4180
|
async function runSecretsList(opts = {}) {
|
|
4325
4181
|
const appPaths2 = await resolveSecretProfilePaths(opts);
|
|
4326
|
-
const
|
|
4327
|
-
if (
|
|
4182
|
+
const ids2 = await listSecretIds(appPaths2);
|
|
4183
|
+
if (ids2.length === 0) {
|
|
4328
4184
|
console.log("\u5F53\u524D\u6CA1\u6709\u52A0\u5BC6\u5B58\u50A8\u7684 secret\u3002");
|
|
4329
4185
|
return;
|
|
4330
4186
|
}
|
|
4331
|
-
console.log(`# \u5F53\u524D\u5171 ${
|
|
4187
|
+
console.log(`# \u5F53\u524D\u5171 ${ids2.length} \u4E2A secret \u5728\u52A0\u5BC6\u5B58\u50A8\u91CC
|
|
4332
4188
|
`);
|
|
4333
|
-
for (const id of
|
|
4189
|
+
for (const id of ids2) {
|
|
4334
4190
|
console.log(` - ${id}`);
|
|
4335
4191
|
}
|
|
4336
4192
|
}
|
|
@@ -4350,16 +4206,16 @@ async function runSecretsRemove(appId, opts = {}) {
|
|
|
4350
4206
|
async function resolveSecretAcrossProfiles(id, rootDir = paths.rootDir, warn = (message) => console.error(message), profile2 = process.env.XIAOJIU_BRIDGE_PROFILE) {
|
|
4351
4207
|
if (profile2) {
|
|
4352
4208
|
const appPaths2 = resolveAppPaths({ rootDir, profile: profile2 });
|
|
4353
|
-
const
|
|
4354
|
-
if (!
|
|
4209
|
+
const ids2 = await listSecretIds(appPaths2);
|
|
4210
|
+
if (!ids2.includes(id)) return void 0;
|
|
4355
4211
|
return getSecret(id, appPaths2);
|
|
4356
4212
|
}
|
|
4357
4213
|
const profiles = await listSecretProfiles(rootDir);
|
|
4358
4214
|
const matches = [];
|
|
4359
4215
|
for (const profile3 of profiles) {
|
|
4360
4216
|
const appPaths2 = resolveAppPaths({ rootDir, profile: profile3.name });
|
|
4361
|
-
const
|
|
4362
|
-
if (
|
|
4217
|
+
const ids2 = await listSecretIds(appPaths2);
|
|
4218
|
+
if (ids2.includes(id)) matches.push(appPaths2);
|
|
4363
4219
|
}
|
|
4364
4220
|
if (matches.length === 0) return void 0;
|
|
4365
4221
|
if (matches.length > 1) {
|
|
@@ -4410,7 +4266,7 @@ async function readAllStdin() {
|
|
|
4410
4266
|
|
|
4411
4267
|
// src/cli/commands/profile.ts
|
|
4412
4268
|
import { existsSync as existsSync8 } from "fs";
|
|
4413
|
-
import { rm as
|
|
4269
|
+
import { rm as rm13 } from "fs/promises";
|
|
4414
4270
|
|
|
4415
4271
|
// src/config/secret-resolver.ts
|
|
4416
4272
|
import { readFile as readFile10 } from "fs/promises";
|
|
@@ -6300,8 +6156,11 @@ async function runProfileRemove(name, opts = {}) {
|
|
|
6300
6156
|
const profilePaths = resolveAppPaths({ rootDir, profile: name });
|
|
6301
6157
|
const profileLock = await checkRuntimeLock(profilePaths.profileLockFile);
|
|
6302
6158
|
if (profileLock.locked) {
|
|
6303
|
-
const
|
|
6304
|
-
|
|
6159
|
+
const broken = await breakDeadRuntimeLock(profilePaths.profileLockFile);
|
|
6160
|
+
if (!broken) {
|
|
6161
|
+
const holder = profileLock.meta ? ` pid=${profileLock.meta.pid} startedAt=${profileLock.meta.startedAt}` : "";
|
|
6162
|
+
throw new Error(`profile is locked/running: ${name}${holder}`);
|
|
6163
|
+
}
|
|
6305
6164
|
}
|
|
6306
6165
|
const lock6 = await acquireProfileRuntimeLock(profilePaths, profile2.agentKind);
|
|
6307
6166
|
try {
|
|
@@ -6311,8 +6170,8 @@ async function runProfileRemove(name, opts = {}) {
|
|
|
6311
6170
|
});
|
|
6312
6171
|
try {
|
|
6313
6172
|
if (Object.keys(result.root.profiles).length === 0) {
|
|
6314
|
-
await
|
|
6315
|
-
await
|
|
6173
|
+
await rm13(configFile, { force: true });
|
|
6174
|
+
await rm13(resolveAppPaths({ rootDir }).activeProfileFile, { force: true });
|
|
6316
6175
|
} else {
|
|
6317
6176
|
await saveRootConfig(result.root, configFile);
|
|
6318
6177
|
await writeActiveProfile(rootDir, result.root.activeProfile);
|
|
@@ -6403,6 +6262,19 @@ var ENV_BOOT_FILE = "XIAOJIU_BRIDGE_BOOT_FILE";
|
|
|
6403
6262
|
function isUnderLauncher(env = process.env) {
|
|
6404
6263
|
return env[ENV_LAUNCHER] === "1";
|
|
6405
6264
|
}
|
|
6265
|
+
function launcherPidFromEnv(env = process.env) {
|
|
6266
|
+
if (env[ENV_LAUNCHER] !== "1") return void 0;
|
|
6267
|
+
const file = env[ENV_BOOT_FILE];
|
|
6268
|
+
if (!file) return void 0;
|
|
6269
|
+
try {
|
|
6270
|
+
const parsed = JSON.parse(readFileSync3(file, "utf8"));
|
|
6271
|
+
if (typeof parsed !== "object" || parsed === null || !("pid" in parsed)) return void 0;
|
|
6272
|
+
const pid = parsed.pid;
|
|
6273
|
+
return typeof pid === "number" && pid !== process.pid ? pid : void 0;
|
|
6274
|
+
} catch {
|
|
6275
|
+
return void 0;
|
|
6276
|
+
}
|
|
6277
|
+
}
|
|
6406
6278
|
function markBootReady(env = process.env) {
|
|
6407
6279
|
const file = env[ENV_BOOT_FILE];
|
|
6408
6280
|
if (!file) return;
|
|
@@ -6445,6 +6317,75 @@ function defaultBundledLauncher() {
|
|
|
6445
6317
|
return fileURLToPath3(new URL("./launcher.js", import.meta.url));
|
|
6446
6318
|
}
|
|
6447
6319
|
|
|
6320
|
+
// src/cli/commands/listen-client.ts
|
|
6321
|
+
var ListenApiError = class extends Error {
|
|
6322
|
+
constructor(message, status) {
|
|
6323
|
+
super(message);
|
|
6324
|
+
this.status = status;
|
|
6325
|
+
}
|
|
6326
|
+
status;
|
|
6327
|
+
};
|
|
6328
|
+
function apiUrl(sidecar, path4) {
|
|
6329
|
+
const url = new URL(sidecar.url);
|
|
6330
|
+
url.pathname = path4;
|
|
6331
|
+
url.search = "";
|
|
6332
|
+
url.searchParams.set("token", sidecar.token);
|
|
6333
|
+
return url.toString();
|
|
6334
|
+
}
|
|
6335
|
+
function errorMessage(parsed, fallback) {
|
|
6336
|
+
if (parsed && typeof parsed === "object" && "error" in parsed) {
|
|
6337
|
+
const error = parsed.error;
|
|
6338
|
+
if (typeof error === "string" && error.trim()) return error;
|
|
6339
|
+
}
|
|
6340
|
+
return fallback;
|
|
6341
|
+
}
|
|
6342
|
+
async function postJson(sidecar, path4, body) {
|
|
6343
|
+
const response = await fetch(apiUrl(sidecar, path4), {
|
|
6344
|
+
method: "POST",
|
|
6345
|
+
headers: {
|
|
6346
|
+
"content-type": "application/json",
|
|
6347
|
+
"x-ui-token": sidecar.token
|
|
6348
|
+
},
|
|
6349
|
+
body: JSON.stringify(body)
|
|
6350
|
+
});
|
|
6351
|
+
const text2 = await response.text();
|
|
6352
|
+
let parsed = {};
|
|
6353
|
+
if (text2) {
|
|
6354
|
+
try {
|
|
6355
|
+
parsed = JSON.parse(text2);
|
|
6356
|
+
} catch {
|
|
6357
|
+
parsed = { error: text2 };
|
|
6358
|
+
}
|
|
6359
|
+
}
|
|
6360
|
+
if (!response.ok) {
|
|
6361
|
+
throw new ListenApiError(errorMessage(parsed, `HTTP ${response.status}`), response.status);
|
|
6362
|
+
}
|
|
6363
|
+
return parsed;
|
|
6364
|
+
}
|
|
6365
|
+
async function joinListenProfile(sidecar, profile2) {
|
|
6366
|
+
await postJson(sidecar, "/api/profiles/start", { profile: profile2 });
|
|
6367
|
+
}
|
|
6368
|
+
async function leaveListenProfile(sidecar, profile2) {
|
|
6369
|
+
await postJson(sidecar, "/api/profiles/stop", { profile: profile2 });
|
|
6370
|
+
}
|
|
6371
|
+
async function listListenBots(sidecar) {
|
|
6372
|
+
const response = await fetch(apiUrl(sidecar, "/api/bots"), {
|
|
6373
|
+
headers: { "x-ui-token": sidecar.token }
|
|
6374
|
+
});
|
|
6375
|
+
if (!response.ok) throw new ListenApiError(`HTTP ${response.status}`, response.status);
|
|
6376
|
+
const parsed = await response.json();
|
|
6377
|
+
if (!parsed || typeof parsed !== "object" || !("bots" in parsed) || !Array.isArray(parsed.bots)) {
|
|
6378
|
+
return [];
|
|
6379
|
+
}
|
|
6380
|
+
const names = [];
|
|
6381
|
+
for (const bot of parsed.bots) {
|
|
6382
|
+
if (bot && typeof bot === "object" && "profileName" in bot && typeof bot.profileName === "string") {
|
|
6383
|
+
names.push({ profileName: bot.profileName });
|
|
6384
|
+
}
|
|
6385
|
+
}
|
|
6386
|
+
return names;
|
|
6387
|
+
}
|
|
6388
|
+
|
|
6448
6389
|
// src/cli/commands/service.ts
|
|
6449
6390
|
function listenServiceId(port) {
|
|
6450
6391
|
return `port-${port}`;
|
|
@@ -6717,6 +6658,19 @@ async function runServiceStart(opts = {}) {
|
|
|
6717
6658
|
await adapter.install();
|
|
6718
6659
|
await reportReadyAfter("started", profile2, adapter.start, serviceId, port, opts.webUi);
|
|
6719
6660
|
}
|
|
6661
|
+
async function runKillCli(target) {
|
|
6662
|
+
if (!target) {
|
|
6663
|
+
console.error("\u7528\u6CD5: xiaojiu-agent-bridge kill <uid\u3001\u8FDB\u7A0B \u6216\u5E8F\u53F7>");
|
|
6664
|
+
process.exit(1);
|
|
6665
|
+
}
|
|
6666
|
+
const entry = resolveTarget(target);
|
|
6667
|
+
if (!entry) {
|
|
6668
|
+
console.error(`\u2717 \u6CA1\u627E\u5230\u5339\u914D\u7684 bot:${target}`);
|
|
6669
|
+
console.error(" \u7528 `xiaojiu-agent-bridge ps` \u770B\u53EF\u9009\u76EE\u6807\u3002");
|
|
6670
|
+
process.exit(1);
|
|
6671
|
+
}
|
|
6672
|
+
await runServiceStop({ profile: entry.profileName });
|
|
6673
|
+
}
|
|
6720
6674
|
async function runServiceStop(opts = {}) {
|
|
6721
6675
|
const { profile: profile2 } = await resolveServiceTarget(opts);
|
|
6722
6676
|
const runtime = await maybeResolveProfileRuntime(profile2);
|
|
@@ -6745,17 +6699,42 @@ async function runServiceStop(opts = {}) {
|
|
|
6745
6699
|
printStopped(profile2, entry, listen3.pid);
|
|
6746
6700
|
return;
|
|
6747
6701
|
}
|
|
6748
|
-
await
|
|
6702
|
+
await stopLauncherSupervisor(entry);
|
|
6703
|
+
await stopPidTolerant(listen3.pid);
|
|
6749
6704
|
await removeListenSidecar(listenSidecarFile(port, runtime?.appPaths.rootDir));
|
|
6750
6705
|
await forceReleaseHostLock(listenLockFile(port, runtime?.appPaths.rootDir));
|
|
6751
|
-
|
|
6752
|
-
if (adapter?.fileExists()) await adapter.stopAndDisableAutostart();
|
|
6706
|
+
await stopOwningServices(profile2, port);
|
|
6753
6707
|
printStopped(profile2, entry, listen3.pid);
|
|
6754
6708
|
return;
|
|
6755
6709
|
}
|
|
6756
|
-
if (entry)
|
|
6710
|
+
if (entry) {
|
|
6711
|
+
await stopLauncherSupervisor(entry);
|
|
6712
|
+
await stopProcessEntry(entry);
|
|
6713
|
+
}
|
|
6757
6714
|
printStopped(profile2, entry, entry?.pid);
|
|
6758
6715
|
}
|
|
6716
|
+
async function stopLauncherSupervisor(entry) {
|
|
6717
|
+
const launcherPid = entry?.launcherPid;
|
|
6718
|
+
if (typeof launcherPid !== "number" || !isAlive(launcherPid)) return;
|
|
6719
|
+
try {
|
|
6720
|
+
await stopPidTolerant(launcherPid);
|
|
6721
|
+
} catch (err) {
|
|
6722
|
+
log.warn("service", "launcher-stop-failed", { pid: launcherPid, err: String(err) });
|
|
6723
|
+
}
|
|
6724
|
+
}
|
|
6725
|
+
async function stopPidTolerant(pid) {
|
|
6726
|
+
try {
|
|
6727
|
+
await stopProcessEntry({ pid });
|
|
6728
|
+
} catch (err) {
|
|
6729
|
+
if (err.code !== "ESRCH") throw err;
|
|
6730
|
+
}
|
|
6731
|
+
}
|
|
6732
|
+
async function stopOwningServices(profile2, port) {
|
|
6733
|
+
for (const serviceId of /* @__PURE__ */ new Set([listenServiceId(port), profile2])) {
|
|
6734
|
+
const adapter = getServiceAdapter(serviceId);
|
|
6735
|
+
if (adapter?.fileExists()) await adapter.stopAndDisableAutostart();
|
|
6736
|
+
}
|
|
6737
|
+
}
|
|
6759
6738
|
async function runServiceRestart(opts = {}) {
|
|
6760
6739
|
await runServiceStop(opts);
|
|
6761
6740
|
await runServiceStart(opts);
|
|
@@ -6858,15 +6837,15 @@ function agentDisplay(agentKind) {
|
|
|
6858
6837
|
// src/cli/commands/start.ts
|
|
6859
6838
|
import dns from "dns";
|
|
6860
6839
|
import os from "os";
|
|
6861
|
-
import { readdir as
|
|
6862
|
-
import { join as
|
|
6863
|
-
import { createInterface as
|
|
6840
|
+
import { readdir as readdir14 } from "fs/promises";
|
|
6841
|
+
import { join as join31 } from "path";
|
|
6842
|
+
import { createInterface as createInterface11 } from "readline";
|
|
6864
6843
|
|
|
6865
6844
|
// src/agent/claude/adapter.ts
|
|
6866
6845
|
import { mkdtempSync, rmSync, writeFileSync as writeFileSync3 } from "fs";
|
|
6867
6846
|
import { tmpdir as tmpdir3 } from "os";
|
|
6868
|
-
import { join as
|
|
6869
|
-
import { createInterface as
|
|
6847
|
+
import { join as join17 } from "path";
|
|
6848
|
+
import { createInterface as createInterface4 } from "readline";
|
|
6870
6849
|
|
|
6871
6850
|
// src/agent/system-prompt.ts
|
|
6872
6851
|
import { createHash as createHash2 } from "crypto";
|
|
@@ -6956,17 +6935,210 @@ function hiddenSystemPromptFingerprint(identity, overlay = {}) {
|
|
|
6956
6935
|
// src/agent/types.ts
|
|
6957
6936
|
var CLAUDE_DEFAULT_PERMISSION_MODE = "bypassPermissions";
|
|
6958
6937
|
|
|
6959
|
-
// src/agent/
|
|
6938
|
+
// src/agent/claude/side-query.ts
|
|
6939
|
+
import { readdir as readdir7, rm as rm14 } from "fs/promises";
|
|
6940
|
+
import { homedir as homedir5 } from "os";
|
|
6941
|
+
import { join as join16 } from "path";
|
|
6942
|
+
|
|
6943
|
+
// src/agent/btw-prompt.ts
|
|
6944
|
+
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";
|
|
6945
|
+
function buildBtwPrompt(question) {
|
|
6946
|
+
const body = question.trim() || BTW_DEFAULT_QUESTION;
|
|
6947
|
+
return [
|
|
6948
|
+
"<btw>",
|
|
6949
|
+
"Ephemeral side question for current session.",
|
|
6950
|
+
"Answer briefly, directly; use conversation context already provided.",
|
|
6951
|
+
"NEVER use tools.",
|
|
6952
|
+
"NEVER ask follow-up questions.",
|
|
6953
|
+
"Question:",
|
|
6954
|
+
body,
|
|
6955
|
+
"</btw>"
|
|
6956
|
+
].join("\n");
|
|
6957
|
+
}
|
|
6958
|
+
|
|
6959
|
+
// src/agent/jsonl-side-query.ts
|
|
6960
6960
|
import { createInterface as createInterface2 } from "readline";
|
|
6961
|
+
|
|
6962
|
+
// src/core/deferred.ts
|
|
6963
|
+
function deferred() {
|
|
6964
|
+
let resolve5 = () => {
|
|
6965
|
+
};
|
|
6966
|
+
const promise = new Promise((r) => {
|
|
6967
|
+
resolve5 = r;
|
|
6968
|
+
});
|
|
6969
|
+
return { promise, resolve: resolve5 };
|
|
6970
|
+
}
|
|
6971
|
+
|
|
6972
|
+
// src/agent/jsonl-side-query.ts
|
|
6973
|
+
var TEXT_MAX = 8e3;
|
|
6974
|
+
var STDERR_MAX = 16384;
|
|
6975
|
+
async function runJsonlSideQuery(spec) {
|
|
6976
|
+
const child = spawnProcess(spec.binary, spec.args, {
|
|
6977
|
+
cwd: spec.cwd,
|
|
6978
|
+
env: spec.env ? mergeProcessEnv(process.env, spec.env) : process.env,
|
|
6979
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
6980
|
+
detached: process.platform !== "win32"
|
|
6981
|
+
});
|
|
6982
|
+
const stderr = [];
|
|
6983
|
+
let stderrBytes = 0;
|
|
6984
|
+
child.stderr.on("data", (chunk) => {
|
|
6985
|
+
if (stderrBytes >= STDERR_MAX) return;
|
|
6986
|
+
stderrBytes += chunk.length;
|
|
6987
|
+
stderr.push(chunk);
|
|
6988
|
+
});
|
|
6989
|
+
let spawnError;
|
|
6990
|
+
child.once("error", (err) => {
|
|
6991
|
+
spawnError = err instanceof Error ? err : new Error(String(err));
|
|
6992
|
+
});
|
|
6993
|
+
let aborted = false;
|
|
6994
|
+
const onAbort = () => {
|
|
6995
|
+
aborted = true;
|
|
6996
|
+
killProcessTree(child, true);
|
|
6997
|
+
};
|
|
6998
|
+
spec.signal.addEventListener("abort", onAbort, { once: true });
|
|
6999
|
+
if (spec.signal.aborted) onAbort();
|
|
7000
|
+
let streamed = "";
|
|
7001
|
+
let finalText = "";
|
|
7002
|
+
let sessionId;
|
|
7003
|
+
let threadId;
|
|
7004
|
+
let failure;
|
|
7005
|
+
child.stdin.on("error", () => {
|
|
7006
|
+
});
|
|
7007
|
+
child.stdin.end(spec.prompt, "utf8");
|
|
7008
|
+
try {
|
|
7009
|
+
if (child.pid) {
|
|
7010
|
+
const rl = createInterface2({ input: child.stdout, crlfDelay: Infinity });
|
|
7011
|
+
try {
|
|
7012
|
+
for await (const line of rl) {
|
|
7013
|
+
const trimmed = line.trim();
|
|
7014
|
+
if (!trimmed) continue;
|
|
7015
|
+
let raw;
|
|
7016
|
+
try {
|
|
7017
|
+
raw = JSON.parse(trimmed);
|
|
7018
|
+
} catch {
|
|
7019
|
+
continue;
|
|
7020
|
+
}
|
|
7021
|
+
for (const evt of spec.translate(raw)) {
|
|
7022
|
+
if (evt.type === "system") {
|
|
7023
|
+
sessionId ??= evt.sessionId;
|
|
7024
|
+
threadId ??= evt.threadId;
|
|
7025
|
+
} else if (evt.type === "text") {
|
|
7026
|
+
if (streamed.length < TEXT_MAX) streamed += evt.delta;
|
|
7027
|
+
} else if (evt.type === "final_text") {
|
|
7028
|
+
finalText = evt.content;
|
|
7029
|
+
} else if (evt.type === "error") {
|
|
7030
|
+
failure = evt.message;
|
|
7031
|
+
}
|
|
7032
|
+
}
|
|
7033
|
+
}
|
|
7034
|
+
} finally {
|
|
7035
|
+
rl.close();
|
|
7036
|
+
}
|
|
7037
|
+
}
|
|
7038
|
+
} catch (err) {
|
|
7039
|
+
failure ??= err instanceof Error ? err.message : String(err);
|
|
7040
|
+
} finally {
|
|
7041
|
+
spec.signal.removeEventListener("abort", onAbort);
|
|
7042
|
+
await waitForChildExit(child, 2e3);
|
|
7043
|
+
if (child.exitCode === null && child.signalCode === null) killProcessTree(child, true);
|
|
7044
|
+
}
|
|
7045
|
+
const text2 = (finalText || streamed).trim().slice(0, TEXT_MAX);
|
|
7046
|
+
const result = { text: text2 };
|
|
7047
|
+
if (sessionId) result.sessionId = sessionId;
|
|
7048
|
+
if (threadId) result.threadId = threadId;
|
|
7049
|
+
if (aborted) {
|
|
7050
|
+
result.error = "aborted";
|
|
7051
|
+
return result;
|
|
7052
|
+
}
|
|
7053
|
+
if (spawnError) {
|
|
7054
|
+
result.error = `failed to spawn ${spec.agent}: ${spawnError.message}`;
|
|
7055
|
+
return result;
|
|
7056
|
+
}
|
|
7057
|
+
if (failure && !text2) {
|
|
7058
|
+
result.error = failure;
|
|
7059
|
+
return result;
|
|
7060
|
+
}
|
|
7061
|
+
if (!text2) {
|
|
7062
|
+
const detail = Buffer.concat(stderr).toString("utf8").trim().replace(/\s+/g, " ").slice(0, 300);
|
|
7063
|
+
result.error = detail || `${spec.agent} \u6CA1\u6709\u8FD4\u56DE\u7B54\u6848`;
|
|
7064
|
+
}
|
|
7065
|
+
return result;
|
|
7066
|
+
}
|
|
7067
|
+
function waitForChildExit(child, timeoutMs) {
|
|
7068
|
+
if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve(true);
|
|
7069
|
+
const { promise, resolve: resolve5 } = deferred();
|
|
7070
|
+
let settled = false;
|
|
7071
|
+
const finish = (exited) => {
|
|
7072
|
+
if (settled) return;
|
|
7073
|
+
settled = true;
|
|
7074
|
+
clearTimeout(timer);
|
|
7075
|
+
resolve5(exited);
|
|
7076
|
+
};
|
|
7077
|
+
const timer = setTimeout(() => finish(false), timeoutMs);
|
|
7078
|
+
child.once("exit", () => finish(true));
|
|
7079
|
+
return promise;
|
|
7080
|
+
}
|
|
7081
|
+
|
|
7082
|
+
// src/session/btw-sessions.ts
|
|
7083
|
+
var ids = /* @__PURE__ */ new Map();
|
|
7084
|
+
function markBtwSession(agentKind, sessionId) {
|
|
7085
|
+
let set = ids.get(agentKind);
|
|
7086
|
+
if (!set) {
|
|
7087
|
+
set = /* @__PURE__ */ new Set();
|
|
7088
|
+
ids.set(agentKind, set);
|
|
7089
|
+
}
|
|
7090
|
+
set.add(sessionId);
|
|
7091
|
+
if (set.size > 200) {
|
|
7092
|
+
const oldest = set.values().next().value;
|
|
7093
|
+
if (oldest !== void 0) set.delete(oldest);
|
|
7094
|
+
}
|
|
7095
|
+
}
|
|
7096
|
+
function isBtwSession(agentKind, sessionId) {
|
|
7097
|
+
return ids.get(agentKind)?.has(sessionId) ?? false;
|
|
7098
|
+
}
|
|
7099
|
+
|
|
7100
|
+
// src/agent/claude/session-paths.ts
|
|
7101
|
+
import { readdir as readdir6, stat as stat4 } from "fs/promises";
|
|
7102
|
+
import { homedir as homedir4 } from "os";
|
|
7103
|
+
import { join as join15 } from "path";
|
|
7104
|
+
function claudeProjectDir(cwd, projectsRoot = join15(homedir4(), ".claude", "projects")) {
|
|
7105
|
+
return join15(projectsRoot, cwd.replace(/[^A-Za-z0-9]/g, "-"));
|
|
7106
|
+
}
|
|
7107
|
+
async function latestClaudeSessionId(cwd, projectsRoot) {
|
|
7108
|
+
const dir = claudeProjectDir(cwd, projectsRoot);
|
|
7109
|
+
let files;
|
|
7110
|
+
try {
|
|
7111
|
+
files = (await readdir6(dir)).filter((file) => file.endsWith(".jsonl"));
|
|
7112
|
+
} catch {
|
|
7113
|
+
return void 0;
|
|
7114
|
+
}
|
|
7115
|
+
let newest;
|
|
7116
|
+
for (const file of files) {
|
|
7117
|
+
try {
|
|
7118
|
+
const info = await stat4(join15(dir, file));
|
|
7119
|
+
if (!newest || info.mtimeMs > newest.mtime) {
|
|
7120
|
+
newest = { id: file.replace(/\.jsonl$/, ""), mtime: info.mtimeMs };
|
|
7121
|
+
}
|
|
7122
|
+
} catch {
|
|
7123
|
+
continue;
|
|
7124
|
+
}
|
|
7125
|
+
}
|
|
7126
|
+
return newest?.id;
|
|
7127
|
+
}
|
|
7128
|
+
|
|
7129
|
+
// src/agent/jsonl-adapter.ts
|
|
7130
|
+
import { createInterface as createInterface3 } from "readline";
|
|
6961
7131
|
var JsonlAgentAdapter = class {
|
|
6962
7132
|
id;
|
|
6963
7133
|
displayName;
|
|
7134
|
+
sideQuery;
|
|
6964
7135
|
options;
|
|
6965
7136
|
botIdentity;
|
|
6966
7137
|
constructor(options) {
|
|
6967
7138
|
this.options = options;
|
|
6968
7139
|
this.id = options.id;
|
|
6969
7140
|
this.displayName = options.displayName;
|
|
7141
|
+
if (options.sideQuery) this.sideQuery = options.sideQuery;
|
|
6970
7142
|
}
|
|
6971
7143
|
setBotIdentity(identity) {
|
|
6972
7144
|
this.botIdentity = identity;
|
|
@@ -7034,7 +7206,7 @@ var JsonlAgentAdapter = class {
|
|
|
7034
7206
|
yield { type: "error", message: `failed to spawn ${this.id}`, terminationReason: "failed" };
|
|
7035
7207
|
return;
|
|
7036
7208
|
}
|
|
7037
|
-
const rl =
|
|
7209
|
+
const rl = createInterface3({ input: child.stdout });
|
|
7038
7210
|
let terminal = false;
|
|
7039
7211
|
let sessionSeen;
|
|
7040
7212
|
let invalidJsonCount = 0;
|
|
@@ -7256,6 +7428,55 @@ function* translateEvent(raw) {
|
|
|
7256
7428
|
}
|
|
7257
7429
|
}
|
|
7258
7430
|
|
|
7431
|
+
// src/agent/claude/side-query.ts
|
|
7432
|
+
function buildClaudeSideQueryArgs(input) {
|
|
7433
|
+
return [
|
|
7434
|
+
"-p",
|
|
7435
|
+
"--output-format",
|
|
7436
|
+
"stream-json",
|
|
7437
|
+
"--verbose",
|
|
7438
|
+
"--resume",
|
|
7439
|
+
input.sessionId,
|
|
7440
|
+
"--fork-session",
|
|
7441
|
+
"--tools",
|
|
7442
|
+
""
|
|
7443
|
+
];
|
|
7444
|
+
}
|
|
7445
|
+
async function deleteClaudeSessionFile(sessionId, projectsRoot = join16(homedir5(), ".claude", "projects")) {
|
|
7446
|
+
let dirs;
|
|
7447
|
+
try {
|
|
7448
|
+
dirs = await readdir7(projectsRoot, { withFileTypes: true });
|
|
7449
|
+
} catch {
|
|
7450
|
+
return;
|
|
7451
|
+
}
|
|
7452
|
+
for (const dir of dirs) {
|
|
7453
|
+
if (!dir.isDirectory()) continue;
|
|
7454
|
+
const base = join16(projectsRoot, dir.name, sessionId);
|
|
7455
|
+
await rm14(`${base}.jsonl`, { force: true, maxRetries: 5, retryDelay: 25 }).catch(() => {
|
|
7456
|
+
});
|
|
7457
|
+
await rm14(base, { recursive: true, force: true, maxRetries: 5, retryDelay: 25 }).catch(() => {
|
|
7458
|
+
});
|
|
7459
|
+
}
|
|
7460
|
+
}
|
|
7461
|
+
async function runClaudeSideQuery(input) {
|
|
7462
|
+
const sessionId = input.sessionId ?? await latestClaudeSessionId(input.cwd, input.projectsRoot);
|
|
7463
|
+
if (!sessionId) return { text: "", error: "\u4F1A\u8BDD\u5C1A\u672A\u5EFA\u7ACB" };
|
|
7464
|
+
const result = await runJsonlSideQuery({
|
|
7465
|
+
agent: "claude",
|
|
7466
|
+
binary: input.binary,
|
|
7467
|
+
args: buildClaudeSideQueryArgs({ sessionId }),
|
|
7468
|
+
cwd: input.cwd,
|
|
7469
|
+
prompt: buildBtwPrompt(input.question),
|
|
7470
|
+
translate: (raw) => [...translateEvent(raw)],
|
|
7471
|
+
signal: input.signal
|
|
7472
|
+
});
|
|
7473
|
+
if (result.sessionId && result.sessionId !== sessionId) {
|
|
7474
|
+
markBtwSession("claude", result.sessionId);
|
|
7475
|
+
await deleteClaudeSessionFile(result.sessionId, input.projectsRoot);
|
|
7476
|
+
}
|
|
7477
|
+
return result.error ? { text: result.text, error: result.error } : { text: result.text };
|
|
7478
|
+
}
|
|
7479
|
+
|
|
7259
7480
|
// src/agent/claude/adapter.ts
|
|
7260
7481
|
var ClaudeAdapter = class {
|
|
7261
7482
|
id = "claude";
|
|
@@ -7268,6 +7489,15 @@ var ClaudeAdapter = class {
|
|
|
7268
7489
|
setBotIdentity(identity) {
|
|
7269
7490
|
this.botIdentity = identity;
|
|
7270
7491
|
}
|
|
7492
|
+
async sideQuery(opts) {
|
|
7493
|
+
return runClaudeSideQuery({
|
|
7494
|
+
binary: this.binary,
|
|
7495
|
+
cwd: opts.cwd,
|
|
7496
|
+
...opts.sessionId ? { sessionId: opts.sessionId } : {},
|
|
7497
|
+
question: opts.question,
|
|
7498
|
+
signal: opts.signal
|
|
7499
|
+
});
|
|
7500
|
+
}
|
|
7271
7501
|
async isAvailable() {
|
|
7272
7502
|
return (await this.checkAvailability()).ok;
|
|
7273
7503
|
}
|
|
@@ -7400,7 +7630,7 @@ async function* createEventStream(child, stderrChunks, getError) {
|
|
|
7400
7630
|
};
|
|
7401
7631
|
return;
|
|
7402
7632
|
}
|
|
7403
|
-
const rl =
|
|
7633
|
+
const rl = createInterface4({ input: child.stdout, crlfDelay: Infinity });
|
|
7404
7634
|
let sawStdout = false;
|
|
7405
7635
|
let silentExitTimer;
|
|
7406
7636
|
const closeSilentStdout = () => {
|
|
@@ -7461,8 +7691,8 @@ async function* createEventStream(child, stderrChunks, getError) {
|
|
|
7461
7691
|
}
|
|
7462
7692
|
}
|
|
7463
7693
|
function writeSystemPromptFile(content) {
|
|
7464
|
-
const dir = mkdtempSync(
|
|
7465
|
-
const path4 =
|
|
7694
|
+
const dir = mkdtempSync(join17(tmpdir3(), "xiaojiu-claude-"));
|
|
7695
|
+
const path4 = join17(dir, "append-system-prompt.md");
|
|
7466
7696
|
writeFileSync3(path4, content, "utf8");
|
|
7467
7697
|
return {
|
|
7468
7698
|
path: path4,
|
|
@@ -7479,8 +7709,8 @@ function isWindowsCommandNotFoundLine(line) {
|
|
|
7479
7709
|
}
|
|
7480
7710
|
|
|
7481
7711
|
// src/agent/codex/adapter.ts
|
|
7482
|
-
import { createInterface as
|
|
7483
|
-
import { join as
|
|
7712
|
+
import { createInterface as createInterface5 } from "readline";
|
|
7713
|
+
import { join as join19 } from "path";
|
|
7484
7714
|
|
|
7485
7715
|
// src/runtime/errors.ts
|
|
7486
7716
|
var RunRejected = class extends Error {
|
|
@@ -7547,6 +7777,11 @@ function buildCodexArgs(input) {
|
|
|
7547
7777
|
];
|
|
7548
7778
|
}
|
|
7549
7779
|
|
|
7780
|
+
// src/agent/codex/side-query.ts
|
|
7781
|
+
import { readdir as readdir8, rm as rm15 } from "fs/promises";
|
|
7782
|
+
import { homedir as homedir6 } from "os";
|
|
7783
|
+
import { join as join18 } from "path";
|
|
7784
|
+
|
|
7550
7785
|
// src/agent/codex/jsonl.ts
|
|
7551
7786
|
var CodexJsonlTranslator = class {
|
|
7552
7787
|
threadId;
|
|
@@ -7792,6 +8027,66 @@ function truncate(value, max) {
|
|
|
7792
8027
|
return value.length > max ? value.slice(0, max) : value;
|
|
7793
8028
|
}
|
|
7794
8029
|
|
|
8030
|
+
// src/agent/codex/side-query.ts
|
|
8031
|
+
function buildCodexSideQueryArgs(threadId) {
|
|
8032
|
+
return [
|
|
8033
|
+
"exec",
|
|
8034
|
+
"fork",
|
|
8035
|
+
threadId,
|
|
8036
|
+
"--json",
|
|
8037
|
+
"--sandbox",
|
|
8038
|
+
"read-only",
|
|
8039
|
+
"-c",
|
|
8040
|
+
'approval_policy="never"',
|
|
8041
|
+
"--skip-git-repo-check",
|
|
8042
|
+
"-"
|
|
8043
|
+
];
|
|
8044
|
+
}
|
|
8045
|
+
async function deleteCodexThreadRollout(threadId, codexHome = process.env.CODEX_HOME || join18(homedir6(), ".codex")) {
|
|
8046
|
+
const root = join18(codexHome, "sessions");
|
|
8047
|
+
const queue = [{ dir: root, depth: 0 }];
|
|
8048
|
+
while (queue.length > 0) {
|
|
8049
|
+
const current = queue.pop();
|
|
8050
|
+
if (!current) break;
|
|
8051
|
+
let entries;
|
|
8052
|
+
try {
|
|
8053
|
+
entries = await readdir8(current.dir, { withFileTypes: true });
|
|
8054
|
+
} catch {
|
|
8055
|
+
continue;
|
|
8056
|
+
}
|
|
8057
|
+
for (const entry of entries) {
|
|
8058
|
+
const path4 = join18(current.dir, entry.name);
|
|
8059
|
+
if (entry.isDirectory()) {
|
|
8060
|
+
if (current.depth < 4) queue.push({ dir: path4, depth: current.depth + 1 });
|
|
8061
|
+
continue;
|
|
8062
|
+
}
|
|
8063
|
+
if (entry.name.startsWith("rollout-") && entry.name.endsWith(`-${threadId}.jsonl`)) {
|
|
8064
|
+
await rm15(path4, { force: true, maxRetries: 5, retryDelay: 25 }).catch(() => {
|
|
8065
|
+
});
|
|
8066
|
+
}
|
|
8067
|
+
}
|
|
8068
|
+
}
|
|
8069
|
+
}
|
|
8070
|
+
async function runCodexSideQuery(input) {
|
|
8071
|
+
if (!input.threadId) return { text: "", error: "\u4F1A\u8BDD\u5C1A\u672A\u5EFA\u7ACB" };
|
|
8072
|
+
const translator = new CodexJsonlTranslator();
|
|
8073
|
+
const result = await runJsonlSideQuery({
|
|
8074
|
+
agent: "codex",
|
|
8075
|
+
binary: input.binary,
|
|
8076
|
+
args: buildCodexSideQueryArgs(input.threadId),
|
|
8077
|
+
cwd: input.cwd,
|
|
8078
|
+
...input.env ? { env: input.env } : {},
|
|
8079
|
+
prompt: buildBtwPrompt(input.question),
|
|
8080
|
+
translate: (raw) => translator.translate(raw),
|
|
8081
|
+
signal: input.signal
|
|
8082
|
+
});
|
|
8083
|
+
if (result.threadId && result.threadId !== input.threadId) {
|
|
8084
|
+
markBtwSession("codex", result.threadId);
|
|
8085
|
+
await deleteCodexThreadRollout(result.threadId, input.codexHome);
|
|
8086
|
+
}
|
|
8087
|
+
return result.error ? { text: result.text, error: result.error } : { text: result.text };
|
|
8088
|
+
}
|
|
8089
|
+
|
|
7795
8090
|
// src/agent/codex/adapter.ts
|
|
7796
8091
|
var CodexAdapter = class {
|
|
7797
8092
|
id = "codex";
|
|
@@ -7818,6 +8113,17 @@ var CodexAdapter = class {
|
|
|
7818
8113
|
setBotIdentity(identity) {
|
|
7819
8114
|
this.botIdentity = identity;
|
|
7820
8115
|
}
|
|
8116
|
+
async sideQuery(opts) {
|
|
8117
|
+
const codexHome = this.codexHome ?? (this.inheritCodexHome ? void 0 : join19(this.profileStateDir, "codex-home"));
|
|
8118
|
+
return runCodexSideQuery({
|
|
8119
|
+
binary: this.binary,
|
|
8120
|
+
cwd: opts.cwd,
|
|
8121
|
+
...opts.threadId ? { threadId: opts.threadId } : {},
|
|
8122
|
+
question: opts.question,
|
|
8123
|
+
signal: opts.signal,
|
|
8124
|
+
...codexHome ? { codexHome, env: { CODEX_HOME: codexHome } } : {}
|
|
8125
|
+
});
|
|
8126
|
+
}
|
|
7821
8127
|
async isAvailable() {
|
|
7822
8128
|
return (await this.checkAvailability()).ok;
|
|
7823
8129
|
}
|
|
@@ -7859,7 +8165,7 @@ var CodexAdapter = class {
|
|
|
7859
8165
|
if (this.codexHome) {
|
|
7860
8166
|
envOverrides.CODEX_HOME = this.codexHome;
|
|
7861
8167
|
} else if (!this.inheritCodexHome) {
|
|
7862
|
-
envOverrides.CODEX_HOME =
|
|
8168
|
+
envOverrides.CODEX_HOME = join19(this.profileStateDir, "codex-home");
|
|
7863
8169
|
}
|
|
7864
8170
|
const child = spawnProcess(this.binary, args, {
|
|
7865
8171
|
cwd: opts.cwd,
|
|
@@ -7968,7 +8274,7 @@ async function* createEventStream2(child, stderrChunks, getError, getStopReason)
|
|
|
7968
8274
|
};
|
|
7969
8275
|
return;
|
|
7970
8276
|
}
|
|
7971
|
-
const rl =
|
|
8277
|
+
const rl = createInterface5({ input: child.stdout, crlfDelay: Infinity });
|
|
7972
8278
|
let sawStdout = false;
|
|
7973
8279
|
let silentExitTimer;
|
|
7974
8280
|
const closeSilentStdout = () => {
|
|
@@ -8034,10 +8340,10 @@ function isWindowsCommandNotFoundLine2(line) {
|
|
|
8034
8340
|
}
|
|
8035
8341
|
|
|
8036
8342
|
// src/bot/channel.ts
|
|
8037
|
-
import { dirname as dirname19, join as
|
|
8343
|
+
import { dirname as dirname19, join as join26 } from "path";
|
|
8038
8344
|
|
|
8039
8345
|
// src/channel/channel.ts
|
|
8040
|
-
import { join as
|
|
8346
|
+
import { join as join20 } from "path";
|
|
8041
8347
|
|
|
8042
8348
|
// src/channel/xiaojiu/dedupe-store.ts
|
|
8043
8349
|
import { readFile as readFile13 } from "fs/promises";
|
|
@@ -8746,7 +9052,7 @@ var XiaojiuChannel = class {
|
|
|
8746
9052
|
sendMessageApiVersion: options.sendMessageApiVersion
|
|
8747
9053
|
});
|
|
8748
9054
|
this.dedupe = new XiaojiuDedupeStore(
|
|
8749
|
-
options.dedupeFile ??
|
|
9055
|
+
options.dedupeFile ?? join20(process.cwd(), ".xiaojiu-webhook-events.json"),
|
|
8750
9056
|
options.dedupeTtlMs ? { ttlMs: options.dedupeTtlMs } : {}
|
|
8751
9057
|
);
|
|
8752
9058
|
this.throttleMs = Math.max(250, options.streamThrottleMs ?? 250);
|
|
@@ -9112,8 +9418,8 @@ function fitTextToBudget(text2, max) {
|
|
|
9112
9418
|
const available = max - STREAM_TRUNCATION_MARKER.length;
|
|
9113
9419
|
const headLength = Math.ceil(available / 2);
|
|
9114
9420
|
const tailLength = available - headLength;
|
|
9115
|
-
const
|
|
9116
|
-
return `${text2.slice(0, headLength)}${STREAM_TRUNCATION_MARKER}${
|
|
9421
|
+
const tail2 = tailLength > 0 ? text2.slice(-tailLength) : "";
|
|
9422
|
+
return `${text2.slice(0, headLength)}${STREAM_TRUNCATION_MARKER}${tail2}`;
|
|
9117
9423
|
}
|
|
9118
9424
|
function streamingMarkdownCard(markdown) {
|
|
9119
9425
|
return xiaojiuCard("\u5B9E\u65F6\u8F93\u51FA", [xiaojiuMarkdown(markdown)]);
|
|
@@ -9317,6 +9623,98 @@ function mentionNames(mentions) {
|
|
|
9317
9623
|
return names;
|
|
9318
9624
|
}
|
|
9319
9625
|
|
|
9626
|
+
// src/bot/side-query.ts
|
|
9627
|
+
var TIMEOUT_MS = 9e4;
|
|
9628
|
+
var COOLDOWN_MS = 1e4;
|
|
9629
|
+
var MAX_CONCURRENT = 2;
|
|
9630
|
+
var inFlight = /* @__PURE__ */ new Set();
|
|
9631
|
+
var lastAskedAt = /* @__PURE__ */ new Map();
|
|
9632
|
+
var active2 = 0;
|
|
9633
|
+
async function runSideQuery(input) {
|
|
9634
|
+
const now = input.now ?? Date.now;
|
|
9635
|
+
const run = input.agent.sideQuery;
|
|
9636
|
+
if (!run) {
|
|
9637
|
+
return {
|
|
9638
|
+
ok: false,
|
|
9639
|
+
code: "unsupported",
|
|
9640
|
+
message: `\u5F53\u524D agent\uFF08${input.agent.displayName}\uFF09\u6CA1\u6709\u65C1\u8DEF\u63D0\u95EE\u80FD\u529B\u3002`
|
|
9641
|
+
};
|
|
9642
|
+
}
|
|
9643
|
+
const live = input.progress?.active(input.scope);
|
|
9644
|
+
const stored = input.sessions.getRaw(input.scope);
|
|
9645
|
+
const catalogEntry = input.sessionCatalog && input.sessionCatalogIdentity ? input.sessionCatalog.activeFor(input.sessionCatalogIdentity) : void 0;
|
|
9646
|
+
const sessionId = live?.sessionId ?? stored?.sessionId;
|
|
9647
|
+
const threadId = live?.threadId ?? catalogEntry?.threadId;
|
|
9648
|
+
if (inFlight.has(input.key)) {
|
|
9649
|
+
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" };
|
|
9650
|
+
}
|
|
9651
|
+
const cooldownMs = input.cooldownMs ?? COOLDOWN_MS;
|
|
9652
|
+
const startedAt = now();
|
|
9653
|
+
const last = lastAskedAt.get(input.key);
|
|
9654
|
+
if (last !== void 0 && startedAt - last < cooldownMs) {
|
|
9655
|
+
const waitSeconds = Math.ceil((cooldownMs - (startedAt - last)) / 1e3);
|
|
9656
|
+
return { ok: false, code: "cooldown", message: `\u521A\u95EE\u8FC7\uFF0C${waitSeconds}s \u540E\u518D\u8BD5\u3002` };
|
|
9657
|
+
}
|
|
9658
|
+
if (active2 >= MAX_CONCURRENT) {
|
|
9659
|
+
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" };
|
|
9660
|
+
}
|
|
9661
|
+
const cwd = live?.cwd ?? input.cwd;
|
|
9662
|
+
if (!cwd) {
|
|
9663
|
+
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" };
|
|
9664
|
+
}
|
|
9665
|
+
inFlight.add(input.key);
|
|
9666
|
+
lastAskedAt.set(input.key, startedAt);
|
|
9667
|
+
active2 += 1;
|
|
9668
|
+
const controller = new AbortController();
|
|
9669
|
+
const timer = setTimeout(() => controller.abort(), input.timeoutMs ?? TIMEOUT_MS);
|
|
9670
|
+
log.info("btw", "start", {
|
|
9671
|
+
scope: input.scope,
|
|
9672
|
+
agent: input.agent.id,
|
|
9673
|
+
hasSession: Boolean(sessionId),
|
|
9674
|
+
hasThread: Boolean(threadId),
|
|
9675
|
+
questionChars: input.question.length
|
|
9676
|
+
});
|
|
9677
|
+
try {
|
|
9678
|
+
const result = await run({
|
|
9679
|
+
question: input.question,
|
|
9680
|
+
cwd,
|
|
9681
|
+
...sessionId ? { sessionId } : {},
|
|
9682
|
+
...threadId ? { threadId } : {},
|
|
9683
|
+
signal: controller.signal
|
|
9684
|
+
});
|
|
9685
|
+
const durationMs = now() - startedAt;
|
|
9686
|
+
const text2 = result.text.trim();
|
|
9687
|
+
if (text2) {
|
|
9688
|
+
log.info("btw", "done", {
|
|
9689
|
+
scope: input.scope,
|
|
9690
|
+
agent: input.agent.id,
|
|
9691
|
+
durationMs,
|
|
9692
|
+
chars: text2.length,
|
|
9693
|
+
partial: Boolean(result.error)
|
|
9694
|
+
});
|
|
9695
|
+
reportMetric("btw_ms", durationMs, { agent: input.agent.id });
|
|
9696
|
+
return result.error ? { ok: false, code: "failed", message: result.error, partial: text2 } : { ok: true, text: text2 };
|
|
9697
|
+
}
|
|
9698
|
+
const aborted = controller.signal.aborted;
|
|
9699
|
+
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";
|
|
9700
|
+
log.warn("btw", "fail", {
|
|
9701
|
+
scope: input.scope,
|
|
9702
|
+
agent: input.agent.id,
|
|
9703
|
+
durationMs,
|
|
9704
|
+
code: aborted ? "timeout" : "failed",
|
|
9705
|
+
err: result.error
|
|
9706
|
+
});
|
|
9707
|
+
return { ok: false, code: aborted ? "timeout" : "failed", message };
|
|
9708
|
+
} catch (err) {
|
|
9709
|
+
log.fail("btw", err, { scope: input.scope, agent: input.agent.id });
|
|
9710
|
+
return { ok: false, code: "failed", message: err instanceof Error ? err.message : String(err) };
|
|
9711
|
+
} finally {
|
|
9712
|
+
clearTimeout(timer);
|
|
9713
|
+
inFlight.delete(input.key);
|
|
9714
|
+
active2 -= 1;
|
|
9715
|
+
}
|
|
9716
|
+
}
|
|
9717
|
+
|
|
9320
9718
|
// src/card/config-card.ts
|
|
9321
9719
|
function accessMarkdown(opts, expanded) {
|
|
9322
9720
|
const teamMode = opts.mode === "team";
|
|
@@ -9827,6 +10225,7 @@ function helpCard(agentName = "Agent") {
|
|
|
9827
10225
|
"- `/ws list|save <name>|use <name>|remove <name>` \u2014 \u5DE5\u4F5C\u76EE\u5F55",
|
|
9828
10226
|
"- `/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
10227
|
"- `/status` \u2014 \u5F53\u524D\u72B6\u6001",
|
|
10228
|
+
"- `/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
10229
|
"- `/myid` \u2014 \u4EE5\u5361\u7247\u663E\u793A\u5F53\u524D\u7FA4\u7EC4\u3001\u9891\u9053\u548C\u8BDD\u9898 id",
|
|
9831
10230
|
"- `/agent <claude|codex|pi|opencode|omp>` \u2014 \u7A7A\u95F2\u65F6\u5207\u6362\u672C profile \u7684 Coding Agent",
|
|
9832
10231
|
"- `/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",
|
|
@@ -10505,10 +10904,9 @@ function finalizeIfRunning(state) {
|
|
|
10505
10904
|
|
|
10506
10905
|
// src/session/history.ts
|
|
10507
10906
|
import { createReadStream } from "fs";
|
|
10508
|
-
import { readdir as
|
|
10509
|
-
import {
|
|
10510
|
-
import {
|
|
10511
|
-
import { createInterface as createInterface5 } from "readline";
|
|
10907
|
+
import { readdir as readdir9, stat as stat5 } from "fs/promises";
|
|
10908
|
+
import { join as join21 } from "path";
|
|
10909
|
+
import { createInterface as createInterface6 } from "readline";
|
|
10512
10910
|
|
|
10513
10911
|
// src/session/preview.ts
|
|
10514
10912
|
var DEFAULT_PREVIEW_MAX_CHARS = 80;
|
|
@@ -10542,27 +10940,23 @@ function truncatePreview(input, maxChars) {
|
|
|
10542
10940
|
}
|
|
10543
10941
|
|
|
10544
10942
|
// 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
10943
|
async function listRecentSessions(cwd, limit = 5) {
|
|
10552
10944
|
const dir = claudeProjectDir(cwd);
|
|
10553
10945
|
let files;
|
|
10554
10946
|
try {
|
|
10555
|
-
files = await
|
|
10947
|
+
files = await readdir9(dir);
|
|
10556
10948
|
} catch (err) {
|
|
10557
10949
|
if (err.code === "ENOENT") return [];
|
|
10558
10950
|
throw err;
|
|
10559
10951
|
}
|
|
10560
|
-
const jsonls = files.filter(
|
|
10952
|
+
const jsonls = files.filter(
|
|
10953
|
+
(f) => f.endsWith(".jsonl") && !isBtwSession("claude", f.replace(/\.jsonl$/, ""))
|
|
10954
|
+
);
|
|
10561
10955
|
const withStats = await Promise.all(
|
|
10562
10956
|
jsonls.map(async (f) => {
|
|
10563
|
-
const path4 =
|
|
10957
|
+
const path4 = join21(dir, f);
|
|
10564
10958
|
try {
|
|
10565
|
-
const st = await
|
|
10959
|
+
const st = await stat5(path4);
|
|
10566
10960
|
return { file: f, path: path4, mtime: st.mtimeMs };
|
|
10567
10961
|
} catch {
|
|
10568
10962
|
return null;
|
|
@@ -10580,7 +10974,7 @@ async function listRecentSessions(cwd, limit = 5) {
|
|
|
10580
10974
|
}
|
|
10581
10975
|
async function summarize(path4) {
|
|
10582
10976
|
const stream2 = createReadStream(path4, { encoding: "utf8" });
|
|
10583
|
-
const rl =
|
|
10977
|
+
const rl = createInterface6({ input: stream2 });
|
|
10584
10978
|
let preview = "";
|
|
10585
10979
|
let lineCount = 0;
|
|
10586
10980
|
try {
|
|
@@ -10630,8 +11024,8 @@ function formatRelTime(mtime) {
|
|
|
10630
11024
|
}
|
|
10631
11025
|
|
|
10632
11026
|
// src/session/codex-history.ts
|
|
10633
|
-
import { createInterface as
|
|
10634
|
-
import { join as
|
|
11027
|
+
import { createInterface as createInterface7 } from "readline";
|
|
11028
|
+
import { join as join22 } from "path";
|
|
10635
11029
|
var CodexHistoryError = class extends Error {
|
|
10636
11030
|
code;
|
|
10637
11031
|
constructor(code, message, options) {
|
|
@@ -10654,7 +11048,7 @@ async function listCodexThreadHistory(options) {
|
|
|
10654
11048
|
const stderrChunks = [];
|
|
10655
11049
|
let settled = false;
|
|
10656
11050
|
const result = await new Promise((resolve5, reject4) => {
|
|
10657
|
-
const rl =
|
|
11051
|
+
const rl = createInterface7({ input: child.stdout, crlfDelay: Infinity });
|
|
10658
11052
|
let timer;
|
|
10659
11053
|
const fail = (err) => {
|
|
10660
11054
|
if (settled) return;
|
|
@@ -10738,15 +11132,15 @@ ${JSON.stringify(listRequest(options))}
|
|
|
10738
11132
|
fail(err);
|
|
10739
11133
|
}
|
|
10740
11134
|
});
|
|
10741
|
-
await
|
|
10742
|
-
return result;
|
|
11135
|
+
await waitForChildExit2(child, 250);
|
|
11136
|
+
return result.filter((entry) => !isBtwSession("codex", entry.threadId));
|
|
10743
11137
|
}
|
|
10744
11138
|
function spawnCodexAppServer(options) {
|
|
10745
11139
|
const envOverrides = {};
|
|
10746
11140
|
if (options.codexHome) {
|
|
10747
11141
|
envOverrides.CODEX_HOME = options.codexHome;
|
|
10748
11142
|
} else if (options.inheritCodexHome === false) {
|
|
10749
|
-
envOverrides.CODEX_HOME =
|
|
11143
|
+
envOverrides.CODEX_HOME = join22(options.profileStateDir, "codex-home");
|
|
10750
11144
|
}
|
|
10751
11145
|
return spawnProcess(options.binary, ["app-server", "--listen", "stdio://"], {
|
|
10752
11146
|
env: mergeProcessEnv(process.env, envOverrides),
|
|
@@ -10814,7 +11208,7 @@ function normalizeThread(input) {
|
|
|
10814
11208
|
...stringValue2(raw.name) ? { name: stringValue2(raw.name) } : {}
|
|
10815
11209
|
};
|
|
10816
11210
|
}
|
|
10817
|
-
async function
|
|
11211
|
+
async function waitForChildExit2(child, timeoutMs) {
|
|
10818
11212
|
if (child.exitCode !== null || child.signalCode !== null) return;
|
|
10819
11213
|
await new Promise((resolve5) => {
|
|
10820
11214
|
const timer = setTimeout(() => {
|
|
@@ -11022,11 +11416,11 @@ async function fetchKnownChats(channel) {
|
|
|
11022
11416
|
}
|
|
11023
11417
|
|
|
11024
11418
|
// src/platform/home-path.ts
|
|
11025
|
-
import { homedir as
|
|
11419
|
+
import { homedir as homedir7 } from "os";
|
|
11026
11420
|
import { isAbsolute as isAbsolute2 } from "path";
|
|
11027
11421
|
function expandTilde(p3) {
|
|
11028
|
-
if (p3 === "~") return
|
|
11029
|
-
if (p3.startsWith("~/")) return `${
|
|
11422
|
+
if (p3 === "~") return homedir7();
|
|
11423
|
+
if (p3.startsWith("~/")) return `${homedir7()}${p3.slice(1)}`;
|
|
11030
11424
|
return p3;
|
|
11031
11425
|
}
|
|
11032
11426
|
function isAbsoluteOrTilde(p3) {
|
|
@@ -11049,6 +11443,7 @@ var handlers = {
|
|
|
11049
11443
|
"/ws": handleWs,
|
|
11050
11444
|
"/resume": handleResume,
|
|
11051
11445
|
"/status": handleStatus,
|
|
11446
|
+
"/btw": handleBtw,
|
|
11052
11447
|
"/myid": handleMyId,
|
|
11053
11448
|
"/help": handleHelp,
|
|
11054
11449
|
"/config": handleConfig,
|
|
@@ -11077,6 +11472,13 @@ var ADMIN_COMMANDS = /* @__PURE__ */ new Set([
|
|
|
11077
11472
|
function isAdminCommand(cmd) {
|
|
11078
11473
|
return ADMIN_COMMANDS.has(cmd.startsWith("/") ? cmd : `/${cmd}`);
|
|
11079
11474
|
}
|
|
11475
|
+
var READ_ONLY_COMMANDS = /* @__PURE__ */ new Set(["/btw", "/status", "/help", "/myid"]);
|
|
11476
|
+
function isReadOnlyCommandInvocation(content, mentions) {
|
|
11477
|
+
const trimmed = stripMatchedMentions(content, mentions).trim();
|
|
11478
|
+
if (!trimmed.startsWith("/")) return false;
|
|
11479
|
+
const cmd = trimmed.split(/\s+/)[0] ?? "";
|
|
11480
|
+
return READ_ONLY_COMMANDS.has(cmd);
|
|
11481
|
+
}
|
|
11080
11482
|
async function tryHandleCommand(ctx) {
|
|
11081
11483
|
const trimmed = stripMatchedMentions(ctx.msg.content, ctx.msg.mentions).trim();
|
|
11082
11484
|
if (!trimmed.startsWith("/")) return false;
|
|
@@ -11560,6 +11962,75 @@ async function handleStatus(_args, ctx) {
|
|
|
11560
11962
|
});
|
|
11561
11963
|
await ctx.channel.send(commandSendChatId(ctx), { card }, commandReplyOptions(ctx));
|
|
11562
11964
|
}
|
|
11965
|
+
async function handleBtw(args, ctx) {
|
|
11966
|
+
if (!ctx.activeRuns.get(ctx.scope)) {
|
|
11967
|
+
await reply(ctx, "\u5F53\u524D\u6CA1\u6709\u8FD0\u884C\u4E2D\u7684\u4EFB\u52A1\u3002");
|
|
11968
|
+
return;
|
|
11969
|
+
}
|
|
11970
|
+
const attempt = await runSideQuery({
|
|
11971
|
+
agent: ctx.agent,
|
|
11972
|
+
...ctx.runProgress ? { progress: ctx.runProgress } : {},
|
|
11973
|
+
sessions: ctx.sessions,
|
|
11974
|
+
...ctx.sessionCatalog ? { sessionCatalog: ctx.sessionCatalog } : {},
|
|
11975
|
+
...ctx.sessionCatalogIdentity ? { sessionCatalogIdentity: ctx.sessionCatalogIdentity } : {},
|
|
11976
|
+
scope: ctx.scope,
|
|
11977
|
+
key: `${ctx.controls.profile}:${ctx.scope}`,
|
|
11978
|
+
...effectiveWorkspaceCwd(ctx) ? { cwd: effectiveWorkspaceCwd(ctx) } : {},
|
|
11979
|
+
question: args.trim()
|
|
11980
|
+
});
|
|
11981
|
+
if (attempt.ok) {
|
|
11982
|
+
await reply(
|
|
11983
|
+
ctx,
|
|
11984
|
+
`\u{1F6F0}\uFE0F **\u65C1\u8DEF\u63D0\u95EE**\uFF08\u4E0D\u8FDB\u5165\u4F1A\u8BDD\u5386\u53F2\uFF09
|
|
11985
|
+
|
|
11986
|
+
${attempt.text}
|
|
11987
|
+
|
|
11988
|
+
_\u2014 /btw \u4FA7\u67E5\u8BE2\uFF0C\u672A\u5199\u5165\u4F1A\u8BDD_`
|
|
11989
|
+
);
|
|
11990
|
+
return;
|
|
11991
|
+
}
|
|
11992
|
+
const lines = [`\u274C ${attempt.message}`];
|
|
11993
|
+
if (attempt.partial) lines.push("", attempt.partial);
|
|
11994
|
+
const liveLine = describeLiveRunLine(ctx);
|
|
11995
|
+
if (liveLine) lines.push("", liveLine);
|
|
11996
|
+
await reply(ctx, lines.join("\n"));
|
|
11997
|
+
}
|
|
11998
|
+
function describeLiveRunLine(ctx) {
|
|
11999
|
+
const live = ctx.runProgress?.active(ctx.scope);
|
|
12000
|
+
if (!live) return "";
|
|
12001
|
+
const now = Date.now();
|
|
12002
|
+
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)}_`;
|
|
12003
|
+
}
|
|
12004
|
+
function describeCurrentAction(live, now) {
|
|
12005
|
+
if (live.toolsInFlight.length > 0) {
|
|
12006
|
+
return live.toolsInFlight.map((tool) => `\u5DE5\u5177 \`${escapeCode2(tool.name)}\` ${formatDuration(now - tool.startedAt)}`).join("\u3001");
|
|
12007
|
+
}
|
|
12008
|
+
switch (live.phase) {
|
|
12009
|
+
case "starting":
|
|
12010
|
+
return "\u7B49\u5F85 agent \u9996\u6761\u4E8B\u4EF6";
|
|
12011
|
+
case "thinking":
|
|
12012
|
+
return "\u601D\u8003\u4E2D";
|
|
12013
|
+
case "text":
|
|
12014
|
+
return "\u5199\u56DE\u590D\u4E2D";
|
|
12015
|
+
case "tool":
|
|
12016
|
+
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";
|
|
12017
|
+
}
|
|
12018
|
+
}
|
|
12019
|
+
function escapeCode2(text2) {
|
|
12020
|
+
return text2.replace(/`/g, "'");
|
|
12021
|
+
}
|
|
12022
|
+
function formatDuration(ms) {
|
|
12023
|
+
const totalSeconds = Math.max(0, Math.round(ms / 1e3));
|
|
12024
|
+
if (totalSeconds < 60) return `${totalSeconds}s`;
|
|
12025
|
+
const minutes = Math.floor(totalSeconds / 60);
|
|
12026
|
+
if (minutes < 60) {
|
|
12027
|
+
const seconds = totalSeconds % 60;
|
|
12028
|
+
return seconds ? `${minutes}m${seconds}s` : `${minutes}m`;
|
|
12029
|
+
}
|
|
12030
|
+
const hours = Math.floor(minutes / 60);
|
|
12031
|
+
const rest = minutes % 60;
|
|
12032
|
+
return rest ? `${hours}h${rest}m` : `${hours}h`;
|
|
12033
|
+
}
|
|
11563
12034
|
async function handleMyId(_args, ctx) {
|
|
11564
12035
|
const card = myIdCard({
|
|
11565
12036
|
groupId: ctx.msg.threadId ?? ctx.msg.chatId,
|
|
@@ -12722,6 +13193,7 @@ async function handleCardAction(deps) {
|
|
|
12722
13193
|
agent: deps.agent,
|
|
12723
13194
|
processPool: deps.processPool,
|
|
12724
13195
|
runExecutor: deps.runExecutor,
|
|
13196
|
+
runProgress: deps.runProgress,
|
|
12725
13197
|
controls: deps.controls,
|
|
12726
13198
|
formValue,
|
|
12727
13199
|
fromCardAction: true
|
|
@@ -12793,14 +13265,14 @@ function forwardToAgent(deps, payload, formValue, scope, threadId, mode) {
|
|
|
12793
13265
|
}
|
|
12794
13266
|
function verifyBridgeToken(deps, payload, scope, action) {
|
|
12795
13267
|
const token = typeof payload.bridge_token === "string" ? payload.bridge_token : "";
|
|
12796
|
-
const
|
|
12797
|
-
if (!deps.callbackAuth || !token || !
|
|
13268
|
+
const active3 = deps.activeRuns.get(scope);
|
|
13269
|
+
if (!deps.callbackAuth || !token || !active3) {
|
|
12798
13270
|
log.info("card-action", "skip-callback-auth-missing", { scope, action });
|
|
12799
13271
|
log.warn("callback", "denied", { scope, action, reason: "missing-token-or-run" });
|
|
12800
13272
|
return false;
|
|
12801
13273
|
}
|
|
12802
13274
|
const result = deps.callbackAuth.verify(token, {
|
|
12803
|
-
runId:
|
|
13275
|
+
runId: active3.run.runId,
|
|
12804
13276
|
scope,
|
|
12805
13277
|
chatId: deps.evt.chatId,
|
|
12806
13278
|
operatorOpenId: deps.evt.operator.openId,
|
|
@@ -12909,8 +13381,8 @@ var CallbackAuth = class {
|
|
|
12909
13381
|
return { ok: true, payload };
|
|
12910
13382
|
}
|
|
12911
13383
|
signingKey() {
|
|
12912
|
-
const
|
|
12913
|
-
const key =
|
|
13384
|
+
const active3 = this.keys.filter((key2) => !key2.retired);
|
|
13385
|
+
const key = active3.at(-1);
|
|
12914
13386
|
if (!key) throw new Error("no active callback signing key");
|
|
12915
13387
|
return key;
|
|
12916
13388
|
}
|
|
@@ -13040,8 +13512,8 @@ function footerLine(status) {
|
|
|
13040
13512
|
// src/media/cache.ts
|
|
13041
13513
|
import { createHash as createHash4 } from "crypto";
|
|
13042
13514
|
import { createReadStream as createReadStream2 } from "fs";
|
|
13043
|
-
import { mkdir as mkdir16, open as open3, readdir as
|
|
13044
|
-
import { join as
|
|
13515
|
+
import { mkdir as mkdir16, open as open3, readdir as readdir10, rename as rename3, rm as rm16, stat as stat6, writeFile as writeFile9 } from "fs/promises";
|
|
13516
|
+
import { join as join23 } from "path";
|
|
13045
13517
|
|
|
13046
13518
|
// src/media/attachment.ts
|
|
13047
13519
|
var DEFAULT_POLICY = {
|
|
@@ -13177,7 +13649,7 @@ var MediaCache = class {
|
|
|
13177
13649
|
return null;
|
|
13178
13650
|
}
|
|
13179
13651
|
const kind = r.type;
|
|
13180
|
-
const tmpPath =
|
|
13652
|
+
const tmpPath = join23(
|
|
13181
13653
|
this.rootDir,
|
|
13182
13654
|
`.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`
|
|
13183
13655
|
);
|
|
@@ -13200,14 +13672,14 @@ var MediaCache = class {
|
|
|
13200
13672
|
await writeFile9(tmpPath, new Uint8Array(await response.arrayBuffer()));
|
|
13201
13673
|
contentType = response.headers.get("content-type")?.split(";")[0]?.trim();
|
|
13202
13674
|
}
|
|
13203
|
-
const tmpStat = await
|
|
13675
|
+
const tmpStat = await stat6(tmpPath);
|
|
13204
13676
|
const hash = await hashFile(tmpPath);
|
|
13205
13677
|
const mime = await sniffImageMime(tmpPath) ?? contentType ?? defaultMime(kind);
|
|
13206
13678
|
const ext = safeExtensionForMime(mime);
|
|
13207
|
-
const absPath =
|
|
13679
|
+
const absPath = join23(this.rootDir, `${hash}.${ext}`);
|
|
13208
13680
|
try {
|
|
13209
|
-
await
|
|
13210
|
-
await
|
|
13681
|
+
await stat6(absPath);
|
|
13682
|
+
await rm16(tmpPath, { force: true });
|
|
13211
13683
|
log.info("media", "cache-hit", { path: absPath });
|
|
13212
13684
|
} catch {
|
|
13213
13685
|
await rename3(tmpPath, absPath);
|
|
@@ -13263,9 +13735,9 @@ async function sniffImageMime(path4) {
|
|
|
13263
13735
|
}
|
|
13264
13736
|
async function listFiles(root) {
|
|
13265
13737
|
const out = [];
|
|
13266
|
-
const entries = await
|
|
13738
|
+
const entries = await readdir10(root, { withFileTypes: true }).catch(() => []);
|
|
13267
13739
|
for (const entry of entries) {
|
|
13268
|
-
const full =
|
|
13740
|
+
const full = join23(root, entry.name);
|
|
13269
13741
|
if (entry.isDirectory()) {
|
|
13270
13742
|
out.push(...await listFiles(full));
|
|
13271
13743
|
} else if (entry.isFile()) {
|
|
@@ -13285,20 +13757,20 @@ async function enforceCacheMaxBytes(root, maxBytes, protectedPaths) {
|
|
|
13285
13757
|
if (!Number.isFinite(maxBytes) || maxBytes <= 0) return;
|
|
13286
13758
|
const files = await Promise.all(
|
|
13287
13759
|
(await listFiles(root)).map(async (path4) => {
|
|
13288
|
-
const fileStat = await
|
|
13760
|
+
const fileStat = await stat6(path4);
|
|
13289
13761
|
return { path: path4, size: fileStat.size, mtimeMs: fileStat.mtimeMs };
|
|
13290
13762
|
})
|
|
13291
13763
|
);
|
|
13292
13764
|
let total = files.reduce((sum, file) => sum + file.size, 0);
|
|
13293
13765
|
for (const file of files.filter((item) => !protectedPaths.has(item.path)).sort((a, b) => a.mtimeMs - b.mtimeMs)) {
|
|
13294
13766
|
if (total <= maxBytes) break;
|
|
13295
|
-
await
|
|
13767
|
+
await rm16(file.path, { force: true });
|
|
13296
13768
|
total -= file.size;
|
|
13297
13769
|
}
|
|
13298
13770
|
}
|
|
13299
13771
|
async function removeRejectedResolvedFiles(attachments) {
|
|
13300
13772
|
await Promise.all(
|
|
13301
|
-
attachments.filter((attachment) => attachment.decision !== "accepted").map((attachment) =>
|
|
13773
|
+
attachments.filter((attachment) => attachment.decision !== "accepted").map((attachment) => rm16(attachment.absPath, { force: true }))
|
|
13302
13774
|
);
|
|
13303
13775
|
}
|
|
13304
13776
|
|
|
@@ -13540,6 +14012,7 @@ var RunExecutor = class {
|
|
|
13540
14012
|
createRunId;
|
|
13541
14013
|
now;
|
|
13542
14014
|
postDoneExitGraceMs;
|
|
14015
|
+
progress;
|
|
13543
14016
|
constructor(deps) {
|
|
13544
14017
|
this.agent = deps.agent;
|
|
13545
14018
|
this.pool = deps.pool;
|
|
@@ -13547,6 +14020,7 @@ var RunExecutor = class {
|
|
|
13547
14020
|
this.createRunId = deps.createRunId ?? randomUUID2;
|
|
13548
14021
|
this.now = deps.now ?? Date.now;
|
|
13549
14022
|
this.postDoneExitGraceMs = deps.postDoneExitGraceMs ?? DEFAULT_POST_DONE_EXIT_GRACE_MS;
|
|
14023
|
+
this.progress = deps.progress;
|
|
13550
14024
|
}
|
|
13551
14025
|
async submit(input) {
|
|
13552
14026
|
const submittedAt = this.now();
|
|
@@ -13649,10 +14123,20 @@ var RunExecutor = class {
|
|
|
13649
14123
|
);
|
|
13650
14124
|
}
|
|
13651
14125
|
let cleaned = false;
|
|
14126
|
+
this.progress?.begin({
|
|
14127
|
+
scope: input.scopeId,
|
|
14128
|
+
runId,
|
|
14129
|
+
startedAt,
|
|
14130
|
+
sessionId: input.sessionId,
|
|
14131
|
+
threadId: input.threadId,
|
|
14132
|
+
model: input.model,
|
|
14133
|
+
cwd: input.policy.cwdRealpath
|
|
14134
|
+
});
|
|
13652
14135
|
const cleanup = async (waitForExit2) => {
|
|
13653
14136
|
if (cleaned) return;
|
|
13654
14137
|
cleaned = true;
|
|
13655
14138
|
this.activeRuns.unregister(input.scopeId, run);
|
|
14139
|
+
this.progress?.clear(input.scopeId);
|
|
13656
14140
|
release();
|
|
13657
14141
|
if (waitForExit2) {
|
|
13658
14142
|
const exited = await run.waitForExit(this.postDoneExitGraceMs);
|
|
@@ -13674,7 +14158,9 @@ var RunExecutor = class {
|
|
|
13674
14158
|
dimensions,
|
|
13675
14159
|
startedAt,
|
|
13676
14160
|
now: this.now,
|
|
13677
|
-
onEvent: input.onEvent
|
|
14161
|
+
onEvent: input.onEvent,
|
|
14162
|
+
progress: this.progress,
|
|
14163
|
+
scope: input.scopeId
|
|
13678
14164
|
}), async () => {
|
|
13679
14165
|
await cleanup(!handle2.interrupted);
|
|
13680
14166
|
});
|
|
@@ -13698,6 +14184,7 @@ function observeRunEvents(events, opts) {
|
|
|
13698
14184
|
async *[Symbol.asyncIterator]() {
|
|
13699
14185
|
for await (const event of events) {
|
|
13700
14186
|
await opts.onEvent?.(event);
|
|
14187
|
+
opts.progress?.record(opts.scope, event);
|
|
13701
14188
|
if (event.type === "done") {
|
|
13702
14189
|
log.info("run", "completed", {
|
|
13703
14190
|
...opts.dimensions,
|
|
@@ -13794,7 +14281,7 @@ function isTerminalEvent(event) {
|
|
|
13794
14281
|
// src/session/context-store.ts
|
|
13795
14282
|
import { createHash as createHash5 } from "crypto";
|
|
13796
14283
|
import { readFile as readFile15 } from "fs/promises";
|
|
13797
|
-
import { join as
|
|
14284
|
+
import { join as join24 } from "path";
|
|
13798
14285
|
var MAX_MESSAGES = 25;
|
|
13799
14286
|
var MAX_MESSAGE_CHARS = 8e3;
|
|
13800
14287
|
var MAX_HISTORY_CHARS = 64e3;
|
|
@@ -13859,7 +14346,7 @@ var ConversationContextStore = class {
|
|
|
13859
14346
|
identity.cwdRealpath,
|
|
13860
14347
|
identity.policyFingerprint
|
|
13861
14348
|
])).digest("hex");
|
|
13862
|
-
return
|
|
14349
|
+
return join24(this.profileDir, "context", `${hash}.json`);
|
|
13863
14350
|
}
|
|
13864
14351
|
async load(identity) {
|
|
13865
14352
|
const path4 = this.path(identity);
|
|
@@ -13894,8 +14381,8 @@ var ConversationContextStore = class {
|
|
|
13894
14381
|
|
|
13895
14382
|
// src/memory/store.ts
|
|
13896
14383
|
import { createHash as createHash6, randomUUID as randomUUID3 } from "crypto";
|
|
13897
|
-
import { mkdir as mkdir17, readdir as
|
|
13898
|
-
import { join as
|
|
14384
|
+
import { mkdir as mkdir17, readdir as readdir11, realpath as realpath5, stat as stat7, writeFile as writeFile10 } from "fs/promises";
|
|
14385
|
+
import { join as join25 } from "path";
|
|
13899
14386
|
import * as lockfile5 from "proper-lockfile";
|
|
13900
14387
|
var initializations = /* @__PURE__ */ new Map();
|
|
13901
14388
|
var README_NAME = "README.md";
|
|
@@ -13925,7 +14412,7 @@ var WorkspaceMemoryStore = class {
|
|
|
13925
14412
|
maxNotes;
|
|
13926
14413
|
maxBytes;
|
|
13927
14414
|
constructor(profileDir, limits = {}) {
|
|
13928
|
-
this.root =
|
|
14415
|
+
this.root = join25(profileDir, "memory");
|
|
13929
14416
|
this.maxNotes = limits.maxNotes ?? 200;
|
|
13930
14417
|
this.maxBytes = limits.maxBytes ?? 1024 * 1024;
|
|
13931
14418
|
}
|
|
@@ -13933,10 +14420,10 @@ var WorkspaceMemoryStore = class {
|
|
|
13933
14420
|
const directory = await this.ensureDirectory(cwdRealpath);
|
|
13934
14421
|
let noteCount = 0;
|
|
13935
14422
|
let totalBytes = 0;
|
|
13936
|
-
for (const entry of await
|
|
14423
|
+
for (const entry of await readdir11(directory, { withFileTypes: true })) {
|
|
13937
14424
|
if (entry.name === README_NAME || !entry.isFile() || entry.name.startsWith(".README.md.tmp-")) continue;
|
|
13938
14425
|
try {
|
|
13939
|
-
const info = await
|
|
14426
|
+
const info = await stat7(join25(directory, entry.name));
|
|
13940
14427
|
noteCount += 1;
|
|
13941
14428
|
totalBytes += info.size;
|
|
13942
14429
|
} catch (err) {
|
|
@@ -13957,7 +14444,7 @@ var WorkspaceMemoryStore = class {
|
|
|
13957
14444
|
/** Creates a new note; capacity reporting is advisory, not a concurrent hard quota. */
|
|
13958
14445
|
async appendNote(cwdRealpath, content) {
|
|
13959
14446
|
const directory = await this.ensureDirectory(cwdRealpath);
|
|
13960
|
-
const path4 =
|
|
14447
|
+
const path4 = join25(directory, `${randomUUID3()}.md`);
|
|
13961
14448
|
await writeFile10(path4, content, { encoding: "utf8", flag: "wx", mode: 384 });
|
|
13962
14449
|
return path4;
|
|
13963
14450
|
}
|
|
@@ -13965,11 +14452,11 @@ var WorkspaceMemoryStore = class {
|
|
|
13965
14452
|
const resolved = await realpath5(cwdRealpath);
|
|
13966
14453
|
const canonical = process.platform === "win32" ? resolved.toLowerCase() : resolved;
|
|
13967
14454
|
const hash = createHash6("sha256").update(canonical).digest("hex");
|
|
13968
|
-
const directory =
|
|
14455
|
+
const directory = join25(this.root, hash);
|
|
13969
14456
|
await mkdir17(directory, { recursive: true, mode: 448 });
|
|
13970
|
-
const readmePath =
|
|
14457
|
+
const readmePath = join25(directory, README_NAME);
|
|
13971
14458
|
try {
|
|
13972
|
-
await
|
|
14459
|
+
await stat7(readmePath);
|
|
13973
14460
|
} catch (err) {
|
|
13974
14461
|
if (err.code !== "ENOENT") throw err;
|
|
13975
14462
|
const existing = initializations.get(directory);
|
|
@@ -13983,7 +14470,7 @@ var WorkspaceMemoryStore = class {
|
|
|
13983
14470
|
});
|
|
13984
14471
|
try {
|
|
13985
14472
|
try {
|
|
13986
|
-
await
|
|
14473
|
+
await stat7(readmePath);
|
|
13987
14474
|
} catch (readmeError) {
|
|
13988
14475
|
if (readmeError.code !== "ENOENT") throw readmeError;
|
|
13989
14476
|
await writeFileAtomic(readmePath, README, { mode: 384 });
|
|
@@ -14434,6 +14921,95 @@ function fallbackReason(err) {
|
|
|
14434
14921
|
return UNKNOWN_REASON;
|
|
14435
14922
|
}
|
|
14436
14923
|
|
|
14924
|
+
// src/bot/run-progress.ts
|
|
14925
|
+
var TAIL_MAX = 240;
|
|
14926
|
+
var MAX_TOOLS_IN_FLIGHT = 8;
|
|
14927
|
+
var RunProgressRegistry = class {
|
|
14928
|
+
constructor(now = Date.now) {
|
|
14929
|
+
this.now = now;
|
|
14930
|
+
}
|
|
14931
|
+
now;
|
|
14932
|
+
live = /* @__PURE__ */ new Map();
|
|
14933
|
+
begin(input) {
|
|
14934
|
+
this.live.set(input.scope, {
|
|
14935
|
+
scope: input.scope,
|
|
14936
|
+
runId: input.runId,
|
|
14937
|
+
startedAt: input.startedAt,
|
|
14938
|
+
lastEventAt: input.startedAt,
|
|
14939
|
+
phase: "starting",
|
|
14940
|
+
sessionId: input.sessionId,
|
|
14941
|
+
threadId: input.threadId,
|
|
14942
|
+
model: input.model,
|
|
14943
|
+
cwd: input.cwd,
|
|
14944
|
+
toolsInFlight: [],
|
|
14945
|
+
toolCalls: 0,
|
|
14946
|
+
thinkingTail: "",
|
|
14947
|
+
textTail: "",
|
|
14948
|
+
usage: { inputTokens: 0, outputTokens: 0, cachedInputTokens: 0, costUsd: 0 }
|
|
14949
|
+
});
|
|
14950
|
+
}
|
|
14951
|
+
/** Fold one agent event into the live entry. No-op when the scope isn't running. */
|
|
14952
|
+
record(scope, event) {
|
|
14953
|
+
const entry = this.live.get(scope);
|
|
14954
|
+
if (!entry) return;
|
|
14955
|
+
const at = this.now();
|
|
14956
|
+
entry.lastEventAt = at;
|
|
14957
|
+
switch (event.type) {
|
|
14958
|
+
case "system":
|
|
14959
|
+
if (event.sessionId) entry.sessionId = event.sessionId;
|
|
14960
|
+
if (event.threadId) entry.threadId = event.threadId;
|
|
14961
|
+
if (event.model) entry.model = event.model;
|
|
14962
|
+
if (event.cwd) entry.cwd = event.cwd;
|
|
14963
|
+
return;
|
|
14964
|
+
case "thinking":
|
|
14965
|
+
entry.phase = "thinking";
|
|
14966
|
+
entry.thinkingTail = tail(entry.thinkingTail + event.delta);
|
|
14967
|
+
return;
|
|
14968
|
+
case "text":
|
|
14969
|
+
entry.phase = "text";
|
|
14970
|
+
entry.textTail = tail(entry.textTail + event.delta);
|
|
14971
|
+
return;
|
|
14972
|
+
case "final_text":
|
|
14973
|
+
entry.phase = "text";
|
|
14974
|
+
entry.textTail = tail(event.content);
|
|
14975
|
+
return;
|
|
14976
|
+
case "tool_use":
|
|
14977
|
+
entry.phase = "tool";
|
|
14978
|
+
entry.toolCalls += 1;
|
|
14979
|
+
entry.toolsInFlight.push({ id: event.id, name: event.name, startedAt: at });
|
|
14980
|
+
if (entry.toolsInFlight.length > MAX_TOOLS_IN_FLIGHT) entry.toolsInFlight.shift();
|
|
14981
|
+
return;
|
|
14982
|
+
case "tool_result": {
|
|
14983
|
+
const index = entry.toolsInFlight.findIndex((tool2) => tool2.id === event.id);
|
|
14984
|
+
const tool = index >= 0 ? entry.toolsInFlight.splice(index, 1)[0] : void 0;
|
|
14985
|
+
entry.lastTool = { name: tool?.name ?? "tool", ok: !event.isError, at };
|
|
14986
|
+
return;
|
|
14987
|
+
}
|
|
14988
|
+
case "usage":
|
|
14989
|
+
if (event.inputTokens !== void 0) entry.usage.inputTokens += event.inputTokens;
|
|
14990
|
+
if (event.outputTokens !== void 0) entry.usage.outputTokens += event.outputTokens;
|
|
14991
|
+
if (event.cachedInputTokens !== void 0) entry.usage.cachedInputTokens += event.cachedInputTokens;
|
|
14992
|
+
if (event.costUsd !== void 0) entry.usage.costUsd += event.costUsd;
|
|
14993
|
+
return;
|
|
14994
|
+
case "done":
|
|
14995
|
+
case "error":
|
|
14996
|
+
this.live.delete(scope);
|
|
14997
|
+
return;
|
|
14998
|
+
}
|
|
14999
|
+
}
|
|
15000
|
+
/** Drop the entry when a run ends without a terminal event (stop before EOF). */
|
|
15001
|
+
clear(scope) {
|
|
15002
|
+
this.live.delete(scope);
|
|
15003
|
+
}
|
|
15004
|
+
/** Live snapshot, or undefined when nothing is running for the scope. */
|
|
15005
|
+
active(scope) {
|
|
15006
|
+
return this.live.get(scope);
|
|
15007
|
+
}
|
|
15008
|
+
};
|
|
15009
|
+
function tail(text2) {
|
|
15010
|
+
return text2.length > TAIL_MAX ? text2.slice(-TAIL_MAX) : text2;
|
|
15011
|
+
}
|
|
15012
|
+
|
|
14437
15013
|
// src/bot/quote.ts
|
|
14438
15014
|
async function fetchQuotedContext(channel, messageId, opts) {
|
|
14439
15015
|
try {
|
|
@@ -14619,13 +15195,13 @@ function fitCotLines(lines) {
|
|
|
14619
15195
|
tailBodyLength = next;
|
|
14620
15196
|
}
|
|
14621
15197
|
for (; start <= visualLines.length; start += 1) {
|
|
14622
|
-
const
|
|
15198
|
+
const tail2 = visualLines.slice(start);
|
|
14623
15199
|
const openingFence = fenceLengthAt(visualLines, start);
|
|
14624
|
-
const closingFence = fenceLengthAfter(
|
|
15200
|
+
const closingFence = fenceLengthAfter(tail2, openingFence);
|
|
14625
15201
|
const fitted = [
|
|
14626
15202
|
omission,
|
|
14627
15203
|
...openingFence ? ["`".repeat(openingFence)] : [],
|
|
14628
|
-
...
|
|
15204
|
+
...tail2,
|
|
14629
15205
|
...closingFence ? ["`".repeat(closingFence)] : []
|
|
14630
15206
|
];
|
|
14631
15207
|
if (fitted.join("\n").length <= COT_CARD_BODY_MAX) return fitted;
|
|
@@ -15031,12 +15607,13 @@ async function startChannel(deps) {
|
|
|
15031
15607
|
const activeRuns = new ActiveRuns(notifyBusyChanged);
|
|
15032
15608
|
const chatModeCache = new ChatModeCache();
|
|
15033
15609
|
const pool = new ProcessPool(() => getMaxConcurrentRuns(controls.cfg));
|
|
15034
|
-
const
|
|
15610
|
+
const progress = new RunProgressRegistry();
|
|
15611
|
+
const executor = new RunExecutor({ agent, pool, activeRuns, progress });
|
|
15035
15612
|
const profileDir = deps.appPaths?.mediaDir ? dirname19(deps.appPaths.mediaDir) : void 0;
|
|
15036
15613
|
const contextStore = profileDir ? new ConversationContextStore(profileDir) : void 0;
|
|
15037
15614
|
const memory = profileDir ? new WorkspaceMemoryStore(profileDir) : void 0;
|
|
15038
15615
|
const appSecret = await resolveAppSecret(cfg, deps.appPaths);
|
|
15039
|
-
const callbackNonceStore = deps.appPaths?.mediaDir ? new CallbackNonceStore(
|
|
15616
|
+
const callbackNonceStore = deps.appPaths?.mediaDir ? new CallbackNonceStore(join26(dirname19(deps.appPaths.mediaDir), "callback-nonces.json")) : void 0;
|
|
15040
15617
|
await callbackNonceStore?.load();
|
|
15041
15618
|
const callbackAuth = callbackNonceStore ? new CallbackAuth({
|
|
15042
15619
|
keys: [{ version: 1, secret: appSecret }],
|
|
@@ -15065,7 +15642,7 @@ async function startChannel(deps) {
|
|
|
15065
15642
|
webhookServer,
|
|
15066
15643
|
webhookBodyLimitBytes: cfg.webhook.bodyLimitBytes,
|
|
15067
15644
|
dedupeTtlMs: cfg.webhook.dedupeTtlMs,
|
|
15068
|
-
dedupeFile: deps.appPaths?.mediaDir ?
|
|
15645
|
+
dedupeFile: deps.appPaths?.mediaDir ? join26(dirname19(deps.appPaths.mediaDir), "webhook-events.json") : void 0,
|
|
15069
15646
|
streamThrottleMs: 250,
|
|
15070
15647
|
sendMessageApiVersion: () => getSendMessageApiVersion(controls.cfg)
|
|
15071
15648
|
});
|
|
@@ -15148,7 +15725,8 @@ async function startChannel(deps) {
|
|
|
15148
15725
|
logThreadModeOverride,
|
|
15149
15726
|
lastRunCompletedAtByScope,
|
|
15150
15727
|
executor,
|
|
15151
|
-
pool
|
|
15728
|
+
pool,
|
|
15729
|
+
runProgress: progress
|
|
15152
15730
|
})
|
|
15153
15731
|
).catch((err) => log.fail("intake", err));
|
|
15154
15732
|
},
|
|
@@ -15167,6 +15745,7 @@ async function startChannel(deps) {
|
|
|
15167
15745
|
agent,
|
|
15168
15746
|
processPool: pool,
|
|
15169
15747
|
runExecutor: executor,
|
|
15748
|
+
runProgress: progress,
|
|
15170
15749
|
controls,
|
|
15171
15750
|
pending,
|
|
15172
15751
|
chatModeCache,
|
|
@@ -15310,6 +15889,7 @@ async function intakeMessage(deps) {
|
|
|
15310
15889
|
logThreadModeOverride,
|
|
15311
15890
|
executor,
|
|
15312
15891
|
pool,
|
|
15892
|
+
runProgress,
|
|
15313
15893
|
lastRunCompletedAtByScope
|
|
15314
15894
|
} = deps;
|
|
15315
15895
|
const preview = msg.content.length > 80 ? `${msg.content.slice(0, 80)}\u2026` : msg.content;
|
|
@@ -15415,10 +15995,11 @@ async function intakeMessage(deps) {
|
|
|
15415
15995
|
}),
|
|
15416
15996
|
runExecutor: executor,
|
|
15417
15997
|
processPool: pool,
|
|
15998
|
+
runProgress,
|
|
15418
15999
|
controls
|
|
15419
16000
|
});
|
|
15420
16001
|
if (handled) {
|
|
15421
|
-
const dropped = pending.cancel(scope);
|
|
16002
|
+
const dropped = isReadOnlyCommandInvocation(emsg.content, emsg.mentions) ? [] : pending.cancel(scope);
|
|
15422
16003
|
log.info("intake", "command", { scope, droppedPending: dropped.length });
|
|
15423
16004
|
return;
|
|
15424
16005
|
}
|
|
@@ -16464,7 +17045,7 @@ function startAutoUpdateScheduler(deps) {
|
|
|
16464
17045
|
|
|
16465
17046
|
// src/cli/commands/migrate-launcher.ts
|
|
16466
17047
|
import { readFile as readFile16 } from "fs/promises";
|
|
16467
|
-
import { join as
|
|
17048
|
+
import { join as join27 } from "path";
|
|
16468
17049
|
var RETRY_AFTER_MS = 24 * 60 * 60 * 1e3;
|
|
16469
17050
|
async function maybeMigrateServiceToLauncher(opts) {
|
|
16470
17051
|
const env = opts.env ?? process.env;
|
|
@@ -16472,7 +17053,7 @@ async function maybeMigrateServiceToLauncher(opts) {
|
|
|
16472
17053
|
if (!getAutoUpdateEnabled(opts.cfg)) return { migrated: false, reason: "auto-update disabled" };
|
|
16473
17054
|
if (isAutoUpdateEnvDisabled(env)) return { migrated: false, reason: "update checks disabled" };
|
|
16474
17055
|
const layout = updateLayout(opts.rootDir);
|
|
16475
|
-
const markerFile =
|
|
17056
|
+
const markerFile = join27(layout.updateDir, "launcher-migration.json");
|
|
16476
17057
|
const lastAttempt = await readFile16(markerFile, "utf8").then((text2) => {
|
|
16477
17058
|
const parsed = JSON.parse(text2);
|
|
16478
17059
|
return typeof parsed === "object" && parsed !== null && "attemptedAt" in parsed && typeof parsed.attemptedAt === "string" ? Date.parse(parsed.attemptedAt) : Number.NaN;
|
|
@@ -17965,8 +18546,8 @@ var WebhookRequestError2 = class extends Error {
|
|
|
17965
18546
|
};
|
|
17966
18547
|
|
|
17967
18548
|
// src/agent/model-discovery.ts
|
|
17968
|
-
import { createInterface as
|
|
17969
|
-
import { join as
|
|
18549
|
+
import { createInterface as createInterface8 } from "readline";
|
|
18550
|
+
import { join as join28 } from "path";
|
|
17970
18551
|
var DEFAULT_TIMEOUT_MS3 = 5e3;
|
|
17971
18552
|
async function discoverModels(agentKind, options) {
|
|
17972
18553
|
if (!options) return supportedModels(agentKind);
|
|
@@ -18082,7 +18663,7 @@ async function listCodexModels(options) {
|
|
|
18082
18663
|
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS3;
|
|
18083
18664
|
let settled = false;
|
|
18084
18665
|
return new Promise((resolve5, reject4) => {
|
|
18085
|
-
const rl =
|
|
18666
|
+
const rl = createInterface8({ input: child.stdout, crlfDelay: Infinity });
|
|
18086
18667
|
const timer = setTimeout(() => fail(new Error("codex model discovery timed out")), timeoutMs);
|
|
18087
18668
|
const cleanup = (kill) => {
|
|
18088
18669
|
if (settled) return;
|
|
@@ -18139,7 +18720,7 @@ ${JSON.stringify({ method: "model/list", id: 2, params: { includeHidden: false,
|
|
|
18139
18720
|
function spawnCodexAppServer2(options) {
|
|
18140
18721
|
const envOverrides = {};
|
|
18141
18722
|
if (options.codexHome) envOverrides.CODEX_HOME = options.codexHome;
|
|
18142
|
-
else if (options.inheritCodexHome === false) envOverrides.CODEX_HOME =
|
|
18723
|
+
else if (options.inheritCodexHome === false) envOverrides.CODEX_HOME = join28(options.profileStateDir, "codex-home");
|
|
18143
18724
|
return spawnProcess(options.binary, ["app-server", "--listen", "stdio://"], {
|
|
18144
18725
|
env: mergeProcessEnv(process.env, envOverrides),
|
|
18145
18726
|
stdio: ["pipe", "pipe", "pipe"]
|
|
@@ -18436,6 +19017,124 @@ function* translateEvent2(raw) {
|
|
|
18436
19017
|
yield* genericJsonEvent(raw);
|
|
18437
19018
|
}
|
|
18438
19019
|
|
|
19020
|
+
// src/agent/pi/side-query.ts
|
|
19021
|
+
import { mkdtemp as mkdtemp2, readdir as readdir12, readFile as readFile21, rm as rm17, stat as stat8 } from "fs/promises";
|
|
19022
|
+
import { homedir as homedir8, tmpdir as tmpdir4 } from "os";
|
|
19023
|
+
import { join as join29 } from "path";
|
|
19024
|
+
function buildPiSideQueryArgs(input) {
|
|
19025
|
+
return [
|
|
19026
|
+
"-p",
|
|
19027
|
+
"--mode",
|
|
19028
|
+
"json",
|
|
19029
|
+
"--fork",
|
|
19030
|
+
input.sessionFile,
|
|
19031
|
+
"--session-dir",
|
|
19032
|
+
input.sessionDir,
|
|
19033
|
+
"--no-tools"
|
|
19034
|
+
];
|
|
19035
|
+
}
|
|
19036
|
+
async function findPiSessionFile(sessionId, sessionsRoot = join29(homedir8(), ".pi", "agent", "sessions")) {
|
|
19037
|
+
let dirs;
|
|
19038
|
+
try {
|
|
19039
|
+
dirs = await readdir12(sessionsRoot, { withFileTypes: true });
|
|
19040
|
+
} catch {
|
|
19041
|
+
return void 0;
|
|
19042
|
+
}
|
|
19043
|
+
for (const dir of dirs) {
|
|
19044
|
+
if (!dir.isDirectory()) continue;
|
|
19045
|
+
const cwdDir = join29(sessionsRoot, dir.name);
|
|
19046
|
+
let files;
|
|
19047
|
+
try {
|
|
19048
|
+
files = await readdir12(cwdDir);
|
|
19049
|
+
} catch {
|
|
19050
|
+
continue;
|
|
19051
|
+
}
|
|
19052
|
+
const hit = files.find((file) => file.endsWith(".jsonl") && file.includes(sessionId));
|
|
19053
|
+
if (hit) return join29(cwdDir, hit);
|
|
19054
|
+
}
|
|
19055
|
+
return void 0;
|
|
19056
|
+
}
|
|
19057
|
+
async function findLatestPiSessionFile(cwd, sessionsRoot = join29(homedir8(), ".pi", "agent", "sessions")) {
|
|
19058
|
+
const candidates = [];
|
|
19059
|
+
let dirs;
|
|
19060
|
+
try {
|
|
19061
|
+
dirs = await readdir12(sessionsRoot, { withFileTypes: true });
|
|
19062
|
+
} catch {
|
|
19063
|
+
return void 0;
|
|
19064
|
+
}
|
|
19065
|
+
for (const dir of dirs) {
|
|
19066
|
+
if (!dir.isDirectory()) continue;
|
|
19067
|
+
const base = join29(sessionsRoot, dir.name);
|
|
19068
|
+
let files;
|
|
19069
|
+
try {
|
|
19070
|
+
files = await readdir12(base);
|
|
19071
|
+
} catch {
|
|
19072
|
+
continue;
|
|
19073
|
+
}
|
|
19074
|
+
for (const file of files) {
|
|
19075
|
+
if (!file.endsWith(".jsonl")) continue;
|
|
19076
|
+
const path4 = join29(base, file);
|
|
19077
|
+
try {
|
|
19078
|
+
candidates.push({ file: path4, mtime: (await stat8(path4)).mtimeMs });
|
|
19079
|
+
} catch {
|
|
19080
|
+
continue;
|
|
19081
|
+
}
|
|
19082
|
+
}
|
|
19083
|
+
}
|
|
19084
|
+
candidates.sort((a, b) => b.mtime - a.mtime);
|
|
19085
|
+
for (const candidate of candidates.slice(0, 10)) {
|
|
19086
|
+
const header = await readSessionHeader(candidate.file);
|
|
19087
|
+
if (header?.type === "session" && sameCwd(header.cwd, cwd)) return candidate.file;
|
|
19088
|
+
}
|
|
19089
|
+
return void 0;
|
|
19090
|
+
}
|
|
19091
|
+
async function readSessionHeader(file) {
|
|
19092
|
+
try {
|
|
19093
|
+
const text2 = await readFile21(file, "utf8");
|
|
19094
|
+
for (const line of text2.split("\n").slice(0, 5)) {
|
|
19095
|
+
if (!line.trim()) continue;
|
|
19096
|
+
try {
|
|
19097
|
+
return JSON.parse(line);
|
|
19098
|
+
} catch {
|
|
19099
|
+
continue;
|
|
19100
|
+
}
|
|
19101
|
+
}
|
|
19102
|
+
} catch {
|
|
19103
|
+
return void 0;
|
|
19104
|
+
}
|
|
19105
|
+
return void 0;
|
|
19106
|
+
}
|
|
19107
|
+
function sameCwd(left, right) {
|
|
19108
|
+
if (typeof left !== "string") return false;
|
|
19109
|
+
const normalize = (value) => value.replace(/\\/g, "/").replace(/\/+$/, "").toLowerCase();
|
|
19110
|
+
return normalize(left) === normalize(right);
|
|
19111
|
+
}
|
|
19112
|
+
async function runPiSideQuery(input) {
|
|
19113
|
+
const sessionFile = input.sessionId ? await findPiSessionFile(input.sessionId, input.sessionsRoot) : await findLatestPiSessionFile(input.cwd, input.sessionsRoot);
|
|
19114
|
+
if (!sessionFile) {
|
|
19115
|
+
return {
|
|
19116
|
+
text: "",
|
|
19117
|
+
error: input.sessionId ? `\u627E\u4E0D\u5230 Pi \u4F1A\u8BDD ${input.sessionId.slice(0, 8)}\u2026` : "\u4F1A\u8BDD\u5C1A\u672A\u5EFA\u7ACB"
|
|
19118
|
+
};
|
|
19119
|
+
}
|
|
19120
|
+
const sessionDir = await mkdtemp2(join29(tmpdir4(), "xiaojiu-pi-btw-"));
|
|
19121
|
+
try {
|
|
19122
|
+
const result = await runJsonlSideQuery({
|
|
19123
|
+
agent: "pi",
|
|
19124
|
+
binary: input.binary,
|
|
19125
|
+
args: buildPiSideQueryArgs({ sessionFile, sessionDir }),
|
|
19126
|
+
cwd: input.cwd,
|
|
19127
|
+
prompt: buildBtwPrompt(input.question),
|
|
19128
|
+
translate: (raw) => [...translateEvent2(raw)],
|
|
19129
|
+
signal: input.signal
|
|
19130
|
+
});
|
|
19131
|
+
return result.error ? { text: result.text, error: result.error } : { text: result.text };
|
|
19132
|
+
} finally {
|
|
19133
|
+
await rm17(sessionDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 25 }).catch(() => {
|
|
19134
|
+
});
|
|
19135
|
+
}
|
|
19136
|
+
}
|
|
19137
|
+
|
|
18439
19138
|
// src/agent/pi/adapter.ts
|
|
18440
19139
|
var PiAdapter = class extends JsonlAgentAdapter {
|
|
18441
19140
|
constructor(options = {}) {
|
|
@@ -18444,7 +19143,14 @@ var PiAdapter = class extends JsonlAgentAdapter {
|
|
|
18444
19143
|
displayName: "Pi",
|
|
18445
19144
|
binary: options.binary ?? "pi",
|
|
18446
19145
|
buildArgs: buildPiArgs,
|
|
18447
|
-
translate: (raw) => [...translateEvent2(raw)]
|
|
19146
|
+
translate: (raw) => [...translateEvent2(raw)],
|
|
19147
|
+
sideQuery: (opts) => runPiSideQuery({
|
|
19148
|
+
binary: options.binary ?? "pi",
|
|
19149
|
+
cwd: opts.cwd,
|
|
19150
|
+
...opts.sessionId ? { sessionId: opts.sessionId } : {},
|
|
19151
|
+
question: opts.question,
|
|
19152
|
+
signal: opts.signal
|
|
19153
|
+
})
|
|
18448
19154
|
});
|
|
18449
19155
|
}
|
|
18450
19156
|
};
|
|
@@ -18599,6 +19305,113 @@ function* translateEvent3(raw) {
|
|
|
18599
19305
|
yield* genericJsonEvent(raw);
|
|
18600
19306
|
}
|
|
18601
19307
|
|
|
19308
|
+
// src/agent/opencode/side-query.ts
|
|
19309
|
+
import { randomBytes as randomBytes6 } from "crypto";
|
|
19310
|
+
import { createInterface as createInterface9 } from "readline";
|
|
19311
|
+
var ANSWER_MAX = 8e3;
|
|
19312
|
+
var READY_TIMEOUT_MS = 2e4;
|
|
19313
|
+
function buildOpenCodeServeArgs() {
|
|
19314
|
+
return ["serve", "--port", "0", "--stdio"];
|
|
19315
|
+
}
|
|
19316
|
+
async function runOpenCodeSideQuery(input) {
|
|
19317
|
+
if (!input.sessionId) return { text: "", error: "\u4F1A\u8BDD\u5C1A\u672A\u5EFA\u7ACB" };
|
|
19318
|
+
const password2 = randomBytes6(32).toString("base64url");
|
|
19319
|
+
const child = spawnProcess(input.binary, buildOpenCodeServeArgs(), {
|
|
19320
|
+
cwd: input.cwd,
|
|
19321
|
+
env: { ...process.env, OPENCODE_PASSWORD: password2 },
|
|
19322
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
19323
|
+
detached: process.platform !== "win32"
|
|
19324
|
+
});
|
|
19325
|
+
let stderr = "";
|
|
19326
|
+
child.stderr.on("data", (chunk) => {
|
|
19327
|
+
if (stderr.length < 4e3) stderr += chunk.toString("utf8");
|
|
19328
|
+
});
|
|
19329
|
+
let spawnError;
|
|
19330
|
+
child.once("error", (err) => {
|
|
19331
|
+
spawnError = err instanceof Error ? err : new Error(String(err));
|
|
19332
|
+
});
|
|
19333
|
+
child.stdin.on("error", () => {
|
|
19334
|
+
});
|
|
19335
|
+
const { promise, resolve: resolve5 } = deferred();
|
|
19336
|
+
let settled = false;
|
|
19337
|
+
const settle = (result) => {
|
|
19338
|
+
if (settled) return;
|
|
19339
|
+
settled = true;
|
|
19340
|
+
clearTimeout(readyTimer);
|
|
19341
|
+
resolve5(result);
|
|
19342
|
+
};
|
|
19343
|
+
const onAbort = () => {
|
|
19344
|
+
killProcessTree(child, true);
|
|
19345
|
+
settle({ text: "", error: "aborted" });
|
|
19346
|
+
};
|
|
19347
|
+
input.signal.addEventListener("abort", onAbort, { once: true });
|
|
19348
|
+
const readyTimer = setTimeout(() => {
|
|
19349
|
+
killProcessTree(child, true);
|
|
19350
|
+
settle({ text: "", error: "opencode serve \u672A\u5C31\u7EEA" });
|
|
19351
|
+
}, READY_TIMEOUT_MS);
|
|
19352
|
+
const rl = createInterface9({ input: child.stdout, crlfDelay: Infinity });
|
|
19353
|
+
let started = false;
|
|
19354
|
+
rl.on("line", (line) => {
|
|
19355
|
+
if (started) return;
|
|
19356
|
+
const trimmed = line.trim();
|
|
19357
|
+
if (!trimmed.startsWith("{")) return;
|
|
19358
|
+
let url;
|
|
19359
|
+
try {
|
|
19360
|
+
const parsed = JSON.parse(trimmed);
|
|
19361
|
+
if (typeof parsed.url === "string") url = parsed.url;
|
|
19362
|
+
} catch {
|
|
19363
|
+
return;
|
|
19364
|
+
}
|
|
19365
|
+
if (!url) return;
|
|
19366
|
+
started = true;
|
|
19367
|
+
clearTimeout(readyTimer);
|
|
19368
|
+
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) }));
|
|
19369
|
+
});
|
|
19370
|
+
child.once("exit", (code) => {
|
|
19371
|
+
rl.close();
|
|
19372
|
+
if (!started) {
|
|
19373
|
+
const detail = stderr.trim().replace(/\s+/g, " ").slice(0, 300);
|
|
19374
|
+
settle({
|
|
19375
|
+
text: "",
|
|
19376
|
+
error: spawnError?.message ?? (detail || `opencode serve \u9000\u51FA\uFF08code ${code ?? "null"}\uFF09`)
|
|
19377
|
+
});
|
|
19378
|
+
}
|
|
19379
|
+
});
|
|
19380
|
+
try {
|
|
19381
|
+
return await promise;
|
|
19382
|
+
} finally {
|
|
19383
|
+
input.signal.removeEventListener("abort", onAbort);
|
|
19384
|
+
rl.close();
|
|
19385
|
+
child.stdin.end();
|
|
19386
|
+
if (child.exitCode === null && child.signalCode === null) killProcessTree(child, true);
|
|
19387
|
+
}
|
|
19388
|
+
}
|
|
19389
|
+
async function requestGenerate(input) {
|
|
19390
|
+
const authorization = `Basic ${Buffer.from(`opencode:${input.password}`).toString("base64")}`;
|
|
19391
|
+
const response = await fetch(`${input.url}/api/session/${encodeURIComponent(input.sessionId)}/generate`, {
|
|
19392
|
+
method: "POST",
|
|
19393
|
+
headers: {
|
|
19394
|
+
authorization,
|
|
19395
|
+
"content-type": "application/json",
|
|
19396
|
+
"x-opencode-directory": input.cwd
|
|
19397
|
+
},
|
|
19398
|
+
body: JSON.stringify({ prompt: input.question })
|
|
19399
|
+
});
|
|
19400
|
+
const body = await response.text();
|
|
19401
|
+
if (!response.ok) {
|
|
19402
|
+
return { text: "", error: `opencode generate ${response.status}: ${body.trim().slice(0, 300)}` };
|
|
19403
|
+
}
|
|
19404
|
+
let text2;
|
|
19405
|
+
try {
|
|
19406
|
+
const parsed = JSON.parse(body);
|
|
19407
|
+
if (typeof parsed.data?.text === "string") text2 = parsed.data.text;
|
|
19408
|
+
} catch {
|
|
19409
|
+
return { text: "", error: `opencode generate \u8FD4\u56DE\u4E86\u975E JSON \u5185\u5BB9: ${body.trim().slice(0, 200)}` };
|
|
19410
|
+
}
|
|
19411
|
+
const answer = text2?.trim().slice(0, ANSWER_MAX);
|
|
19412
|
+
return answer ? { text: answer } : { text: "", error: "opencode \u6CA1\u6709\u8FD4\u56DE\u7B54\u6848" };
|
|
19413
|
+
}
|
|
19414
|
+
|
|
18602
19415
|
// src/agent/opencode/adapter.ts
|
|
18603
19416
|
var OpenCodeAdapter = class extends JsonlAgentAdapter {
|
|
18604
19417
|
constructor(options = {}) {
|
|
@@ -18608,7 +19421,14 @@ var OpenCodeAdapter = class extends JsonlAgentAdapter {
|
|
|
18608
19421
|
binary: options.binary ?? "opencode",
|
|
18609
19422
|
buildArgs: buildOpenCodeArgs,
|
|
18610
19423
|
buildEnv: buildOpenCodeEnv,
|
|
18611
|
-
translate: (raw) => [...translateEvent3(raw)]
|
|
19424
|
+
translate: (raw) => [...translateEvent3(raw)],
|
|
19425
|
+
sideQuery: (opts) => runOpenCodeSideQuery({
|
|
19426
|
+
binary: options.binary ?? "opencode",
|
|
19427
|
+
cwd: opts.cwd,
|
|
19428
|
+
...opts.sessionId ? { sessionId: opts.sessionId } : {},
|
|
19429
|
+
question: opts.question,
|
|
19430
|
+
signal: opts.signal
|
|
19431
|
+
})
|
|
18612
19432
|
});
|
|
18613
19433
|
}
|
|
18614
19434
|
};
|
|
@@ -18679,6 +19499,168 @@ function* translateEvent4(raw) {
|
|
|
18679
19499
|
yield* genericJsonEvent(raw);
|
|
18680
19500
|
}
|
|
18681
19501
|
|
|
19502
|
+
// src/agent/omp/side-query.ts
|
|
19503
|
+
import { readFile as readFile22, readdir as readdir13, stat as stat9 } from "fs/promises";
|
|
19504
|
+
import { homedir as homedir9 } from "os";
|
|
19505
|
+
import { join as join30 } from "path";
|
|
19506
|
+
import { createInterface as createInterface10 } from "readline";
|
|
19507
|
+
var ANSWER_MAX2 = 8e3;
|
|
19508
|
+
var READY_TIMEOUT_MS2 = 2e4;
|
|
19509
|
+
function buildOmpRpcArgs(input) {
|
|
19510
|
+
return ["--mode", "rpc", "--resume=" + input.sessionId, "--cwd", input.cwd, "--no-ui"];
|
|
19511
|
+
}
|
|
19512
|
+
async function findLatestOmpSessionId(cwd, sessionsRoot = join30(homedir9(), ".omp", "agent", "sessions")) {
|
|
19513
|
+
let dirs;
|
|
19514
|
+
try {
|
|
19515
|
+
dirs = await readdir13(sessionsRoot, { withFileTypes: true });
|
|
19516
|
+
} catch {
|
|
19517
|
+
return void 0;
|
|
19518
|
+
}
|
|
19519
|
+
const candidates = [];
|
|
19520
|
+
for (const dir of dirs) {
|
|
19521
|
+
if (!dir.isDirectory()) continue;
|
|
19522
|
+
const base = join30(sessionsRoot, dir.name);
|
|
19523
|
+
let files;
|
|
19524
|
+
try {
|
|
19525
|
+
files = await readdir13(base);
|
|
19526
|
+
} catch {
|
|
19527
|
+
continue;
|
|
19528
|
+
}
|
|
19529
|
+
for (const file of files) {
|
|
19530
|
+
if (!file.endsWith(".jsonl")) continue;
|
|
19531
|
+
const path4 = join30(base, file);
|
|
19532
|
+
try {
|
|
19533
|
+
candidates.push({ file: path4, mtime: (await stat9(path4)).mtimeMs });
|
|
19534
|
+
} catch {
|
|
19535
|
+
continue;
|
|
19536
|
+
}
|
|
19537
|
+
}
|
|
19538
|
+
}
|
|
19539
|
+
candidates.sort((a, b) => b.mtime - a.mtime);
|
|
19540
|
+
for (const candidate of candidates.slice(0, 10)) {
|
|
19541
|
+
let header;
|
|
19542
|
+
try {
|
|
19543
|
+
for (const line of (await readFile22(candidate.file, "utf8")).split("\n").slice(0, 5)) {
|
|
19544
|
+
if (!line.trim()) continue;
|
|
19545
|
+
try {
|
|
19546
|
+
header = JSON.parse(line);
|
|
19547
|
+
break;
|
|
19548
|
+
} catch {
|
|
19549
|
+
continue;
|
|
19550
|
+
}
|
|
19551
|
+
}
|
|
19552
|
+
} catch {
|
|
19553
|
+
continue;
|
|
19554
|
+
}
|
|
19555
|
+
if (header?.type === "session" && typeof header.id === "string" && sameCwd2(header.cwd, cwd)) {
|
|
19556
|
+
return header.id;
|
|
19557
|
+
}
|
|
19558
|
+
}
|
|
19559
|
+
return void 0;
|
|
19560
|
+
}
|
|
19561
|
+
function sameCwd2(left, right) {
|
|
19562
|
+
if (typeof left !== "string") return false;
|
|
19563
|
+
const normalize = (value) => value.replace(/\\/g, "/").replace(/\/+$/, "").toLowerCase();
|
|
19564
|
+
return normalize(left) === normalize(right);
|
|
19565
|
+
}
|
|
19566
|
+
async function runOmpSideQuery(input) {
|
|
19567
|
+
const sessionId = input.sessionId ?? await findLatestOmpSessionId(input.cwd, input.sessionsRoot);
|
|
19568
|
+
if (!sessionId) return { text: "", error: "\u4F1A\u8BDD\u5C1A\u672A\u5EFA\u7ACB" };
|
|
19569
|
+
const child = spawnProcess(input.binary, buildOmpRpcArgs({ sessionId, cwd: input.cwd }), {
|
|
19570
|
+
cwd: input.cwd,
|
|
19571
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
19572
|
+
detached: process.platform !== "win32"
|
|
19573
|
+
});
|
|
19574
|
+
let stderr = "";
|
|
19575
|
+
child.stderr.on("data", (chunk) => {
|
|
19576
|
+
if (stderr.length < 4e3) stderr += chunk.toString("utf8");
|
|
19577
|
+
});
|
|
19578
|
+
let spawnError;
|
|
19579
|
+
child.once("error", (err) => {
|
|
19580
|
+
spawnError = err instanceof Error ? err : new Error(String(err));
|
|
19581
|
+
});
|
|
19582
|
+
child.stdin.on("error", () => {
|
|
19583
|
+
});
|
|
19584
|
+
const { promise, resolve: resolve5 } = deferred();
|
|
19585
|
+
let settled = false;
|
|
19586
|
+
const settle = (result) => {
|
|
19587
|
+
if (settled) return;
|
|
19588
|
+
settled = true;
|
|
19589
|
+
clearTimeout(deadline);
|
|
19590
|
+
resolve5(result);
|
|
19591
|
+
};
|
|
19592
|
+
const onAbort = () => {
|
|
19593
|
+
killProcessTree(child, true);
|
|
19594
|
+
settle({ text: "", error: "aborted" });
|
|
19595
|
+
};
|
|
19596
|
+
input.signal.addEventListener("abort", onAbort, { once: true });
|
|
19597
|
+
const deadline = setTimeout(() => {
|
|
19598
|
+
killProcessTree(child, true);
|
|
19599
|
+
settle({ text: "", error: "timeout" });
|
|
19600
|
+
}, READY_TIMEOUT_MS2 + 7e4);
|
|
19601
|
+
let ready = false;
|
|
19602
|
+
let answer = "";
|
|
19603
|
+
const rl = createInterface10({ input: child.stdout, crlfDelay: Infinity });
|
|
19604
|
+
rl.on("line", (line) => {
|
|
19605
|
+
const trimmed = line.trim();
|
|
19606
|
+
if (!trimmed) return;
|
|
19607
|
+
let frame;
|
|
19608
|
+
try {
|
|
19609
|
+
frame = JSON.parse(trimmed);
|
|
19610
|
+
} catch {
|
|
19611
|
+
return;
|
|
19612
|
+
}
|
|
19613
|
+
if (frame.type === "ready") {
|
|
19614
|
+
ready = true;
|
|
19615
|
+
try {
|
|
19616
|
+
child.stdin.write(JSON.stringify({ id: "btw", type: "btw", question: input.question }) + "\n");
|
|
19617
|
+
} catch {
|
|
19618
|
+
}
|
|
19619
|
+
return;
|
|
19620
|
+
}
|
|
19621
|
+
if (frame.type === "response" && frame.success === false) {
|
|
19622
|
+
settle({ text: "", error: frame.error || "omp \u62D2\u7EDD\u4E86\u65C1\u8DEF\u63D0\u95EE" });
|
|
19623
|
+
return;
|
|
19624
|
+
}
|
|
19625
|
+
if (frame.type === "btw_record") {
|
|
19626
|
+
const record5 = frame.record ?? {};
|
|
19627
|
+
if (record5.answer) answer = record5.answer;
|
|
19628
|
+
if (record5.status === "complete") {
|
|
19629
|
+
settle({ text: answer.trim().slice(0, ANSWER_MAX2) });
|
|
19630
|
+
} else if (record5.status === "error" || record5.status === "cancelled" || record5.status === "interrupted") {
|
|
19631
|
+
settle({ text: answer.trim().slice(0, ANSWER_MAX2), error: record5.error || `btw ${record5.status}` });
|
|
19632
|
+
}
|
|
19633
|
+
}
|
|
19634
|
+
});
|
|
19635
|
+
rl.on("close", () => {
|
|
19636
|
+
if (settled) return;
|
|
19637
|
+
const detail = stderr.trim().replace(/\s+/g, " ").slice(0, 300);
|
|
19638
|
+
if (answer.trim()) {
|
|
19639
|
+
settle({ text: answer.trim().slice(0, ANSWER_MAX2) });
|
|
19640
|
+
return;
|
|
19641
|
+
}
|
|
19642
|
+
settle({
|
|
19643
|
+
text: "",
|
|
19644
|
+
error: spawnError?.message ?? (detail || `omp rpc \u63D0\u524D\u9000\u51FA\uFF08code ${child.exitCode ?? "null"}\uFF09`)
|
|
19645
|
+
});
|
|
19646
|
+
});
|
|
19647
|
+
const readyTimer = setTimeout(() => {
|
|
19648
|
+
if (!ready) {
|
|
19649
|
+
killProcessTree(child, true);
|
|
19650
|
+
settle({ text: "", error: "omp rpc \u672A\u5C31\u7EEA" });
|
|
19651
|
+
}
|
|
19652
|
+
}, READY_TIMEOUT_MS2);
|
|
19653
|
+
try {
|
|
19654
|
+
return await promise;
|
|
19655
|
+
} finally {
|
|
19656
|
+
clearTimeout(readyTimer);
|
|
19657
|
+
input.signal.removeEventListener("abort", onAbort);
|
|
19658
|
+
rl.close();
|
|
19659
|
+
child.stdin.end();
|
|
19660
|
+
if (child.exitCode === null && child.signalCode === null) killProcessTree(child, true);
|
|
19661
|
+
}
|
|
19662
|
+
}
|
|
19663
|
+
|
|
18682
19664
|
// src/agent/omp/adapter.ts
|
|
18683
19665
|
var OmpAdapter = class extends JsonlAgentAdapter {
|
|
18684
19666
|
constructor(options = {}) {
|
|
@@ -18687,7 +19669,14 @@ var OmpAdapter = class extends JsonlAgentAdapter {
|
|
|
18687
19669
|
displayName: "OMP",
|
|
18688
19670
|
binary: options.binary ?? "omp",
|
|
18689
19671
|
buildArgs: buildOmpArgs,
|
|
18690
|
-
translate: (raw) => [...translateEvent4(raw)]
|
|
19672
|
+
translate: (raw) => [...translateEvent4(raw)],
|
|
19673
|
+
sideQuery: (opts) => runOmpSideQuery({
|
|
19674
|
+
binary: options.binary ?? "omp",
|
|
19675
|
+
cwd: opts.cwd,
|
|
19676
|
+
...opts.sessionId ? { sessionId: opts.sessionId } : {},
|
|
19677
|
+
question: opts.question,
|
|
19678
|
+
signal: opts.signal
|
|
19679
|
+
})
|
|
18691
19680
|
});
|
|
18692
19681
|
}
|
|
18693
19682
|
};
|
|
@@ -18809,7 +19798,8 @@ var ManagedProfile = class {
|
|
|
18809
19798
|
version,
|
|
18810
19799
|
registryFile: this.appPaths.userRegistryFile,
|
|
18811
19800
|
webhookPort: this.cfg.webhook.port,
|
|
18812
|
-
webhookPath: await advertisedWebhookPath(this.appPaths.profile, this.cfg, this.configPath)
|
|
19801
|
+
webhookPath: await advertisedWebhookPath(this.appPaths.profile, this.cfg, this.configPath),
|
|
19802
|
+
launcherPid: launcherPidFromEnv()
|
|
18813
19803
|
});
|
|
18814
19804
|
setStdoutProfileUid(this.profile, this.entry.id);
|
|
18815
19805
|
this.controls = this.makeControls(this.appPaths, this.cfg, this.profileConfig);
|
|
@@ -19302,13 +20292,13 @@ async function collectProfileLogDirs(rootDir) {
|
|
|
19302
20292
|
const dirs = [];
|
|
19303
20293
|
let profiles;
|
|
19304
20294
|
try {
|
|
19305
|
-
profiles = await
|
|
20295
|
+
profiles = await readdir14(join31(rootDir, "profiles"));
|
|
19306
20296
|
} catch {
|
|
19307
20297
|
return dirs;
|
|
19308
20298
|
}
|
|
19309
20299
|
for (const profile2 of profiles) {
|
|
19310
|
-
dirs.push(
|
|
19311
|
-
dirs.push(
|
|
20300
|
+
dirs.push(join31(rootDir, "profiles", profile2, "logs"));
|
|
20301
|
+
dirs.push(join31(rootDir, "profiles", profile2, "logs", "daemon"));
|
|
19312
20302
|
}
|
|
19313
20303
|
return dirs;
|
|
19314
20304
|
}
|
|
@@ -19401,7 +20391,7 @@ async function confirmStopRuntimeLockProcess(err) {
|
|
|
19401
20391
|
`\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
20392
|
);
|
|
19403
20393
|
}
|
|
19404
|
-
const rl =
|
|
20394
|
+
const rl = createInterface11({ input: process.stdin, output: process.stdout });
|
|
19405
20395
|
try {
|
|
19406
20396
|
const answer = (await new Promise(
|
|
19407
20397
|
(resolve5) => rl.question("\u662F\u5426\u505C\u6B62\u65E7\u8FDB\u7A0B\u5E76\u91CD\u65B0\u542F\u52A8? [y/N]: ", resolve5)
|