@xopcai/xopc 0.0.138 → 0.0.140
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser-ext/manifest.json +1 -1
- package/dist/extensions/telegram/xopc.extension.json +1 -1
- package/dist/gateway/static/root/assets/{agent-avatar-dicebear-CIsGDJzd.js → agent-avatar-dicebear-DtONoxBN.js} +1 -1
- package/dist/gateway/static/root/assets/{agents-fX97A6iN.js → agents-Dl9EWnUh.js} +1 -1
- package/dist/gateway/static/root/assets/{app-management-settings-panel-ByM4Bzwm.js → app-management-settings-panel-BRBxLECY.js} +1 -1
- package/dist/gateway/static/root/assets/{appearance-settings-BF_poRd3.js → appearance-settings-ChvyuSEt.js} +1 -1
- package/dist/gateway/static/root/assets/{apps-page-BssdA5Qc.js → apps-page-DgHWTnjs.js} +1 -1
- package/dist/gateway/static/root/assets/{archive-plugin-DJaYoyGn.js → archive-plugin-CdIoagem.js} +1 -1
- package/dist/gateway/static/root/assets/{attachment-load-xx6dBaZU.js → attachment-load-Ch411Kht.js} +1 -1
- package/dist/gateway/static/root/assets/{automation-suggestion-card-BMvGqYob.js → automation-suggestion-card-SVq27yw2.js} +1 -1
- package/dist/gateway/static/root/assets/{automations-page-Dip8ZFmx.js → automations-page-CFt5Ik4q.js} +1 -1
- package/dist/gateway/static/root/assets/{binary-plugins-CuPLWibr.js → binary-plugins-D8cV-emn.js} +1 -1
- package/dist/gateway/static/root/assets/{block-editor-bzfvlJnh.js → block-editor-CXDkby6y.js} +1 -1
- package/dist/gateway/static/root/assets/{browser-settings-page-lbx_8Dku.js → browser-settings-page-ColJPwer.js} +1 -1
- package/dist/gateway/static/root/assets/{capability-presets-api-X4Imbf8n.js → capability-presets-api-DLxI--Ge.js} +1 -1
- package/dist/gateway/static/root/assets/{capability-presets-settings-panel-v9JgKjJu.js → capability-presets-settings-panel-DKyRbnlH.js} +1 -1
- package/dist/gateway/static/root/assets/{channels-settings-CED7Oy5Y.js → channels-settings-BDLHV3Jx.js} +1 -1
- package/dist/gateway/static/root/assets/{connectors-page-BMfp0jWL.js → connectors-page-CA752gY8.js} +1 -1
- package/dist/gateway/static/root/assets/{desktop-pet-oTig6qFO.js → desktop-pet-Bz9ommjr.js} +1 -1
- package/dist/gateway/static/root/assets/{desktop-pet-settings-DXJiPL_H.js → desktop-pet-settings-BnLgxgoR.js} +1 -1
- package/dist/gateway/static/root/assets/{directory-picker-path-field-CltkXSR2.js → directory-picker-path-field-DLsCwFaf.js} +1 -1
- package/dist/gateway/static/root/assets/{dreaming-settings-CYrZQxoL.js → dreaming-settings-BzkF1-XT.js} +1 -1
- package/dist/gateway/static/root/assets/{extension-debug-page-C-4BOy1R.js → extension-debug-page-CdERvf3L.js} +1 -1
- package/dist/gateway/static/root/assets/{extension-page-C8nMpXqh.js → extension-page-D1fz474Z.js} +1 -1
- package/dist/gateway/static/root/assets/{extension-settings-page-CXWYOwka.js → extension-settings-page-DoQMkNOK.js} +1 -1
- package/dist/gateway/static/root/assets/{gateway-config-api-B3TGdim5.js → gateway-config-api-Rygo8UAs.js} +1 -1
- package/dist/gateway/static/root/assets/{gateway-settings-D7tOnGAJ.js → gateway-settings-kb8KIeQL.js} +1 -1
- package/dist/gateway/static/root/assets/{goal-create-dialog-BL_cRshf.js → goal-create-dialog-DVAHnifk.js} +1 -1
- package/dist/gateway/static/root/assets/{goal-detail-page-T1vg6Ng_.js → goal-detail-page-BuOEQZn_.js} +1 -1
- package/dist/gateway/static/root/assets/{goals-config-api-D-WZWhP2.js → goals-config-api-BuY6-l0a.js} +1 -1
- package/dist/gateway/static/root/assets/{goals-page-1vzWXl5W.js → goals-page-WV4cHvD-.js} +1 -1
- package/dist/gateway/static/root/assets/{goals-settings-DgGwvLVC.js → goals-settings-DoH5fZWo.js} +1 -1
- package/dist/gateway/static/root/assets/{heartbeat-settings-yh0bEIwQ.js → heartbeat-settings-BqDs48B-.js} +1 -1
- package/dist/gateway/static/root/assets/{index-NwiCnzI-.js → index-CrPRlGMg.js} +6 -6
- package/dist/gateway/static/root/assets/{keyboard-shortcuts-settings-CnxRFbgA.js → keyboard-shortcuts-settings-D51yogNZ.js} +1 -1
- package/dist/gateway/static/root/assets/{logs-page-DebnvTpD.js → logs-page-CL22jleU.js} +1 -1
- package/dist/gateway/static/root/assets/{markdown-split-BU69Nof8.js → markdown-split-CSt32FWE.js} +1 -1
- package/dist/gateway/static/root/assets/{media-plugins-CDs7OvWt.js → media-plugins-ByItHxBj.js} +1 -1
- package/dist/gateway/static/root/assets/{models-hub-panel-Ca_jy26S.js → models-hub-panel-BkV9hDc-.js} +1 -1
- package/dist/gateway/static/root/assets/{notes-page-DTpeaI65.js → notes-page-BK9yydrL.js} +1 -1
- package/dist/gateway/static/root/assets/{notes-workbench-uKMYsjUU.js → notes-workbench-Dd0v-hK2.js} +2 -2
- package/dist/gateway/static/root/assets/{page-tabs-CROo8Vgz.js → page-tabs-DOfMaq_L.js} +1 -1
- package/dist/gateway/static/root/assets/{preview-open-alternatives-BxsS9i1G.js → preview-open-alternatives-BArxASu7.js} +1 -1
- package/dist/gateway/static/root/assets/{project-detail-page-BWKOhshy.js → project-detail-page-DSPhB3do.js} +1 -1
- package/dist/gateway/static/root/assets/{projects-page-CoowiCLe.js → projects-page-C-fZk1f7.js} +1 -1
- package/dist/gateway/static/root/assets/{remote-access-hub-CiOaX1wd.js → remote-access-hub-BGaVc3t7.js} +1 -1
- package/dist/gateway/static/root/assets/{save-bar-controls-B4N17dMG.js → save-bar-controls-BRxlkhG8.js} +1 -1
- package/dist/gateway/static/root/assets/{schedule-field-ClJzQ2vz.js → schedule-field-BzM1iyOc.js} +1 -1
- package/dist/gateway/static/root/assets/{schema-form-oZvQUfDg.js → schema-form-ChVcm0DX.js} +1 -1
- package/dist/gateway/static/root/assets/{sessions-page-Sx9Gc0cv.js → sessions-page-DbnzgQOP.js} +1 -1
- package/dist/gateway/static/root/assets/settings-advanced-gate-CuDBoz5k.js +1 -0
- package/dist/gateway/static/root/assets/{settings-collapsible-section-B0kOLXUf.js → settings-collapsible-section-BcD9xrvY.js} +1 -1
- package/dist/gateway/static/root/assets/{settings-form-section-DoVPlVFd.js → settings-form-section-Cu30CXVl.js} +1 -1
- package/dist/gateway/static/root/assets/{settings-loading-skeleton-C7J96bLc.js → settings-loading-skeleton-Cfd37IYb.js} +1 -1
- package/dist/gateway/static/root/assets/{settings-page-CXiAByF0.js → settings-page-EINHyzLo.js} +1 -1
- package/dist/gateway/static/root/assets/{settings-page-layout-R-6ArlMI.js → settings-page-layout-C15zixct.js} +1 -1
- package/dist/gateway/static/root/assets/{setup-status-panel-Drz23n9l.js → setup-status-panel-Bu7SdpD4.js} +1 -1
- package/dist/gateway/static/root/assets/{share-preview-page-Bn1umseg.js → share-preview-page-CjjAFV-v.js} +1 -1
- package/dist/gateway/static/root/assets/{shares-settings-Bb-pcMWg.js → shares-settings-06IYvwDt.js} +1 -1
- package/dist/gateway/static/root/assets/skill-reload-api-0ODH0DXl.js +1 -0
- package/dist/gateway/static/root/assets/{skills-page-B6cDPqkk.js → skills-page-3W2-wDyO.js} +1 -1
- package/dist/gateway/static/root/assets/{system-settings-panel-CtEddAy-.js → system-settings-panel-DlQMtzPf.js} +1 -1
- package/dist/gateway/static/root/assets/{typed-models-lib-BkhSnYq7.js → typed-models-lib-BS1BwExE.js} +1 -1
- package/dist/gateway/static/root/assets/{user-profile-settings-panel-BssTVOBS.js → user-profile-settings-panel-B7RCdmSp.js} +1 -1
- package/dist/gateway/static/root/assets/{utils-CI3ywKLT.js → utils-BrhEgVaa.js} +1 -1
- package/dist/gateway/static/root/assets/{voice-api-key-field-DXMEGw9O.js → voice-api-key-field-BPn1ZEga.js} +1 -1
- package/dist/gateway/static/root/assets/{work-item-detail-page-DsFqU0tK.js → work-item-detail-page-BQGTTsz1.js} +1 -1
- package/dist/gateway/static/root/assets/{workflow-run-setup-panel-DImBi-m6.js → workflow-run-setup-panel-na-N4jZ6.js} +1 -1
- package/dist/gateway/static/root/assets/{workflow-start-dialog-DuPpKAAc.js → workflow-start-dialog-BZCY7N42.js} +1 -1
- package/dist/gateway/static/root/assets/{workflows-page-DfTVzTNY.js → workflows-page-CjeVDs4h.js} +1 -1
- package/dist/gateway/static/root/index.html +1 -1
- package/dist/package.js +1 -1
- package/dist/src/agent/code-intelligence/binary.d.ts +14 -0
- package/dist/src/agent/code-intelligence/binary.js +344 -12
- package/dist/src/agent/code-intelligence/binary.js.map +1 -1
- package/dist/src/agent/code-intelligence/index.d.ts +1 -1
- package/dist/src/agent/code-intelligence/index.js +2 -2
- package/dist/src/agent/code-intelligence/runtime.js +2 -2
- package/dist/src/agent/code-intelligence/runtime.js.map +1 -1
- package/package.json +2 -2
- package/dist/gateway/static/root/assets/settings-advanced-gate-CnbVdze4.js +0 -1
- package/dist/gateway/static/root/assets/skill-reload-api-DE9HCHct.js +0 -1
|
@@ -1,11 +1,75 @@
|
|
|
1
|
+
import { resolveStateDir } from "../../config/paths-state.js";
|
|
2
|
+
import { createLogger } from "../../utils/logger/index.js";
|
|
3
|
+
import { init_logger } from "../../utils/logger.js";
|
|
4
|
+
import { init_paths, resolveBinDir } from "../../config/paths.js";
|
|
1
5
|
import { createRequire } from "node:module";
|
|
6
|
+
import { tmpdir } from "node:os";
|
|
2
7
|
import { dirname, join, resolve } from "node:path";
|
|
3
|
-
import { accessSync, constants, existsSync, realpathSync } from "node:fs";
|
|
8
|
+
import { accessSync, chmodSync, constants, copyFileSync, createReadStream, createWriteStream, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
9
|
+
import { execFile } from "node:child_process";
|
|
10
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
11
|
+
import { promisify } from "node:util";
|
|
12
|
+
import { Readable } from "node:stream";
|
|
13
|
+
import lockfile from "proper-lockfile";
|
|
14
|
+
import { pipeline } from "node:stream/promises";
|
|
4
15
|
//#region src/agent/code-intelligence/binary.ts
|
|
16
|
+
init_paths();
|
|
17
|
+
init_logger();
|
|
5
18
|
const require = createRequire(import.meta.url);
|
|
19
|
+
const log = createLogger("CodeIntelligenceBinary");
|
|
20
|
+
const CBM_VERSION = "0.9.0";
|
|
21
|
+
const CACHE_SCHEMA_VERSION = 1;
|
|
22
|
+
const DOWNLOAD_TIMEOUT_MS = 2 * 6e4;
|
|
23
|
+
const RELEASE_BASE_URL = `https://github.com/DeusData/codebase-memory-mcp/releases/download/v${CBM_VERSION}`;
|
|
24
|
+
const execFileAsync = promisify(execFile);
|
|
6
25
|
function binaryName() {
|
|
7
26
|
return process.platform === "win32" ? "codebase-memory-mcp.exe" : "codebase-memory-mcp";
|
|
8
27
|
}
|
|
28
|
+
function platformName() {
|
|
29
|
+
switch (process.platform) {
|
|
30
|
+
case "darwin": return "darwin";
|
|
31
|
+
case "linux": return "linux";
|
|
32
|
+
case "win32": return "windows";
|
|
33
|
+
default: throw new Error(`Code intelligence is not supported on ${process.platform}`);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
function architectureName() {
|
|
37
|
+
switch (process.arch) {
|
|
38
|
+
case "arm64": return "arm64";
|
|
39
|
+
case "x64": return "amd64";
|
|
40
|
+
default: throw new Error(`Code intelligence is not supported on ${process.arch}`);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
function platformKey() {
|
|
44
|
+
return `${platformName()}-${architectureName()}`;
|
|
45
|
+
}
|
|
46
|
+
function archiveName() {
|
|
47
|
+
const platform = platformName();
|
|
48
|
+
const extension = platform === "windows" ? "zip" : "tar.gz";
|
|
49
|
+
const linuxPortable = platform === "linux" ? "-portable" : "";
|
|
50
|
+
return `codebase-memory-mcp-${platform}-${architectureName()}${linuxPortable}.${extension}`;
|
|
51
|
+
}
|
|
52
|
+
function releaseUrl() {
|
|
53
|
+
return `${RELEASE_BASE_URL}/${archiveName()}`;
|
|
54
|
+
}
|
|
55
|
+
function archiveExtension() {
|
|
56
|
+
return platformName() === "windows" ? "zip" : "tar.gz";
|
|
57
|
+
}
|
|
58
|
+
function cacheVersionRoot() {
|
|
59
|
+
return join(resolveBinDir(), "codebase-memory-mcp", `v${CBM_VERSION}`);
|
|
60
|
+
}
|
|
61
|
+
function cacheDir() {
|
|
62
|
+
return join(cacheVersionRoot(), platformKey());
|
|
63
|
+
}
|
|
64
|
+
function cacheBinaryPath() {
|
|
65
|
+
return join(cacheDir(), binaryName());
|
|
66
|
+
}
|
|
67
|
+
function cacheManifestPath(dir = cacheDir()) {
|
|
68
|
+
return join(dir, "manifest.json");
|
|
69
|
+
}
|
|
70
|
+
function legacyManagedBinaryPath() {
|
|
71
|
+
return join(resolveStateDir(), "code-intelligence", "bin", `v${CBM_VERSION}`, platformKey(), binaryName());
|
|
72
|
+
}
|
|
9
73
|
function isUsableBinary(path) {
|
|
10
74
|
if (!existsSync(path)) return false;
|
|
11
75
|
try {
|
|
@@ -15,6 +79,52 @@ function isUsableBinary(path) {
|
|
|
15
79
|
return false;
|
|
16
80
|
}
|
|
17
81
|
}
|
|
82
|
+
function expectedSha256(checksums, filename) {
|
|
83
|
+
for (const line of checksums.split(/\r?\n/)) {
|
|
84
|
+
const match = /^([a-f0-9]{64})\s+\*?(.+)$/i.exec(line.trim());
|
|
85
|
+
if (match?.[2] === filename) return match[1].toLowerCase();
|
|
86
|
+
}
|
|
87
|
+
throw new Error(`checksums.txt does not contain ${filename}`);
|
|
88
|
+
}
|
|
89
|
+
async function sha256(path) {
|
|
90
|
+
const hash = createHash("sha256");
|
|
91
|
+
await new Promise((resolvePromise, reject) => {
|
|
92
|
+
const input = createReadStream(path);
|
|
93
|
+
input.on("data", (chunk) => hash.update(chunk));
|
|
94
|
+
input.once("error", reject);
|
|
95
|
+
input.once("end", resolvePromise);
|
|
96
|
+
});
|
|
97
|
+
return hash.digest("hex");
|
|
98
|
+
}
|
|
99
|
+
function readManagedManifest(dir = cacheDir()) {
|
|
100
|
+
try {
|
|
101
|
+
const parsed = JSON.parse(readFileSync(cacheManifestPath(dir), "utf8"));
|
|
102
|
+
if (parsed.schemaVersion !== CACHE_SCHEMA_VERSION || parsed.component !== "codebase-memory-mcp" || parsed.cbmVersion !== CBM_VERSION || parsed.platform !== platformName() || parsed.arch !== architectureName() || parsed.binaryName !== binaryName() || typeof parsed.binarySha256 !== "string" || typeof parsed.binarySize !== "number") return;
|
|
103
|
+
return parsed;
|
|
104
|
+
} catch {
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
function resolveSharedCachedBinary() {
|
|
109
|
+
const binary = cacheBinaryPath();
|
|
110
|
+
const manifest = readManagedManifest();
|
|
111
|
+
if (!manifest || !isUsableBinary(binary)) return void 0;
|
|
112
|
+
try {
|
|
113
|
+
return statSync(binary).size === manifest.binarySize ? realpathSync(binary) : void 0;
|
|
114
|
+
} catch {
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
async function verifySharedCachedBinary() {
|
|
119
|
+
const binary = resolveSharedCachedBinary();
|
|
120
|
+
const manifest = readManagedManifest();
|
|
121
|
+
if (!binary || !manifest) return void 0;
|
|
122
|
+
try {
|
|
123
|
+
return await sha256(binary) === manifest.binarySha256 ? binary : void 0;
|
|
124
|
+
} catch {
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
18
128
|
function packageBinaryPath() {
|
|
19
129
|
try {
|
|
20
130
|
return join(dirname(require.resolve("codebase-memory-mcp/package.json")), "bin", binaryName());
|
|
@@ -22,21 +132,243 @@ function packageBinaryPath() {
|
|
|
22
132
|
return;
|
|
23
133
|
}
|
|
24
134
|
}
|
|
25
|
-
function
|
|
26
|
-
const
|
|
27
|
-
|
|
28
|
-
explicitPath,
|
|
29
|
-
process.env.XOPC_CBM_BINARY,
|
|
30
|
-
resourcesPath ? join(resourcesPath, "bin", binaryName()) : void 0,
|
|
31
|
-
packageBinaryPath()
|
|
32
|
-
].filter((value) => Boolean(value?.trim()));
|
|
33
|
-
for (const candidate of candidates) {
|
|
135
|
+
function overrideBinaryPath(explicitPath) {
|
|
136
|
+
for (const candidate of [explicitPath, process.env.XOPC_CBM_BINARY]) {
|
|
137
|
+
if (!candidate?.trim()) continue;
|
|
34
138
|
const absolute = resolve(candidate);
|
|
35
139
|
if (isUsableBinary(absolute)) return realpathSync(absolute);
|
|
36
140
|
}
|
|
37
|
-
|
|
141
|
+
}
|
|
142
|
+
function bundledBinaryCandidates() {
|
|
143
|
+
const bundledPath = process.env.XOPC_CBM_BUNDLED_PATH?.trim();
|
|
144
|
+
const bundledManifestPath = process.env.XOPC_CBM_BUNDLED_MANIFEST_PATH?.trim();
|
|
145
|
+
const resourcesPath = process.resourcesPath;
|
|
146
|
+
const resourcePath = resourcesPath ? join(resourcesPath, "bin", binaryName()) : void 0;
|
|
147
|
+
const packagePath = packageBinaryPath();
|
|
148
|
+
const candidates = [];
|
|
149
|
+
if (bundledPath) candidates.push({
|
|
150
|
+
path: bundledPath,
|
|
151
|
+
source: "electron-bundle",
|
|
152
|
+
manifestPath: bundledManifestPath || join(dirname(bundledPath), "codebase-memory-mcp.manifest.json")
|
|
153
|
+
});
|
|
154
|
+
if (resourcePath && resourcePath !== bundledPath) candidates.push({
|
|
155
|
+
path: resourcePath,
|
|
156
|
+
source: "electron-bundle",
|
|
157
|
+
manifestPath: join(dirname(resourcePath), "codebase-memory-mcp.manifest.json")
|
|
158
|
+
});
|
|
159
|
+
if (packagePath) candidates.push({
|
|
160
|
+
path: packagePath,
|
|
161
|
+
source: "package-bundle"
|
|
162
|
+
});
|
|
163
|
+
candidates.push({
|
|
164
|
+
path: legacyManagedBinaryPath(),
|
|
165
|
+
source: "legacy-cache"
|
|
166
|
+
});
|
|
167
|
+
return candidates;
|
|
168
|
+
}
|
|
169
|
+
async function verifyBundledSource(candidate) {
|
|
170
|
+
if (!isUsableBinary(candidate.path)) throw new Error(`source binary is unavailable at ${candidate.path}`);
|
|
171
|
+
if (candidate.source !== "electron-bundle") return;
|
|
172
|
+
if (!candidate.manifestPath) throw new Error("Electron CBM manifest path is missing");
|
|
173
|
+
let manifest;
|
|
174
|
+
try {
|
|
175
|
+
manifest = JSON.parse(readFileSync(candidate.manifestPath, "utf8"));
|
|
176
|
+
} catch (error) {
|
|
177
|
+
throw new Error(`Electron CBM manifest is unreadable: ${error instanceof Error ? error.message : String(error)}`);
|
|
178
|
+
}
|
|
179
|
+
if (manifest.cbmVersion !== CBM_VERSION || manifest.platform !== platformName() || manifest.arch !== architectureName() || !/^[a-f0-9]{64}$/i.test(manifest.binarySha256)) throw new Error("Electron CBM manifest does not match this runtime");
|
|
180
|
+
const actual = await sha256(candidate.path);
|
|
181
|
+
if (actual !== manifest.binarySha256.toLowerCase()) throw new Error(`Electron CBM checksum mismatch: expected ${manifest.binarySha256}, got ${actual}`);
|
|
182
|
+
}
|
|
183
|
+
async function withCacheLock(fn) {
|
|
184
|
+
const versionRoot = cacheVersionRoot();
|
|
185
|
+
mkdirSync(versionRoot, { recursive: true });
|
|
186
|
+
const release = await lockfile.lock(versionRoot, {
|
|
187
|
+
realpath: false,
|
|
188
|
+
lockfilePath: join(versionRoot, `.${platformKey()}.install.lock`),
|
|
189
|
+
stale: 10 * 6e4,
|
|
190
|
+
retries: {
|
|
191
|
+
retries: 30,
|
|
192
|
+
factor: 1.2,
|
|
193
|
+
minTimeout: 100,
|
|
194
|
+
maxTimeout: 1e3
|
|
195
|
+
}
|
|
196
|
+
});
|
|
197
|
+
try {
|
|
198
|
+
return await fn();
|
|
199
|
+
} finally {
|
|
200
|
+
await release();
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
function cleanupStaleStaging(versionRoot) {
|
|
204
|
+
const prefix = `.${platformKey()}.staging-`;
|
|
205
|
+
const cutoff = Date.now() - 60 * 6e4;
|
|
206
|
+
try {
|
|
207
|
+
for (const entry of readdirSync(versionRoot)) {
|
|
208
|
+
if (!entry.startsWith(prefix)) continue;
|
|
209
|
+
const path = join(versionRoot, entry);
|
|
210
|
+
if (statSync(path).mtimeMs < cutoff) rmSync(path, {
|
|
211
|
+
recursive: true,
|
|
212
|
+
force: true
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
} catch {}
|
|
216
|
+
}
|
|
217
|
+
async function installInSharedCache(source, populate) {
|
|
218
|
+
const versionRoot = cacheVersionRoot();
|
|
219
|
+
const targetDir = cacheDir();
|
|
220
|
+
const stagingDir = join(versionRoot, `.${platformKey()}.staging-${process.pid}-${randomBytes(6).toString("hex")}`);
|
|
221
|
+
const stagingBinary = join(stagingDir, binaryName());
|
|
222
|
+
mkdirSync(stagingDir, { recursive: true });
|
|
223
|
+
try {
|
|
224
|
+
await populate(stagingBinary);
|
|
225
|
+
if (!isUsableBinary(stagingBinary)) throw new Error("staged codebase-memory-mcp binary is not executable");
|
|
226
|
+
if (process.platform !== "win32") chmodSync(stagingBinary, 493);
|
|
227
|
+
const binarySha256 = await sha256(stagingBinary);
|
|
228
|
+
const manifest = {
|
|
229
|
+
schemaVersion: CACHE_SCHEMA_VERSION,
|
|
230
|
+
component: "codebase-memory-mcp",
|
|
231
|
+
cbmVersion: CBM_VERSION,
|
|
232
|
+
platform: platformName(),
|
|
233
|
+
arch: architectureName(),
|
|
234
|
+
binaryName: binaryName(),
|
|
235
|
+
binarySha256,
|
|
236
|
+
binarySize: statSync(stagingBinary).size,
|
|
237
|
+
source,
|
|
238
|
+
installedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
239
|
+
};
|
|
240
|
+
writeFileSync(cacheManifestPath(stagingDir), `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
|
|
241
|
+
rmSync(targetDir, {
|
|
242
|
+
recursive: true,
|
|
243
|
+
force: true
|
|
244
|
+
});
|
|
245
|
+
renameSync(stagingDir, targetDir);
|
|
246
|
+
return realpathSync(cacheBinaryPath());
|
|
247
|
+
} catch (error) {
|
|
248
|
+
rmSync(stagingDir, {
|
|
249
|
+
recursive: true,
|
|
250
|
+
force: true
|
|
251
|
+
});
|
|
252
|
+
throw error;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
/** Resolve an explicit, shared, or bundled binary synchronously when already present. */
|
|
256
|
+
function resolveCodebaseMemoryBinary(explicitPath) {
|
|
257
|
+
const overridden = overrideBinaryPath(explicitPath);
|
|
258
|
+
if (overridden) return overridden;
|
|
259
|
+
const shared = resolveSharedCachedBinary();
|
|
260
|
+
if (shared) return shared;
|
|
261
|
+
for (const candidate of bundledBinaryCandidates()) {
|
|
262
|
+
const absolute = resolve(candidate.path);
|
|
263
|
+
if (isUsableBinary(absolute)) return realpathSync(absolute);
|
|
264
|
+
}
|
|
265
|
+
throw new Error("codebase-memory-mcp binary is unavailable");
|
|
266
|
+
}
|
|
267
|
+
/** Download and checksum-verify the CBM executable into a caller-provided path. */
|
|
268
|
+
async function downloadCodebaseMemoryBinary(destination, options = {}) {
|
|
269
|
+
const fetchImplementation = options.fetchImplementation ?? fetch;
|
|
270
|
+
const timeoutMs = options.timeoutMs ?? DOWNLOAD_TIMEOUT_MS;
|
|
271
|
+
const temporaryPath = `${destination}.${process.pid}.part`;
|
|
272
|
+
const abortController = new AbortController();
|
|
273
|
+
const tempDir = mkdtempSync(join(tmpdir(), "xopc-cbm-"));
|
|
274
|
+
const archivePath = join(tempDir, `cbm.${archiveExtension()}`);
|
|
275
|
+
let timedOut = false;
|
|
276
|
+
let rejectTimeout;
|
|
277
|
+
const timeoutPromise = new Promise((_resolve, reject) => {
|
|
278
|
+
rejectTimeout = reject;
|
|
279
|
+
});
|
|
280
|
+
const timer = setTimeout(() => {
|
|
281
|
+
timedOut = true;
|
|
282
|
+
abortController.abort();
|
|
283
|
+
rejectTimeout?.(/* @__PURE__ */ new Error(`download timed out after ${timeoutMs}ms`));
|
|
284
|
+
}, timeoutMs);
|
|
285
|
+
try {
|
|
286
|
+
mkdirSync(dirname(destination), { recursive: true });
|
|
287
|
+
rmSync(temporaryPath, { force: true });
|
|
288
|
+
await Promise.race([(async () => {
|
|
289
|
+
const checksumsResponse = await fetchImplementation(`${RELEASE_BASE_URL}/checksums.txt`, {
|
|
290
|
+
redirect: "follow",
|
|
291
|
+
signal: abortController.signal
|
|
292
|
+
});
|
|
293
|
+
if (!checksumsResponse.ok) throw new Error(`GitHub Releases returned HTTP ${checksumsResponse.status} for checksums.txt`);
|
|
294
|
+
const expectedChecksum = expectedSha256(await checksumsResponse.text(), archiveName());
|
|
295
|
+
const response = await fetchImplementation(releaseUrl(), {
|
|
296
|
+
redirect: "follow",
|
|
297
|
+
signal: abortController.signal
|
|
298
|
+
});
|
|
299
|
+
if (!response.ok) throw new Error(`GitHub Releases returned HTTP ${response.status}`);
|
|
300
|
+
if (!response.body) throw new Error("GitHub Releases returned an empty response body");
|
|
301
|
+
await pipeline(Readable.fromWeb(response.body), createWriteStream(archivePath, { mode: 384 }));
|
|
302
|
+
const actualChecksum = await sha256(archivePath);
|
|
303
|
+
if (actualChecksum !== expectedChecksum) throw new Error(`checksum mismatch for ${archiveName()}: expected ${expectedChecksum}, got ${actualChecksum}`);
|
|
304
|
+
if (archiveExtension() === "tar.gz") await execFileAsync("tar", [
|
|
305
|
+
"-xzf",
|
|
306
|
+
archivePath,
|
|
307
|
+
"-C",
|
|
308
|
+
tempDir,
|
|
309
|
+
"--no-same-owner"
|
|
310
|
+
]);
|
|
311
|
+
else await execFileAsync("powershell", [
|
|
312
|
+
"-NoProfile",
|
|
313
|
+
"-Command",
|
|
314
|
+
`Expand-Archive -Path '${archivePath}' -DestinationPath '${tempDir}' -Force`
|
|
315
|
+
]);
|
|
316
|
+
const extracted = join(tempDir, binaryName());
|
|
317
|
+
if (!isUsableBinary(extracted)) throw new Error(`binary was not present after extracting ${archiveExtension()} archive`);
|
|
318
|
+
copyFileSync(extracted, temporaryPath);
|
|
319
|
+
})(), timeoutPromise]);
|
|
320
|
+
if (timedOut) throw new Error(`download timed out after ${timeoutMs}ms`);
|
|
321
|
+
if (process.platform !== "win32") chmodSync(temporaryPath, 493);
|
|
322
|
+
renameSync(temporaryPath, destination);
|
|
323
|
+
return realpathSync(destination);
|
|
324
|
+
} catch (error) {
|
|
325
|
+
const reason = timedOut ? `download timed out after ${timeoutMs}ms` : error instanceof Error ? error.message : String(error);
|
|
326
|
+
throw new Error(`Unable to download codebase-memory-mcp from GitHub Releases: ${reason}. Check network access or set XOPC_CBM_BINARY to a trusted executable.`);
|
|
327
|
+
} finally {
|
|
328
|
+
clearTimeout(timer);
|
|
329
|
+
rmSync(temporaryPath, { force: true });
|
|
330
|
+
rmSync(tempDir, {
|
|
331
|
+
recursive: true,
|
|
332
|
+
force: true
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
/**
|
|
337
|
+
* Resolve a shared, versioned user cache. Electron seeds it from its bundled binary;
|
|
338
|
+
* CLI seeds it from a verified release download. This keeps both surfaces on one binary.
|
|
339
|
+
*/
|
|
340
|
+
async function ensureCodebaseMemoryBinary(explicitPath) {
|
|
341
|
+
const overridden = overrideBinaryPath(explicitPath);
|
|
342
|
+
if (overridden) return overridden;
|
|
343
|
+
const cached = await verifySharedCachedBinary();
|
|
344
|
+
if (cached) return cached;
|
|
345
|
+
return withCacheLock(async () => {
|
|
346
|
+
cleanupStaleStaging(cacheVersionRoot());
|
|
347
|
+
const afterLock = await verifySharedCachedBinary();
|
|
348
|
+
if (afterLock) return afterLock;
|
|
349
|
+
for (const candidate of bundledBinaryCandidates()) try {
|
|
350
|
+
await verifyBundledSource(candidate);
|
|
351
|
+
return await installInSharedCache(candidate.source, async (destination) => {
|
|
352
|
+
copyFileSync(candidate.path, destination);
|
|
353
|
+
});
|
|
354
|
+
} catch (error) {
|
|
355
|
+
log.warn({
|
|
356
|
+
err: error,
|
|
357
|
+
source: candidate.source,
|
|
358
|
+
path: candidate.path
|
|
359
|
+
}, "Code intelligence binary source was not usable");
|
|
360
|
+
}
|
|
361
|
+
log.info({
|
|
362
|
+
destination: cacheBinaryPath(),
|
|
363
|
+
version: CBM_VERSION,
|
|
364
|
+
timeoutMs: DOWNLOAD_TIMEOUT_MS
|
|
365
|
+
}, "Downloading code intelligence binary into shared cache");
|
|
366
|
+
return installInSharedCache("github-release", async (destination) => {
|
|
367
|
+
await downloadCodebaseMemoryBinary(destination);
|
|
368
|
+
});
|
|
369
|
+
});
|
|
38
370
|
}
|
|
39
371
|
//#endregion
|
|
40
|
-
export { resolveCodebaseMemoryBinary };
|
|
372
|
+
export { downloadCodebaseMemoryBinary, ensureCodebaseMemoryBinary, resolveCodebaseMemoryBinary };
|
|
41
373
|
|
|
42
374
|
//# sourceMappingURL=binary.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"binary.js","names":[],"sources":["../../../../src/agent/code-intelligence/binary.ts"],"sourcesContent":["import { createRequire } from 'node:module';\nimport { accessSync, constants, existsSync, realpathSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\n\nconst require = createRequire(import.meta.url);\n\nfunction binaryName(): string {\n return process.platform === 'win32' ? 'codebase-memory-mcp.exe' : 'codebase-memory-mcp';\n}\n\nfunction isUsableBinary(path: string): boolean {\n if (!existsSync(path)) return false;\n try {\n accessSync(path, process.platform === 'win32' ? constants.F_OK : constants.X_OK);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction packageBinaryPath(): string | undefined {\n try {\n const packageJson = require.resolve('codebase-memory-mcp/package.json');\n return join(dirname(packageJson), 'bin', binaryName());\n } catch {\n return undefined;\n }\n}\n\nexport function resolveCodebaseMemoryBinary(explicitPath?: string): string {\n const resourcesPath = (process as NodeJS.Process & { resourcesPath?: string }).resourcesPath;\n const candidates = [\n explicitPath,\n process.env.XOPC_CBM_BINARY,\n resourcesPath ? join(resourcesPath, 'bin', binaryName()) : undefined,\n packageBinaryPath(),\n ].filter((value): value is string => Boolean(value?.trim()));\n\n for (const candidate of candidates) {\n const absolute = resolve(candidate);\n if (isUsableBinary(absolute)) {\n return realpathSync(absolute);\n }\n }\n\n throw new Error(\n `codebase-memory-mcp binary is unavailable; checked ${candidates.join(', ') || 'no candidate paths'}`,\n );\n}\n"],"mappings":";;;;AAIA,MAAM,UAAU,cAAc,OAAO,KAAK,IAAI;AAE9C,SAAS,aAAqB;AAC5B,QAAO,QAAQ,aAAa,UAAU,4BAA4B;;AAGpE,SAAS,eAAe,MAAuB;AAC7C,KAAI,CAAC,WAAW,KAAK,CAAE,QAAO;AAC9B,KAAI;AACF,aAAW,MAAM,QAAQ,aAAa,UAAU,UAAU,OAAO,UAAU,KAAK;AAChF,SAAO;SACD;AACN,SAAO;;;AAIX,SAAS,oBAAwC;AAC/C,KAAI;AAEF,SAAO,KAAK,QADQ,QAAQ,QAAQ,mCACL,CAAC,EAAE,OAAO,YAAY,CAAC;SAChD;AACN;;;AAIJ,SAAgB,4BAA4B,cAA+B;CACzE,MAAM,gBAAiB,QAAwD;CAC/E,MAAM,aAAa;EACjB;EACA,QAAQ,IAAI;EACZ,gBAAgB,KAAK,eAAe,OAAO,YAAY,CAAC,GAAG,KAAA;EAC3D,mBAAmB;EACpB,CAAC,QAAQ,UAA2B,QAAQ,OAAO,MAAM,CAAC,CAAC;AAE5D,MAAK,MAAM,aAAa,YAAY;EAClC,MAAM,WAAW,QAAQ,UAAU;AACnC,MAAI,eAAe,SAAS,CAC1B,QAAO,aAAa,SAAS;;AAIjC,OAAM,IAAI,MACR,sDAAsD,WAAW,KAAK,KAAK,IAAI,uBAChF"}
|
|
1
|
+
{"version":3,"file":"binary.js","names":[],"sources":["../../../../src/agent/code-intelligence/binary.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport { createHash, randomBytes } from 'node:crypto';\nimport {\n accessSync,\n chmodSync,\n constants,\n copyFileSync,\n createReadStream,\n createWriteStream,\n existsSync,\n mkdirSync,\n mkdtempSync,\n readdirSync,\n readFileSync,\n realpathSync,\n renameSync,\n rmSync,\n statSync,\n writeFileSync,\n} from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { tmpdir } from 'node:os';\nimport { dirname, join, resolve } from 'node:path';\nimport { Readable } from 'node:stream';\nimport { pipeline } from 'node:stream/promises';\nimport { promisify } from 'node:util';\n\nimport lockfile from 'proper-lockfile';\n\nimport { resolveBinDir, resolveStateDir } from '../../config/paths.js';\nimport { createLogger } from '../../utils/logger.js';\n\nconst require = createRequire(import.meta.url);\nconst log = createLogger('CodeIntelligenceBinary');\n\nconst CBM_VERSION = '0.9.0';\nconst CACHE_SCHEMA_VERSION = 1;\nconst DOWNLOAD_TIMEOUT_MS = 2 * 60_000;\nconst RELEASE_BASE_URL = `https://github.com/DeusData/codebase-memory-mcp/releases/download/v${CBM_VERSION}`;\nconst execFileAsync = promisify(execFile);\n\ntype FetchImplementation = typeof fetch;\ntype ManagedBinarySource = 'github-release' | 'electron-bundle' | 'package-bundle' | 'legacy-cache';\n\ninterface ManagedBinaryManifest {\n schemaVersion: number;\n component: 'codebase-memory-mcp';\n cbmVersion: string;\n platform: string;\n arch: string;\n binaryName: string;\n binarySha256: string;\n binarySize: number;\n source: ManagedBinarySource;\n installedAt: string;\n}\n\ninterface BundledBinaryManifest {\n cbmVersion: string;\n platform: string;\n arch: string;\n binarySha256: string;\n}\n\ninterface BinarySourceCandidate {\n path: string;\n source: Exclude<ManagedBinarySource, 'github-release'>;\n manifestPath?: string;\n}\n\nexport interface DownloadCodebaseMemoryBinaryOptions {\n fetchImplementation?: FetchImplementation;\n timeoutMs?: number;\n}\n\nfunction binaryName(): string {\n return process.platform === 'win32' ? 'codebase-memory-mcp.exe' : 'codebase-memory-mcp';\n}\n\nfunction platformName(): string {\n switch (process.platform) {\n case 'darwin':\n return 'darwin';\n case 'linux':\n return 'linux';\n case 'win32':\n return 'windows';\n default:\n throw new Error(`Code intelligence is not supported on ${process.platform}`);\n }\n}\n\nfunction architectureName(): string {\n switch (process.arch) {\n case 'arm64':\n return 'arm64';\n case 'x64':\n return 'amd64';\n default:\n throw new Error(`Code intelligence is not supported on ${process.arch}`);\n }\n}\n\nfunction platformKey(): string {\n return `${platformName()}-${architectureName()}`;\n}\n\nfunction archiveName(): string {\n const platform = platformName();\n const extension = platform === 'windows' ? 'zip' : 'tar.gz';\n const linuxPortable = platform === 'linux' ? '-portable' : '';\n return `codebase-memory-mcp-${platform}-${architectureName()}${linuxPortable}.${extension}`;\n}\n\nfunction releaseUrl(): string {\n return `${RELEASE_BASE_URL}/${archiveName()}`;\n}\n\nfunction archiveExtension(): 'zip' | 'tar.gz' {\n return platformName() === 'windows' ? 'zip' : 'tar.gz';\n}\n\nfunction cacheVersionRoot(): string {\n return join(resolveBinDir(), 'codebase-memory-mcp', `v${CBM_VERSION}`);\n}\n\nfunction cacheDir(): string {\n return join(cacheVersionRoot(), platformKey());\n}\n\nfunction cacheBinaryPath(): string {\n return join(cacheDir(), binaryName());\n}\n\nfunction cacheManifestPath(dir = cacheDir()): string {\n return join(dir, 'manifest.json');\n}\n\nfunction legacyManagedBinaryPath(): string {\n return join(\n resolveStateDir(),\n 'code-intelligence',\n 'bin',\n `v${CBM_VERSION}`,\n platformKey(),\n binaryName(),\n );\n}\n\nfunction isUsableBinary(path: string): boolean {\n if (!existsSync(path)) return false;\n try {\n accessSync(path, process.platform === 'win32' ? constants.F_OK : constants.X_OK);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction expectedSha256(checksums: string, filename: string): string {\n for (const line of checksums.split(/\\r?\\n/)) {\n const match = /^([a-f0-9]{64})\\s+\\*?(.+)$/i.exec(line.trim());\n if (match?.[2] === filename) return match[1].toLowerCase();\n }\n throw new Error(`checksums.txt does not contain ${filename}`);\n}\n\nasync function sha256(path: string): Promise<string> {\n const hash = createHash('sha256');\n await new Promise<void>((resolvePromise, reject) => {\n const input = createReadStream(path);\n input.on('data', (chunk: Buffer) => hash.update(chunk));\n input.once('error', reject);\n input.once('end', resolvePromise);\n });\n return hash.digest('hex');\n}\n\nfunction readManagedManifest(dir = cacheDir()): ManagedBinaryManifest | undefined {\n try {\n const parsed = JSON.parse(readFileSync(cacheManifestPath(dir), 'utf8')) as Partial<ManagedBinaryManifest>;\n if (\n parsed.schemaVersion !== CACHE_SCHEMA_VERSION ||\n parsed.component !== 'codebase-memory-mcp' ||\n parsed.cbmVersion !== CBM_VERSION ||\n parsed.platform !== platformName() ||\n parsed.arch !== architectureName() ||\n parsed.binaryName !== binaryName() ||\n typeof parsed.binarySha256 !== 'string' ||\n typeof parsed.binarySize !== 'number'\n ) {\n return undefined;\n }\n return parsed as ManagedBinaryManifest;\n } catch {\n return undefined;\n }\n}\n\nfunction resolveSharedCachedBinary(): string | undefined {\n const binary = cacheBinaryPath();\n const manifest = readManagedManifest();\n if (!manifest || !isUsableBinary(binary)) return undefined;\n try {\n return statSync(binary).size === manifest.binarySize ? realpathSync(binary) : undefined;\n } catch {\n return undefined;\n }\n}\n\nasync function verifySharedCachedBinary(): Promise<string | undefined> {\n const binary = resolveSharedCachedBinary();\n const manifest = readManagedManifest();\n if (!binary || !manifest) return undefined;\n try {\n return (await sha256(binary)) === manifest.binarySha256 ? binary : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction packageBinaryPath(): string | undefined {\n try {\n const packageJson = require.resolve('codebase-memory-mcp/package.json');\n return join(dirname(packageJson), 'bin', binaryName());\n } catch {\n return undefined;\n }\n}\n\nfunction overrideBinaryPath(explicitPath?: string): string | undefined {\n for (const candidate of [explicitPath, process.env.XOPC_CBM_BINARY]) {\n if (!candidate?.trim()) continue;\n const absolute = resolve(candidate);\n if (isUsableBinary(absolute)) return realpathSync(absolute);\n }\n return undefined;\n}\n\nfunction bundledBinaryCandidates(): BinarySourceCandidate[] {\n const bundledPath = process.env.XOPC_CBM_BUNDLED_PATH?.trim();\n const bundledManifestPath = process.env.XOPC_CBM_BUNDLED_MANIFEST_PATH?.trim();\n const resourcesPath = (process as NodeJS.Process & { resourcesPath?: string }).resourcesPath;\n const resourcePath = resourcesPath ? join(resourcesPath, 'bin', binaryName()) : undefined;\n const packagePath = packageBinaryPath();\n const candidates: BinarySourceCandidate[] = [];\n\n if (bundledPath) {\n candidates.push({\n path: bundledPath,\n source: 'electron-bundle',\n manifestPath: bundledManifestPath || join(dirname(bundledPath), 'codebase-memory-mcp.manifest.json'),\n });\n }\n if (resourcePath && resourcePath !== bundledPath) {\n candidates.push({\n path: resourcePath,\n source: 'electron-bundle',\n manifestPath: join(dirname(resourcePath), 'codebase-memory-mcp.manifest.json'),\n });\n }\n if (packagePath) candidates.push({ path: packagePath, source: 'package-bundle' });\n candidates.push({ path: legacyManagedBinaryPath(), source: 'legacy-cache' });\n return candidates;\n}\n\nasync function verifyBundledSource(candidate: BinarySourceCandidate): Promise<void> {\n if (!isUsableBinary(candidate.path)) {\n throw new Error(`source binary is unavailable at ${candidate.path}`);\n }\n if (candidate.source !== 'electron-bundle') return;\n if (!candidate.manifestPath) throw new Error('Electron CBM manifest path is missing');\n\n let manifest: BundledBinaryManifest;\n try {\n manifest = JSON.parse(readFileSync(candidate.manifestPath, 'utf8')) as BundledBinaryManifest;\n } catch (error) {\n throw new Error(\n `Electron CBM manifest is unreadable: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n if (\n manifest.cbmVersion !== CBM_VERSION ||\n manifest.platform !== platformName() ||\n manifest.arch !== architectureName() ||\n !/^[a-f0-9]{64}$/i.test(manifest.binarySha256)\n ) {\n throw new Error('Electron CBM manifest does not match this runtime');\n }\n const actual = await sha256(candidate.path);\n if (actual !== manifest.binarySha256.toLowerCase()) {\n throw new Error(`Electron CBM checksum mismatch: expected ${manifest.binarySha256}, got ${actual}`);\n }\n}\n\nasync function withCacheLock<T>(fn: () => Promise<T>): Promise<T> {\n const versionRoot = cacheVersionRoot();\n mkdirSync(versionRoot, { recursive: true });\n const release = await lockfile.lock(versionRoot, {\n realpath: false,\n lockfilePath: join(versionRoot, `.${platformKey()}.install.lock`),\n stale: 10 * 60_000,\n retries: { retries: 30, factor: 1.2, minTimeout: 100, maxTimeout: 1_000 },\n });\n try {\n return await fn();\n } finally {\n await release();\n }\n}\n\nfunction cleanupStaleStaging(versionRoot: string): void {\n const prefix = `.${platformKey()}.staging-`;\n const cutoff = Date.now() - 60 * 60_000;\n try {\n for (const entry of readdirSync(versionRoot)) {\n if (!entry.startsWith(prefix)) continue;\n const path = join(versionRoot, entry);\n if (statSync(path).mtimeMs < cutoff) rmSync(path, { recursive: true, force: true });\n }\n } catch {\n // Best-effort cleanup; installation remains safe under the cache lock.\n }\n}\n\nasync function installInSharedCache(\n source: ManagedBinarySource,\n populate: (destination: string) => Promise<void>,\n): Promise<string> {\n const versionRoot = cacheVersionRoot();\n const targetDir = cacheDir();\n const stagingDir = join(versionRoot, `.${platformKey()}.staging-${process.pid}-${randomBytes(6).toString('hex')}`);\n const stagingBinary = join(stagingDir, binaryName());\n mkdirSync(stagingDir, { recursive: true });\n\n try {\n await populate(stagingBinary);\n if (!isUsableBinary(stagingBinary)) {\n throw new Error('staged codebase-memory-mcp binary is not executable');\n }\n if (process.platform !== 'win32') chmodSync(stagingBinary, 0o755);\n const binarySha256 = await sha256(stagingBinary);\n const manifest: ManagedBinaryManifest = {\n schemaVersion: CACHE_SCHEMA_VERSION,\n component: 'codebase-memory-mcp',\n cbmVersion: CBM_VERSION,\n platform: platformName(),\n arch: architectureName(),\n binaryName: binaryName(),\n binarySha256,\n binarySize: statSync(stagingBinary).size,\n source,\n installedAt: new Date().toISOString(),\n };\n writeFileSync(cacheManifestPath(stagingDir), `${JSON.stringify(manifest, null, 2)}\\n`, 'utf8');\n\n rmSync(targetDir, { recursive: true, force: true });\n renameSync(stagingDir, targetDir);\n return realpathSync(cacheBinaryPath());\n } catch (error) {\n rmSync(stagingDir, { recursive: true, force: true });\n throw error;\n }\n}\n\n/** Resolve an explicit, shared, or bundled binary synchronously when already present. */\nexport function resolveCodebaseMemoryBinary(explicitPath?: string): string {\n const overridden = overrideBinaryPath(explicitPath);\n if (overridden) return overridden;\n\n const shared = resolveSharedCachedBinary();\n if (shared) return shared;\n\n for (const candidate of bundledBinaryCandidates()) {\n const absolute = resolve(candidate.path);\n if (isUsableBinary(absolute)) return realpathSync(absolute);\n }\n\n throw new Error('codebase-memory-mcp binary is unavailable');\n}\n\n/** Download and checksum-verify the CBM executable into a caller-provided path. */\nexport async function downloadCodebaseMemoryBinary(\n destination: string,\n options: DownloadCodebaseMemoryBinaryOptions = {},\n): Promise<string> {\n const fetchImplementation = options.fetchImplementation ?? fetch;\n const timeoutMs = options.timeoutMs ?? DOWNLOAD_TIMEOUT_MS;\n const temporaryPath = `${destination}.${process.pid}.part`;\n const abortController = new AbortController();\n const tempDir = mkdtempSync(join(tmpdir(), 'xopc-cbm-'));\n const archivePath = join(tempDir, `cbm.${archiveExtension()}`);\n let timedOut = false;\n let rejectTimeout: ((error: Error) => void) | undefined;\n const timeoutPromise = new Promise<never>((_resolve, reject) => {\n rejectTimeout = reject;\n });\n const timer = setTimeout(() => {\n timedOut = true;\n abortController.abort();\n rejectTimeout?.(new Error(`download timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n\n try {\n mkdirSync(dirname(destination), { recursive: true });\n rmSync(temporaryPath, { force: true });\n await Promise.race([\n (async () => {\n const checksumsResponse = await fetchImplementation(`${RELEASE_BASE_URL}/checksums.txt`, {\n redirect: 'follow',\n signal: abortController.signal,\n });\n if (!checksumsResponse.ok) {\n throw new Error(`GitHub Releases returned HTTP ${checksumsResponse.status} for checksums.txt`);\n }\n const expectedChecksum = expectedSha256(await checksumsResponse.text(), archiveName());\n const response = await fetchImplementation(releaseUrl(), {\n redirect: 'follow',\n signal: abortController.signal,\n });\n if (!response.ok) throw new Error(`GitHub Releases returned HTTP ${response.status}`);\n if (!response.body) throw new Error('GitHub Releases returned an empty response body');\n\n await pipeline(\n Readable.fromWeb(response.body as import('node:stream/web').ReadableStream),\n createWriteStream(archivePath, { mode: 0o600 }),\n );\n const actualChecksum = await sha256(archivePath);\n if (actualChecksum !== expectedChecksum) {\n throw new Error(\n `checksum mismatch for ${archiveName()}: expected ${expectedChecksum}, got ${actualChecksum}`,\n );\n }\n if (archiveExtension() === 'tar.gz') {\n await execFileAsync('tar', ['-xzf', archivePath, '-C', tempDir, '--no-same-owner']);\n } else {\n await execFileAsync('powershell', [\n '-NoProfile',\n '-Command',\n `Expand-Archive -Path '${archivePath}' -DestinationPath '${tempDir}' -Force`,\n ]);\n }\n\n const extracted = join(tempDir, binaryName());\n if (!isUsableBinary(extracted)) {\n throw new Error(`binary was not present after extracting ${archiveExtension()} archive`);\n }\n copyFileSync(extracted, temporaryPath);\n })(),\n timeoutPromise,\n ]);\n if (timedOut) throw new Error(`download timed out after ${timeoutMs}ms`);\n if (process.platform !== 'win32') chmodSync(temporaryPath, 0o755);\n renameSync(temporaryPath, destination);\n return realpathSync(destination);\n } catch (error) {\n const reason = timedOut\n ? `download timed out after ${timeoutMs}ms`\n : error instanceof Error\n ? error.message\n : String(error);\n throw new Error(\n `Unable to download codebase-memory-mcp from GitHub Releases: ${reason}. ` +\n 'Check network access or set XOPC_CBM_BINARY to a trusted executable.',\n );\n } finally {\n clearTimeout(timer);\n rmSync(temporaryPath, { force: true });\n rmSync(tempDir, { recursive: true, force: true });\n }\n}\n\n/**\n * Resolve a shared, versioned user cache. Electron seeds it from its bundled binary;\n * CLI seeds it from a verified release download. This keeps both surfaces on one binary.\n */\nexport async function ensureCodebaseMemoryBinary(explicitPath?: string): Promise<string> {\n const overridden = overrideBinaryPath(explicitPath);\n if (overridden) return overridden;\n\n const cached = await verifySharedCachedBinary();\n if (cached) return cached;\n\n return withCacheLock(async () => {\n cleanupStaleStaging(cacheVersionRoot());\n const afterLock = await verifySharedCachedBinary();\n if (afterLock) return afterLock;\n\n for (const candidate of bundledBinaryCandidates()) {\n try {\n await verifyBundledSource(candidate);\n return await installInSharedCache(candidate.source, async (destination) => {\n copyFileSync(candidate.path, destination);\n });\n } catch (error) {\n log.warn(\n { err: error, source: candidate.source, path: candidate.path },\n 'Code intelligence binary source was not usable',\n );\n }\n }\n\n log.info(\n { destination: cacheBinaryPath(), version: CBM_VERSION, timeoutMs: DOWNLOAD_TIMEOUT_MS },\n 'Downloading code intelligence binary into shared cache',\n );\n return installInSharedCache('github-release', async (destination) => {\n await downloadCodeb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F,MAAM,aAAa,mBAAmB,aAAa;AACnD,KAAI,WAAY,QAAO;CAEvB,MAAM,SAAS,MAAM,0BAA0B;AAC/C,KAAI,OAAQ,QAAO;AAEnB,QAAO,cAAc,YAAY;AAC/B,sBAAoB,kBAAkB,CAAC;EACvC,MAAM,YAAY,MAAM,0BAA0B;AAClD,MAAI,UAAW,QAAO;AAEtB,OAAK,MAAM,aAAa,yBAAyB,CAC/C,KAAI;AACF,SAAM,oBAAoB,UAAU;AACpC,UAAO,MAAM,qBAAqB,UAAU,QAAQ,OAAO,gBAAgB;AACzE,iBAAa,UAAU,MAAM,YAAY;KACzC;WACK,OAAO;AACd,OAAI,KACF;IAAE,KAAK;IAAO,QAAQ,UAAU;IAAQ,MAAM,UAAU;IAAM,EAC9D,iDACD;;AAIL,MAAI,KACF;GAAE,aAAa,iBAAiB;GAAE,SAAS;GAAa,WAAW;GAAqB,EACxF,yDACD;AACD,SAAO,qBAAqB,kBAAkB,OAAO,gBAAgB;AACnE,SAAM,6BAA6B,YAAY;IAC/C;GACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { resolveCodebaseMemoryBinary } from './binary.js';
|
|
1
|
+
export { downloadCodebaseMemoryBinary, ensureCodebaseMemoryBinary, resolveCodebaseMemoryBinary, } from './binary.js';
|
|
2
2
|
export { CodeIntelligenceRuntime } from './runtime.js';
|
|
3
3
|
export { createCodeIntelligenceTools, type CodeIntelligenceToolDeps } from './tools.js';
|
|
4
4
|
export type { CodeIntelligenceRuntimeLike, CodeIntelligenceState, CodeIntelligenceStatus, CodeIntelligenceToolResult, } from './types.js';
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import { createCodeIntelligenceTools } from "./tools.js";
|
|
2
|
-
import { resolveCodebaseMemoryBinary } from "./binary.js";
|
|
2
|
+
import { downloadCodebaseMemoryBinary, ensureCodebaseMemoryBinary, resolveCodebaseMemoryBinary } from "./binary.js";
|
|
3
3
|
import { CodeIntelligenceRuntime } from "./runtime.js";
|
|
4
|
-
export { CodeIntelligenceRuntime, createCodeIntelligenceTools, resolveCodebaseMemoryBinary };
|
|
4
|
+
export { CodeIntelligenceRuntime, createCodeIntelligenceTools, downloadCodebaseMemoryBinary, ensureCodebaseMemoryBinary, resolveCodebaseMemoryBinary };
|
|
@@ -3,7 +3,7 @@ import { createLogger } from "../../utils/logger/index.js";
|
|
|
3
3
|
import { init_logger } from "../../utils/logger.js";
|
|
4
4
|
import { init_paths } from "../../config/paths.js";
|
|
5
5
|
import { XopcStdioClientTransport } from "../mcp/mcp-stdio-transport.js";
|
|
6
|
-
import {
|
|
6
|
+
import { ensureCodebaseMemoryBinary } from "./binary.js";
|
|
7
7
|
import { isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
8
8
|
import { mkdirSync } from "node:fs";
|
|
9
9
|
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
@@ -132,7 +132,7 @@ var CodeIntelligenceRuntime = class {
|
|
|
132
132
|
this.connectionPromise = (async () => {
|
|
133
133
|
this.state = "connecting";
|
|
134
134
|
const config = this.getConfig().codeIntelligence;
|
|
135
|
-
const binary =
|
|
135
|
+
const binary = await ensureCodebaseMemoryBinary(config.binaryPath);
|
|
136
136
|
const cacheDir = join(resolveStateDir(), "code-intelligence", "cbm");
|
|
137
137
|
mkdirSync(cacheDir, { recursive: true });
|
|
138
138
|
const transport = new XopcStdioClientTransport({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.js","names":[],"sources":["../../../../src/agent/code-intelligence/runtime.ts"],"sourcesContent":["import { mkdirSync } from 'node:fs';\nimport { isAbsolute, join, relative, resolve, sep } from 'node:path';\n\nimport { Client } from '@modelcontextprotocol/sdk/client/index.js';\nimport type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';\n\nimport type { Config } from '../../config/schema.js';\nimport { resolveStateDir } from '../../config/paths.js';\nimport { createLogger } from '../../utils/logger.js';\nimport { XopcStdioClientTransport } from '../mcp/mcp-stdio-transport.js';\nimport { resolveCodebaseMemoryBinary } from './binary.js';\nimport type {\n CodeIntelligenceRuntimeLike,\n CodeIntelligenceState,\n CodeIntelligenceStatus,\n CodeIntelligenceToolResult,\n} from './types.js';\n\nconst log = createLogger('CodeIntelligence');\n\ntype JsonRecord = Record<string, unknown>;\n\nfunction deriveProjectName(workspace: string): string {\n return workspace\n .replace(/^[\\\\/]+/, '')\n .replace(/[\\\\/:]+/g, '-')\n .replace(/-+/g, '-')\n .replace(/^-|-$/g, '');\n}\n\nfunction timeout<T>(promise: Promise<T>, timeoutMs: number, operation: string): Promise<T> {\n return new Promise<T>((resolvePromise, reject) => {\n const timer = setTimeout(\n () => reject(new Error(`${operation} timed out after ${timeoutMs}ms`)),\n timeoutMs,\n );\n promise.then(\n (value) => {\n clearTimeout(timer);\n resolvePromise(value);\n },\n (error) => {\n clearTimeout(timer);\n reject(error);\n },\n );\n });\n}\n\nfunction resultText(result: CallToolResult): string {\n const parts: string[] = [];\n for (const item of result.content ?? []) {\n if (item.type === 'text' && typeof item.text === 'string') {\n parts.push(item.text);\n }\n }\n return parts.join('\\n').trim();\n}\n\nfunction parseJsonRecord(text: string): JsonRecord | undefined {\n try {\n const parsed = JSON.parse(text) as unknown;\n return parsed && typeof parsed === 'object' && !Array.isArray(parsed)\n ? parsed as JsonRecord\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction abortError(): Error {\n return new DOMException('Code intelligence operation aborted', 'AbortError');\n}\n\nexport class CodeIntelligenceRuntime implements CodeIntelligenceRuntimeLike {\n private readonly workspace: string;\n private readonly project: string;\n private readonly getConfig: () => Config;\n private state: CodeIntelligenceState = 'idle';\n private coverage: CodeIntelligenceStatus['coverage'] = 'unknown';\n private indexedAt: string | undefined;\n private errorMessage: string | undefined;\n private dirtyPaths = new Set<string>();\n private dirtyVersion = 0;\n private refreshTimer: ReturnType<typeof setTimeout> | undefined;\n private connectionPromise: Promise<void> | undefined;\n private indexPromise: Promise<void> | undefined;\n private client: Client | undefined;\n private transport: XopcStdioClientTransport | undefined;\n private availableTools = new Set<string>();\n private disposed = false;\n\n constructor(options: { workspace: string; getConfig: () => Config }) {\n this.workspace = resolve(options.workspace);\n this.project = deriveProjectName(this.workspace);\n this.getConfig = options.getConfig;\n }\n\n getStatus(): CodeIntelligenceStatus {\n return {\n state: this.state,\n workspace: this.workspace,\n project: this.project,\n indexedAt: this.indexedAt,\n dirtyPaths: [...this.dirtyPaths].toSorted(),\n coverage: this.coverage,\n errorMessage: this.errorMessage,\n };\n }\n\n supportsTool(name: string): boolean {\n return this.availableTools.has(name);\n }\n\n async prime(): Promise<void> {\n const config = this.getConfig().codeIntelligence;\n if (!config.enabled || !config.autoIndex || this.disposed) return;\n if (this.indexPromise) return this.indexPromise;\n if (this.indexedAt && this.dirtyPaths.size === 0) return;\n await this.refreshIndex();\n }\n\n markDirty(paths: readonly string[]): void {\n const config = this.getConfig().codeIntelligence;\n if (!config.enabled || !config.autoRefresh || this.disposed) return;\n\n let changed = false;\n for (const input of paths) {\n if (!input?.trim()) continue;\n const absolute = isAbsolute(input) ? resolve(input) : resolve(this.workspace, input);\n const rel = relative(this.workspace, absolute);\n if (!rel || rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) continue;\n this.dirtyPaths.add(rel.split(sep).join('/'));\n changed = true;\n }\n if (!changed) return;\n\n this.dirtyVersion += 1;\n if (this.state === 'ready' || this.state === 'degraded') {\n this.state = 'dirty';\n }\n if (this.refreshTimer) clearTimeout(this.refreshTimer);\n this.refreshTimer = setTimeout(() => {\n this.refreshTimer = undefined;\n void this.refreshIndex().catch(() => {});\n }, config.refreshDebounceMs);\n this.refreshTimer.unref?.();\n }\n\n async callTool(\n toolNames: string | readonly string[],\n input: Record<string, unknown>,\n signal?: AbortSignal,\n ): Promise<CodeIntelligenceToolResult> {\n if (signal?.aborted) throw abortError();\n const config = this.getConfig().codeIntelligence;\n if (!config.enabled) {\n throw new Error('Code intelligence is disabled');\n }\n\n if (\n config.autoIndex &&\n (this.indexedAt === undefined || this.state === 'idle' || this.dirtyPaths.size > 0)\n ) {\n await this.refreshIndex();\n } else {\n await this.ensureConnected();\n }\n if (signal?.aborted) throw abortError();\n\n const names = typeof toolNames === 'string' ? [toolNames] : [...toolNames];\n const toolName = names.find((name) => this.availableTools.has(name));\n if (!toolName) {\n throw new Error(`CBM does not expose a supported tool: ${names.join(' or ')}`);\n }\n const result = await this.callRaw(toolName, input, config.queryTimeoutMs);\n const text = resultText(result);\n if (result.isError) {\n throw new Error(text || `CBM ${toolName} failed`);\n }\n return { text, status: this.getStatus() };\n }\n\n private async ensureConnected(): Promise<void> {\n if (this.disposed) throw new Error('Code intelligence runtime is disposed');\n if (this.client && this.transport) return;\n if (this.connectionPromise) return this.connectionPromise;\n\n this.connectionPromise = (async () => {\n this.state = 'connecting';\n const config = this.getConfig().codeIntelligence;\n const binary = resolveCodebaseMemoryBinary(config.binaryPath);\n const cacheDir = join(resolveStateDir(), 'code-intelligence', 'cbm');\n mkdirSync(cacheDir, { recursive: true });\n const transport = new XopcStdioClientTransport({\n command: binary,\n cwd: this.workspace,\n env: {\n CBM_ALLOWED_ROOT: this.workspace,\n CBM_CACHE_DIR: cacheDir,\n CBM_LOG_LEVEL: process.env.XOPC_LOG_LEVEL === 'debug' ? 'debug' : 'warn',\n },\n stderr: 'pipe',\n });\n const client = new Client({ name: 'xopc-code-intelligence', version: '1.0.0' });\n transport.stderr?.on('data', (chunk: Buffer | string) => {\n for (const line of String(chunk).split(/\\r?\\n/)) {\n if (line.trim()) log.debug({ workspace: this.workspace }, `CBM: ${line.trim()}`);\n }\n });\n\n try {\n await timeout(client.connect(transport), 30_000, 'CBM connection');\n const toolNames = new Set<string>();\n let cursor: string | undefined;\n do {\n const page = await timeout(\n client.listTools(cursor ? { cursor } : undefined),\n 20_000,\n 'CBM tool discovery',\n );\n for (const tool of page.tools) toolNames.add(tool.name);\n cursor = page.nextCursor;\n } while (cursor);\n this.client = client;\n this.transport = transport;\n this.availableTools = toolNames;\n this.state = this.dirtyPaths.size > 0 ? 'dirty' : 'idle';\n this.errorMessage = undefined;\n log.info(\n { workspace: this.workspace, project: this.project, toolCount: this.availableTools.size },\n 'Code intelligence runtime connected',\n );\n } catch (error) {\n await transport.close().catch(() => {});\n await client.close().catch(() => {});\n throw error;\n }\n })();\n\n try {\n await this.connectionPromise;\n } catch (error) {\n this.state = 'unavailable';\n this.errorMessage = error instanceof Error ? error.message : String(error);\n log.warn(\n { err: error, workspace: this.workspace, project: this.project },\n `Code intelligence unavailable: ${this.errorMessage}`,\n );\n throw error;\n } finally {\n this.connectionPromise = undefined;\n }\n }\n\n private async refreshIndex(): Promise<void> {\n if (this.disposed) throw new Error('Code intelligence runtime is disposed');\n if (this.indexPromise) return this.indexPromise;\n\n const versionAtStart = this.dirtyVersion;\n this.indexPromise = (async () => {\n await this.ensureConnected();\n const config = this.getConfig().codeIntelligence;\n this.state = 'indexing';\n const result = await this.callRaw(\n 'index_repository',\n {\n repo_path: this.workspace,\n name: this.project,\n mode: config.indexMode,\n persistence: false,\n },\n config.indexTimeoutMs,\n );\n const text = resultText(result);\n const parsed = parseJsonRecord(text);\n const resultStatus = typeof parsed?.status === 'string' ? parsed.status : 'indexed';\n if (result.isError || resultStatus === 'error') {\n throw new Error(text || 'CBM indexing failed');\n }\n\n this.indexedAt = new Date().toISOString();\n this.coverage = resultStatus === 'degraded' ? 'partial' : 'unknown';\n this.errorMessage = undefined;\n if (versionAtStart === this.dirtyVersion) {\n this.dirtyPaths.clear();\n this.state = resultStatus === 'degraded' ? 'degraded' : 'ready';\n } else {\n this.state = 'dirty';\n }\n log.info(\n {\n workspace: this.workspace,\n project: this.project,\n indexMode: config.indexMode,\n status: resultStatus,\n dirtyPaths: this.dirtyPaths.size,\n },\n 'Code intelligence index refreshed',\n );\n })();\n\n try {\n await this.indexPromise;\n } catch (error) {\n this.state = 'degraded';\n this.coverage = 'unknown';\n this.errorMessage = error instanceof Error ? error.message : String(error);\n log.warn(\n { err: error, workspace: this.workspace, project: this.project },\n `Code intelligence indexing failed: ${this.errorMessage}`,\n );\n throw error;\n } finally {\n this.indexPromise = undefined;\n if (!this.disposed && this.dirtyPaths.size > 0 && versionAtStart !== this.dirtyVersion) {\n queueMicrotask(() => void this.refreshIndex().catch(() => {}));\n }\n }\n }\n\n private async callRaw(\n toolName: string,\n input: Record<string, unknown>,\n timeoutMs: number,\n ): Promise<CallToolResult> {\n await this.ensureConnected();\n if (!this.client) throw new Error('CBM client is not connected');\n if (!this.availableTools.has(toolName)) {\n throw new Error(`CBM tool is unavailable: ${toolName}`);\n }\n try {\n return await timeout(\n this.client.callTool({ name: toolName, arguments: input }) as Promise<CallToolResult>,\n timeoutMs,\n `CBM ${toolName}`,\n );\n } catch (error) {\n this.state = 'unavailable';\n this.errorMessage = error instanceof Error ? error.message : String(error);\n await this.resetConnection();\n throw error;\n }\n }\n\n private async resetConnection(): Promise<void> {\n const transport = this.transport;\n const client = this.client;\n this.transport = undefined;\n this.client = undefined;\n this.availableTools.clear();\n await client?.close().catch(() => {});\n await transport?.close().catch(() => {});\n }\n\n async dispose(): Promise<void> {\n if (this.disposed) return;\n this.disposed = true;\n this.state = 'disposed';\n if (this.refreshTimer) clearTimeout(this.refreshTimer);\n this.refreshTimer = undefined;\n await this.resetConnection();\n }\n}\n"],"mappings":";;;;;;;;;;YAOwD;aACH;AAUrD,MAAM,MAAM,aAAa,mBAAmB;AAI5C,SAAS,kBAAkB,WAA2B;AACpD,QAAO,UACJ,QAAQ,WAAW,GAAG,CACtB,QAAQ,YAAY,IAAI,CACxB,QAAQ,OAAO,IAAI,CACnB,QAAQ,UAAU,GAAG;;AAG1B,SAAS,QAAW,SAAqB,WAAmB,WAA+B;AACzF,QAAO,IAAI,SAAY,gBAAgB,WAAW;EAChD,MAAM,QAAQ,iBACN,uBAAO,IAAI,MAAM,GAAG,UAAU,mBAAmB,UAAU,IAAI,CAAC,EACtE,UACD;AACD,UAAQ,MACL,UAAU;AACT,gBAAa,MAAM;AACnB,kBAAe,M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D,WACA,OAAO,WACR;WACM,OAAO;AACd,QAAK,QAAQ;AACb,QAAK,eAAe,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;AAC1E,SAAM,KAAK,iBAAiB;AAC5B,SAAM;;;CAIV,MAAc,kBAAiC;EAC7C,MAAM,YAAY,KAAK;EACvB,MAAM,SAAS,KAAK;AACpB,OAAK,YAAY,KAAA;AACjB,OAAK,SAAS,KAAA;AACd,OAAK,eAAe,OAAO;AAC3B,QAAM,QAAQ,OAAO,CAAC,YAAY,GAAG;AACrC,QAAM,WAAW,OAAO,CAAC,YAAY,GAAG;;CAG1C,MAAM,UAAyB;AAC7B,MAAI,KAAK,SAAU;AACnB,OAAK,WAAW;AAChB,OAAK,QAAQ;AACb,MAAI,KAAK,aAAc,cAAa,KAAK,aAAa;AACtD,OAAK,eAAe,KAAA;AACpB,QAAM,KAAK,iBAAiB"}
|
|
1
|
+
{"version":3,"file":"runtime.js","names":[],"sources":["../../../../src/agent/code-intelligence/runtime.ts"],"sourcesContent":["import { mkdirSync } from 'node:fs';\nimport { isAbsolute, join, relative, resolve, sep } from 'node:path';\n\nimport { Client } from '@modelcontextprotocol/sdk/client/index.js';\nimport type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';\n\nimport type { Config } from '../../config/schema.js';\nimport { resolveStateDir } from '../../config/paths.js';\nimport { createLogger } from '../../utils/logger.js';\nimport { XopcStdioClientTransport } from '../mcp/mcp-stdio-transport.js';\nimport { ensureCodebaseMemoryBinary } from './binary.js';\nimport type {\n CodeIntelligenceRuntimeLike,\n CodeIntelligenceState,\n CodeIntelligenceStatus,\n CodeIntelligenceToolResult,\n} from './types.js';\n\nconst log = createLogger('CodeIntelligence');\n\ntype JsonRecord = Record<string, unknown>;\n\nfunction deriveProjectName(workspace: string): string {\n return workspace\n .replace(/^[\\\\/]+/, '')\n .replace(/[\\\\/:]+/g, '-')\n .replace(/-+/g, '-')\n .replace(/^-|-$/g, '');\n}\n\nfunction timeout<T>(promise: Promise<T>, timeoutMs: number, operation: string): Promise<T> {\n return new Promise<T>((resolvePromise, reject) => {\n const timer = setTimeout(\n () => reject(new Error(`${operation} timed out after ${timeoutMs}ms`)),\n timeoutMs,\n );\n promise.then(\n (value) => {\n clearTimeout(timer);\n resolvePromise(value);\n },\n (error) => {\n clearTimeout(timer);\n reject(error);\n },\n );\n });\n}\n\nfunction resultText(result: CallToolResult): string {\n const parts: string[] = [];\n for (const item of result.content ?? []) {\n if (item.type === 'text' && typeof item.text === 'string') {\n parts.push(item.text);\n }\n }\n return parts.join('\\n').trim();\n}\n\nfunction parseJsonRecord(text: string): JsonRecord | undefined {\n try {\n const parsed = JSON.parse(text) as unknown;\n return parsed && typeof parsed === 'object' && !Array.isArray(parsed)\n ? parsed as JsonRecord\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction abortError(): Error {\n return new DOMException('Code intelligence operation aborted', 'AbortError');\n}\n\nexport class CodeIntelligenceRuntime implements CodeIntelligenceRuntimeLike {\n private readonly workspace: string;\n private readonly project: string;\n private readonly getConfig: () => Config;\n private state: CodeIntelligenceState = 'idle';\n private coverage: CodeIntelligenceStatus['coverage'] = 'unknown';\n private indexedAt: string | undefined;\n private errorMessage: string | undefined;\n private dirtyPaths = new Set<string>();\n private dirtyVersion = 0;\n private refreshTimer: ReturnType<typeof setTimeout> | undefined;\n private connectionPromise: Promise<void> | undefined;\n private indexPromise: Promise<void> | undefined;\n private client: Client | undefined;\n private transport: XopcStdioClientTransport | undefined;\n private availableTools = new Set<string>();\n private disposed = false;\n\n constructor(options: { workspace: string; getConfig: () => Config }) {\n this.workspace = resolve(options.workspace);\n this.project = deriveProjectName(this.workspace);\n this.getConfig = options.getConfig;\n }\n\n getStatus(): CodeIntelligenceStatus {\n return {\n state: this.state,\n workspace: this.workspace,\n project: this.project,\n indexedAt: this.indexedAt,\n dirtyPaths: [...this.dirtyPaths].toSorted(),\n coverage: this.coverage,\n errorMessage: this.errorMessage,\n };\n }\n\n supportsTool(name: string): boolean {\n return this.availableTools.has(name);\n }\n\n async prime(): Promise<void> {\n const config = this.getConfig().codeIntelligence;\n if (!config.enabled || !config.autoIndex || this.disposed) return;\n if (this.indexPromise) return this.indexPromise;\n if (this.indexedAt && this.dirtyPaths.size === 0) return;\n await this.refreshIndex();\n }\n\n markDirty(paths: readonly string[]): void {\n const config = this.getConfig().codeIntelligence;\n if (!config.enabled || !config.autoRefresh || this.disposed) return;\n\n let changed = false;\n for (const input of paths) {\n if (!input?.trim()) continue;\n const absolute = isAbsolute(input) ? resolve(input) : resolve(this.workspace, input);\n const rel = relative(this.workspace, absolute);\n if (!rel || rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) continue;\n this.dirtyPaths.add(rel.split(sep).join('/'));\n changed = true;\n }\n if (!changed) return;\n\n this.dirtyVersion += 1;\n if (this.state === 'ready' || this.state === 'degraded') {\n this.state = 'dirty';\n }\n if (this.refreshTimer) clearTimeout(this.refreshTimer);\n this.refreshTimer = setTimeout(() => {\n this.refreshTimer = undefined;\n void this.refreshIndex().catch(() => {});\n }, config.refreshDebounceMs);\n this.refreshTimer.unref?.();\n }\n\n async callTool(\n toolNames: string | readonly string[],\n input: Record<string, unknown>,\n signal?: AbortSignal,\n ): Promise<CodeIntelligenceToolResult> {\n if (signal?.aborted) throw abortError();\n const config = this.getConfig().codeIntelligence;\n if (!config.enabled) {\n throw new Error('Code intelligence is disabled');\n }\n\n if (\n config.autoIndex &&\n (this.indexedAt === undefined || this.state === 'idle' || this.dirtyPaths.size > 0)\n ) {\n await this.refreshIndex();\n } else {\n await this.ensureConnected();\n }\n if (signal?.aborted) throw abortError();\n\n const names = typeof toolNames === 'string' ? [toolNames] : [...toolNames];\n const toolName = names.find((name) => this.availableTools.has(name));\n if (!toolName) {\n throw new Error(`CBM does not expose a supported tool: ${names.join(' or ')}`);\n }\n const result = await this.callRaw(toolName, input, config.queryTimeoutMs);\n const text = resultText(result);\n if (result.isError) {\n throw new Error(text || `CBM ${toolName} failed`);\n }\n return { text, status: this.getStatus() };\n }\n\n private async ensureConnected(): Promise<void> {\n if (this.disposed) throw new Error('Code intelligence runtime is disposed');\n if (this.client && this.transport) return;\n if (this.connectionPromise) return this.connectionPromise;\n\n this.connectionPromise = (async () => {\n this.state = 'connecting';\n const config = this.getConfig().codeIntelligence;\n const binary = await ensureCodebaseMemoryBinary(config.binaryPath);\n const cacheDir = join(resolveStateDir(), 'code-intelligence', 'cbm');\n mkdirSync(cacheDir, { recursive: true });\n const transport = new XopcStdioClientTransport({\n command: binary,\n cwd: this.workspace,\n env: {\n CBM_ALLOWED_ROOT: this.workspace,\n CBM_CACHE_DIR: cacheDir,\n CBM_LOG_LEVEL: process.env.XOPC_LOG_LEVEL === 'debug' ? 'debug' : 'warn',\n },\n stderr: 'pipe',\n });\n const client = new Client({ name: 'xopc-code-intelligence', version: '1.0.0' });\n transport.stderr?.on('data', (chunk: Buffer | string) => {\n for (const line of String(chunk).split(/\\r?\\n/)) {\n if (line.trim()) log.debug({ workspace: this.workspace }, `CBM: ${line.trim()}`);\n }\n });\n\n try {\n await timeout(client.connect(transport), 30_000, 'CBM connection');\n const toolNames = new Set<string>();\n let cursor: string | undefined;\n do {\n const page = await timeout(\n client.listTools(cursor ? { cursor } : undefined),\n 20_000,\n 'CBM tool discovery',\n );\n for (const tool of page.tools) toolNames.add(tool.name);\n cursor = page.nextCursor;\n } while (cursor);\n this.client = client;\n this.transport = transport;\n this.availableTools = toolNames;\n this.state = this.dirtyPaths.size > 0 ? 'dirty' : 'idle';\n this.errorMessage = undefined;\n log.info(\n { workspace: this.workspace, project: this.project, toolCount: this.availableTools.size },\n 'Code intelligence runtime connected',\n );\n } catch (error) {\n await transport.close().catch(() => {});\n await client.close().catch(() => {});\n throw error;\n }\n })();\n\n try {\n await this.connectionPromise;\n } catch (error) {\n this.state = 'unavailable';\n this.errorMessage = error instanceof Error ? error.message : String(error);\n log.warn(\n { err: error, workspace: this.workspace, project: this.project },\n `Code intelligence unavailable: ${this.errorMessage}`,\n );\n throw error;\n } finally {\n this.connectionPromise = undefined;\n }\n }\n\n private async refreshIndex(): Promise<void> {\n if (this.disposed) throw new Error('Code intelligence runtime is disposed');\n if (this.indexPromise) return this.indexPromise;\n\n const versionAtStart = this.dirtyVersion;\n this.indexPromise = (async () => {\n await this.ensureConnected();\n const config = this.getConfig().codeIntelligence;\n this.state = 'indexing';\n const result = await this.callRaw(\n 'index_repository',\n {\n repo_path: this.workspace,\n name: this.project,\n mode: config.indexMode,\n persistence: false,\n },\n config.indexTimeoutMs,\n );\n const text = resultText(result);\n const parsed = parseJsonRecord(text);\n const resultStatus = typeof parsed?.status === 'string' ? parsed.status : 'indexed';\n if (result.isError || resultStatus === 'error') {\n throw new Error(text || 'CBM indexing failed');\n }\n\n this.indexedAt = new Date().toISOString();\n this.coverage = resultStatus === 'degraded' ? 'partial' : 'unknown';\n this.errorMessage = undefined;\n if (versionAtStart === this.dirtyVersion) {\n this.dirtyPaths.clear();\n this.state = resultStatus === 'degraded' ? 'degraded' : 'ready';\n } else {\n this.state = 'dirty';\n }\n log.info(\n {\n workspace: this.workspace,\n project: this.project,\n indexMode: config.indexMode,\n status: resultStatus,\n dirtyPaths: this.dirtyPaths.size,\n },\n 'Code intelligence index refreshed',\n );\n })();\n\n try {\n await this.indexPromise;\n } catch (error) {\n this.state = 'degraded';\n this.coverage = 'unknown';\n this.errorMessage = error instanceof Error ? error.message : String(error);\n log.warn(\n { err: error, workspace: this.workspace, project: this.project },\n `Code intelligence indexing failed: ${this.errorMessage}`,\n );\n throw error;\n } finally {\n this.indexPromise = undefined;\n if (!this.disposed && this.dirtyPaths.size > 0 && versionAtStart !== this.dirtyVersion) {\n queueMicrotask(() => void this.refreshIndex().catch(() => {}));\n }\n }\n }\n\n private async callRaw(\n toolName: string,\n input: Record<string, unknown>,\n timeoutMs: number,\n ): Promise<CallToolResult> {\n await this.ensureConnected();\n if (!this.client) throw new Error('CBM client is not connected');\n if (!this.availableTools.has(toolName)) {\n throw new Error(`CBM tool is unavailable: ${toolName}`);\n }\n try {\n return await timeout(\n this.client.callTool({ name: toolName, arguments: input }) as Promise<CallToolResult>,\n timeoutMs,\n `CBM ${toolName}`,\n );\n } catch (error) {\n this.state = 'unavailable';\n this.errorMessage = error instanceof Error ? error.message : String(error);\n await this.resetConnection();\n throw error;\n }\n }\n\n private async resetConnection(): Promise<void> {\n const transport = this.transport;\n const client = this.client;\n this.transport = undefined;\n this.client = undefined;\n this.availableTools.clear();\n await client?.close().catch(() => {});\n await transport?.close().catch(() => {});\n }\n\n async dispose(): Promise<void> {\n if (this.disposed) return;\n this.disposed = true;\n this.state = 'disposed';\n if (this.refreshTimer) clearTimeout(this.refreshTimer);\n this.refreshTimer = undefined;\n await this.resetConnection();\n }\n}\n"],"mappings":";;;;;;;;;;YAOwD;aACH;AAUrD,MAAM,MAAM,aAAa,mBAAmB;AAI5C,SAAS,kBAAkB,WAA2B;AACpD,QAAO,UACJ,QAAQ,WAAW,GAAG,CACtB,QAAQ,YAAY,IAAI,CACxB,QAAQ,OAAO,IAAI,CACnB,QAAQ,UAAU,GAAG;;AAG1B,SAAS,QAAW,SAAqB,WAAmB,WAA+B;AACzF,QAAO,IAAI,SAAY,gBAAgB,WAAW;EAChD,MAAM,QAAQ,iBACN,uBAAO,IAAI,MAAM,GAAG,UAAU,mBAAmB,UAAU,IAAI,CAAC,EACtE,UACD;AACD,UAAQ,MACL,UAAU;AACT,gBAAa,MAAM;AACnB,kBAAe,MAAM;MAEtB,UAAU;AACT,gBAAa,MAAM;AACnB,UAAO,MAAM;IAEhB;GACD;;AAGJ,SAAS,WAAW,QAAgC;CAClD,MAAM,QAAkB,EAAE;AAC1B,MAAK,MAAM,QAAQ,OAAO,WAAW,EAAE,CACrC,KAAI,KAAK,SAAS,UAAU,OAAO,KAAK,SAAS,SAC/C,OAAM,KAAK,KAAK,KAAK;AAGzB,QAAO,MAAM,KAAK,KAAK,CAAC,MAAM;;AAGhC,SAAS,gBAAgB,MAAsC;AAC7D,KAAI;E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GAAG;AACrC,QAAM,WAAW,OAAO,CAAC,YAAY,GAAG;;CAG1C,MAAM,UAAyB;AAC7B,MAAI,KAAK,SAAU;AACnB,OAAK,WAAW;AAChB,OAAK,QAAQ;AACb,MAAI,KAAK,aAAc,cAAa,KAAK,aAAa;AACtD,OAAK,eAAe,KAAA;AACpB,QAAM,KAAK,iBAAiB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xopcai/xopc",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.140",
|
|
4
4
|
"description": "Local-first AI system that remembers context, coordinates AI, and sustains long-term progress.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/src/index.js",
|
|
@@ -84,7 +84,6 @@
|
|
|
84
84
|
"chalk": "^5.6.2",
|
|
85
85
|
"chokidar": "^5.0.0",
|
|
86
86
|
"cli-table3": "^0.6.5",
|
|
87
|
-
"codebase-memory-mcp": "0.9.0",
|
|
88
87
|
"commander": "^14.0.3",
|
|
89
88
|
"cron-parser": "^5.5.0",
|
|
90
89
|
"dotenv": "^17.4.2",
|
|
@@ -122,6 +121,7 @@
|
|
|
122
121
|
"@types/ws": "^8.18.1",
|
|
123
122
|
"@vitejs/plugin-react-swc": "^4.3.1",
|
|
124
123
|
"cross-env": "^10.1.0",
|
|
124
|
+
"codebase-memory-mcp": "0.9.0",
|
|
125
125
|
"dependency-cruiser": "^17.4.3",
|
|
126
126
|
"electron": "^42.4.1",
|
|
127
127
|
"electron-builder": "^26.12.1",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{hr as e}from"./index-NwiCnzI-.js";function t(t){let{children:n,fallback:r}=t,i=r===void 0?null:r;return e()?n:i}export{t};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./rolldown-runtime-aKtaBQYM.js";import{o as t,t as n}from"./fetch-BID89uCH.js";import{pr as r}from"./index-NwiCnzI-.js";var i=e({reloadSkills:()=>a});async function a(){let e=await n(t(`/api/skills/reload`),{method:`POST`});if(!e.ok)throw Error(await r(e))}export{i as n,a as t};
|