agent-space-manager 0.0.0-stage → 1.0.0
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 +51 -0
- package/LICENSE +22 -0
- package/README.md +157 -2
- package/README.zh-CN.md +158 -0
- package/adapters.mjs +1228 -0
- package/agents.mjs +653 -0
- package/index.mjs +292 -0
- package/manager.mjs +4428 -0
- package/package.json +71 -4
- package/page/app.js +4205 -0
- package/page/icon.svg +9 -0
- package/page/index.html +467 -0
- package/page/style.css +1032 -0
- package/server.mjs +1165 -0
- package/smart-tools.middleware.js +188 -0
package/server.mjs
ADDED
|
@@ -0,0 +1,1165 @@
|
|
|
1
|
+
// D:\Software\Magpie\agent-space-manager\server.mjs
|
|
2
|
+
// Local IPC & REST API Server for Agent Space Manager Web UI
|
|
3
|
+
// Allows Magpie WebView2 page to query filesystem, manage junctions, and resolve shortcuts.
|
|
4
|
+
|
|
5
|
+
import http from "node:http";
|
|
6
|
+
import fs from "node:fs";
|
|
7
|
+
import os from "node:os";
|
|
8
|
+
import path from "node:path";
|
|
9
|
+
import { spawn } from "node:child_process";
|
|
10
|
+
import { fileURLToPath } from "node:url";
|
|
11
|
+
import {
|
|
12
|
+
loadHubConfig,
|
|
13
|
+
saveHubConfig,
|
|
14
|
+
scanPlugins,
|
|
15
|
+
connectAgent,
|
|
16
|
+
syncIdePlugins,
|
|
17
|
+
syncAllIdes,
|
|
18
|
+
unlinkAllForIde,
|
|
19
|
+
unlinkAllForProject,
|
|
20
|
+
detectAgentConfigPath,
|
|
21
|
+
resolveDroppedTarget,
|
|
22
|
+
browseFileSystem,
|
|
23
|
+
getEffectiveHubRoot,
|
|
24
|
+
buildCategoriesRegistry,
|
|
25
|
+
resolveHubRoot,
|
|
26
|
+
listAgentProfilesForUi,
|
|
27
|
+
inferAgentType,
|
|
28
|
+
checkComponentsModifications,
|
|
29
|
+
checkAndAutoReconnectOnStartup,
|
|
30
|
+
getComponentsStorageSnapshot,
|
|
31
|
+
recheckConnectedAgentsStatus,
|
|
32
|
+
verifyPluginWorkabilityOnDisk,
|
|
33
|
+
removeComponentUpdateMechanisms,
|
|
34
|
+
checkCentralizedUpstreamUpdates,
|
|
35
|
+
loadCentralizedUpstreamUpdateState,
|
|
36
|
+
getOmniroutePort,
|
|
37
|
+
isOmnirouteInstalled,
|
|
38
|
+
checkOmnirouteStatus,
|
|
39
|
+
startOmniroute,
|
|
40
|
+
stopOmniroute,
|
|
41
|
+
stopOmnirouteSync,
|
|
42
|
+
isMagpieRunning,
|
|
43
|
+
getLastOmnirouteStartAttempt,
|
|
44
|
+
resetOmnirouteStartAttemptForTest,
|
|
45
|
+
openUrlInBrowser,
|
|
46
|
+
scanAgentForeignComponents,
|
|
47
|
+
cleanAgentForeignComponents,
|
|
48
|
+
autoEnableHubComponents,
|
|
49
|
+
} from "./manager.mjs";
|
|
50
|
+
|
|
51
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
52
|
+
const MAGPIE_PLUGINS_JSON = path.join(os.homedir(), ".config", "magpie", "plugins.json");
|
|
53
|
+
const SIBLING_DIRS = [
|
|
54
|
+
__dirname,
|
|
55
|
+
];
|
|
56
|
+
|
|
57
|
+
export const API_PORT = process.env.ASM_PORT ? parseInt(process.env.ASM_PORT, 10) : 41789;
|
|
58
|
+
let activeServer = null;
|
|
59
|
+
let magpieWatchInterval = null;
|
|
60
|
+
let lastMagpieStateSig = "";
|
|
61
|
+
|
|
62
|
+
function isAllowedOrigin(origin) {
|
|
63
|
+
if (!origin || origin === "null") return true;
|
|
64
|
+
if (
|
|
65
|
+
origin.startsWith("file://") ||
|
|
66
|
+
origin.startsWith("magpie://") ||
|
|
67
|
+
origin.startsWith("app://") ||
|
|
68
|
+
origin.startsWith("wails://") ||
|
|
69
|
+
origin.startsWith("tauri://") ||
|
|
70
|
+
origin.startsWith("vscode-webview://") ||
|
|
71
|
+
origin.startsWith("vscode-file://") ||
|
|
72
|
+
origin.startsWith("ms-appx-web://") ||
|
|
73
|
+
origin.includes("htmlplatform.net") ||
|
|
74
|
+
origin.startsWith("chrome-extension://")
|
|
75
|
+
) {
|
|
76
|
+
return true;
|
|
77
|
+
}
|
|
78
|
+
if (/^https?:\/\/(127\.0\.0\.1|localhost)(:\d+)?$/i.test(origin)) return true;
|
|
79
|
+
return false;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function setCorsHeaders(req, res) {
|
|
83
|
+
const origin = req?.headers?.origin;
|
|
84
|
+
if (isAllowedOrigin(origin)) {
|
|
85
|
+
res.setHeader("Access-Control-Allow-Origin", origin || "*");
|
|
86
|
+
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE");
|
|
87
|
+
res.setHeader("Access-Control-Allow-Headers", "*");
|
|
88
|
+
res.setHeader("Access-Control-Allow-Private-Network", "true");
|
|
89
|
+
res.setHeader("Access-Control-Max-Age", "86400");
|
|
90
|
+
return true;
|
|
91
|
+
}
|
|
92
|
+
return false;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function updatePluginsCache(hubRoot, plugins, categories = null) {
|
|
96
|
+
try {
|
|
97
|
+
const cats = categories || buildCategoriesRegistry(plugins, hubRoot);
|
|
98
|
+
const payload = JSON.stringify(
|
|
99
|
+
{
|
|
100
|
+
path: "",
|
|
101
|
+
count: plugins.length,
|
|
102
|
+
updatedAt: Date.now(),
|
|
103
|
+
plugins,
|
|
104
|
+
categories: cats,
|
|
105
|
+
},
|
|
106
|
+
null,
|
|
107
|
+
2
|
|
108
|
+
);
|
|
109
|
+
|
|
110
|
+
const targetDirs = new Set();
|
|
111
|
+
if (process.env.ASM_CACHE_DIR) {
|
|
112
|
+
targetDirs.add(process.env.ASM_CACHE_DIR);
|
|
113
|
+
} else if (process.env.ASM_TEST !== "1" && process.env.NODE_ENV !== "test") {
|
|
114
|
+
for (const base of SIBLING_DIRS) {
|
|
115
|
+
const pDir = path.join(base, "page");
|
|
116
|
+
if (fs.existsSync(pDir)) targetDirs.add(pDir);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
for (const cacheDir of targetDirs) {
|
|
121
|
+
try {
|
|
122
|
+
const cacheFile = path.join(cacheDir, "plugins-cache.json");
|
|
123
|
+
fs.writeFileSync(cacheFile, payload, "utf8");
|
|
124
|
+
const mainJsCache = path.join(cacheDir, "plugins-cache.js");
|
|
125
|
+
fs.writeFileSync(mainJsCache, `window.__PLUGINS_CACHE__ = ${payload};\n`, "utf8");
|
|
126
|
+
} catch {}
|
|
127
|
+
}
|
|
128
|
+
} catch (err) {
|
|
129
|
+
console.warn("Failed to write plugins-cache.json:", err);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function syncFromMagpiePluginsJson(force = false) {
|
|
134
|
+
try {
|
|
135
|
+
if (!fs.existsSync(MAGPIE_PLUGINS_JSON)) return false;
|
|
136
|
+
const raw = fs.readFileSync(MAGPIE_PLUGINS_JSON, "utf8");
|
|
137
|
+
const parsed = JSON.parse(raw);
|
|
138
|
+
if (!Array.isArray(parsed?.plugins)) return false;
|
|
139
|
+
|
|
140
|
+
const entry = parsed.plugins.find((p) => {
|
|
141
|
+
const spec = String(p?.spec || "").toLowerCase();
|
|
142
|
+
return spec.includes("agent-space-manager") || spec.includes("smart-middleware");
|
|
143
|
+
});
|
|
144
|
+
if (!entry || !entry.options) return false;
|
|
145
|
+
|
|
146
|
+
const opts = entry.options;
|
|
147
|
+
handleOmnirouteRequest(opts.omnirouteRequest);
|
|
148
|
+
handleConnectRequest(opts.connectRequest);
|
|
149
|
+
const sig = JSON.stringify({
|
|
150
|
+
toolsRoot: opts.toolsRoot,
|
|
151
|
+
hubConfig: opts.hubConfig,
|
|
152
|
+
rescanNonce: opts.rescanNonce,
|
|
153
|
+
smartMiddlewareEnabled: opts.smartMiddlewareEnabled,
|
|
154
|
+
maxTools: opts.maxTools,
|
|
155
|
+
});
|
|
156
|
+
if (!force && sig === lastMagpieStateSig) return false;
|
|
157
|
+
lastMagpieStateSig = sig;
|
|
158
|
+
|
|
159
|
+
const baseCfg = loadHubConfig();
|
|
160
|
+
const cfg = opts.hubConfig && typeof opts.hubConfig === "object"
|
|
161
|
+
? { ...baseCfg, ...opts.hubConfig }
|
|
162
|
+
: baseCfg;
|
|
163
|
+
|
|
164
|
+
if (!Array.isArray(cfg.ides)) {
|
|
165
|
+
cfg.ides = Array.isArray(baseCfg.ides) ? baseCfg.ides : [
|
|
166
|
+
{
|
|
167
|
+
id: "antigravity",
|
|
168
|
+
name: "Antigravity (Google Gemini)",
|
|
169
|
+
agentType: "antigravity",
|
|
170
|
+
exePath: path.join(os.homedir(), ".gemini", "bin", process.platform === "win32" ? "agy.cmd" : "agy"),
|
|
171
|
+
configPath: detectAgentConfigPath("antigravity"),
|
|
172
|
+
enabled: true,
|
|
173
|
+
plugins: {},
|
|
174
|
+
},
|
|
175
|
+
];
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
if (opts.toolsRoot !== undefined && (!opts.hubConfig || opts.hubConfig.hubRoot === undefined)) {
|
|
179
|
+
cfg.hubRoot = String(opts.toolsRoot || "").trim();
|
|
180
|
+
}
|
|
181
|
+
if (!cfg.hubRoot || cfg.hubRoot.trim() === "") {
|
|
182
|
+
cfg.hubRoot = resolveHubRoot();
|
|
183
|
+
}
|
|
184
|
+
if (opts.smartMiddlewareEnabled !== undefined) {
|
|
185
|
+
cfg.smartMiddleware = { ...(cfg.smartMiddleware || {}), enabled: Boolean(opts.smartMiddlewareEnabled) };
|
|
186
|
+
}
|
|
187
|
+
if (opts.maxTools !== undefined && Number.isInteger(opts.maxTools)) {
|
|
188
|
+
cfg.smartMiddleware = { ...(cfg.smartMiddleware || {}), maxTools: opts.maxTools };
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
saveHubConfig(cfg);
|
|
192
|
+
const effPath = getEffectiveHubRoot(cfg);
|
|
193
|
+
const plugins = scanPlugins(effPath);
|
|
194
|
+
const categories = buildCategoriesRegistry(plugins, effPath);
|
|
195
|
+
updatePluginsCache(effPath, plugins, categories);
|
|
196
|
+
syncAllIdes(cfg, plugins);
|
|
197
|
+
return true;
|
|
198
|
+
} catch (err) {
|
|
199
|
+
return false;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// --- OmniRoute bridge for the sandboxed Magpie page ---
|
|
204
|
+
// The page frame has no network and no popups, so it posts a request via
|
|
205
|
+
// magpie.options.set({ omnirouteRequest: { action, nonce, port } }); this
|
|
206
|
+
// watcher runs it and answers in page/omniroute-status.js (script-src 'self').
|
|
207
|
+
let lastOmnirouteNonce = null;
|
|
208
|
+
let omnirouteBusy = false;
|
|
209
|
+
let pendingOmnirouteRequest = null;
|
|
210
|
+
|
|
211
|
+
let lastWrittenOmnirouteStatusSignature = "";
|
|
212
|
+
|
|
213
|
+
export function writeOmnirouteStatusFile(payload) {
|
|
214
|
+
try {
|
|
215
|
+
const targetDirs = new Set();
|
|
216
|
+
if (process.env.ASM_CACHE_DIR) {
|
|
217
|
+
targetDirs.add(process.env.ASM_CACHE_DIR);
|
|
218
|
+
} else if (process.env.ASM_TEST !== "1" && process.env.NODE_ENV !== "test") {
|
|
219
|
+
for (const base of SIBLING_DIRS) {
|
|
220
|
+
const pDir = path.join(base, "page");
|
|
221
|
+
if (fs.existsSync(pDir)) targetDirs.add(pDir);
|
|
222
|
+
}
|
|
223
|
+
targetDirs.add(path.join(__dirname, "page"));
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// Zero-work cache guard: skip disk writes if operational status is unchanged
|
|
227
|
+
const sig = `${payload?.installed}:${payload?.running}:${payload?.port}:${payload?.statusCode}:${payload?.action}:${payload?.state}`;
|
|
228
|
+
if (sig === lastWrittenOmnirouteStatusSignature && process.env.ASM_TEST !== "1") {
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
lastWrittenOmnirouteStatusSignature = sig;
|
|
232
|
+
|
|
233
|
+
const content = `window.__OMNIROUTE_STATUS__ = ${JSON.stringify(payload)};\n`;
|
|
234
|
+
for (const dir of targetDirs) {
|
|
235
|
+
try {
|
|
236
|
+
const file = path.join(dir, "omniroute-status.js");
|
|
237
|
+
fs.writeFileSync(file, content, "utf8");
|
|
238
|
+
} catch {}
|
|
239
|
+
}
|
|
240
|
+
} catch {}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
let lastOmnirouteStartAttempt = 0;
|
|
244
|
+
|
|
245
|
+
export function clearOmnirouteRequestFromPluginsJson(nonceToClear = null) {
|
|
246
|
+
try {
|
|
247
|
+
if (!fs.existsSync(MAGPIE_PLUGINS_JSON)) return;
|
|
248
|
+
const raw = fs.readFileSync(MAGPIE_PLUGINS_JSON, "utf8");
|
|
249
|
+
const parsed = JSON.parse(raw);
|
|
250
|
+
const entry = (parsed?.plugins || []).find((p) => {
|
|
251
|
+
const spec = String(p?.spec || "").toLowerCase();
|
|
252
|
+
return spec.includes("agent-space-manager") || spec.includes("smart-middleware");
|
|
253
|
+
});
|
|
254
|
+
if (entry?.options?.omnirouteRequest) {
|
|
255
|
+
if (!nonceToClear || entry.options.omnirouteRequest.nonce === nonceToClear) {
|
|
256
|
+
delete entry.options.omnirouteRequest;
|
|
257
|
+
fs.writeFileSync(MAGPIE_PLUGINS_JSON, JSON.stringify(parsed, null, 2), "utf8");
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
} catch {}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
export async function runOmnirouteAction(action = "status", port = null, nonce = null) {
|
|
264
|
+
const cfg = loadHubConfig();
|
|
265
|
+
const effectivePort = port || getOmniroutePort(cfg);
|
|
266
|
+
let status;
|
|
267
|
+
if (action === "start") {
|
|
268
|
+
lastOmnirouteStartAttempt = Date.now();
|
|
269
|
+
if (typeof recordOmnirouteStartAttempt === "function") {
|
|
270
|
+
recordOmnirouteStartAttempt();
|
|
271
|
+
}
|
|
272
|
+
const started = await startOmniroute(port, cfg);
|
|
273
|
+
status = await checkOmnirouteStatus(port, cfg);
|
|
274
|
+
if (!status.running && started?.error) status.error = started.error;
|
|
275
|
+
} else if (action === "stop") {
|
|
276
|
+
const stopped = await stopOmniroute(port, cfg);
|
|
277
|
+
status = await checkOmnirouteStatus(port, cfg);
|
|
278
|
+
if (status.running && stopped?.error) status.error = stopped.error;
|
|
279
|
+
} else if (action === "open") {
|
|
280
|
+
status = await checkOmnirouteStatus(port, cfg);
|
|
281
|
+
if (!status.running) {
|
|
282
|
+
startOmniroute(port, cfg).catch(() => {});
|
|
283
|
+
}
|
|
284
|
+
const targetUrl = status.url || `http://localhost:${port || getOmniroutePort(cfg)}`;
|
|
285
|
+
status.opened = openUrlInBrowser(targetUrl);
|
|
286
|
+
} else {
|
|
287
|
+
status = await checkOmnirouteStatus(port, cfg);
|
|
288
|
+
}
|
|
289
|
+
const payload = { ...status, action, nonce, checkedAt: Date.now() };
|
|
290
|
+
writeOmnirouteStatusFile(payload);
|
|
291
|
+
if (nonce) {
|
|
292
|
+
clearOmnirouteRequestFromPluginsJson(nonce);
|
|
293
|
+
}
|
|
294
|
+
return payload;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
export function handleOmnirouteRequest(req) {
|
|
298
|
+
if (!req || typeof req !== "object" || !req.nonce) return;
|
|
299
|
+
if (req.nonce === lastOmnirouteNonce) return;
|
|
300
|
+
if (omnirouteBusy) {
|
|
301
|
+
pendingOmnirouteRequest = req;
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
lastOmnirouteNonce = req.nonce;
|
|
305
|
+
omnirouteBusy = true;
|
|
306
|
+
const port = Number.isInteger(Number(req.port)) && Number(req.port) > 0 ? Number(req.port) : null;
|
|
307
|
+
runOmnirouteAction(String(req.action || "status"), port, req.nonce)
|
|
308
|
+
.catch(() => {})
|
|
309
|
+
.finally(() => {
|
|
310
|
+
omnirouteBusy = false;
|
|
311
|
+
if (pendingOmnirouteRequest) {
|
|
312
|
+
const next = pendingOmnirouteRequest;
|
|
313
|
+
pendingOmnirouteRequest = null;
|
|
314
|
+
handleOmnirouteRequest(next);
|
|
315
|
+
}
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// --- Connect Agent bridge for the sandboxed Magpie page ---
|
|
320
|
+
// Magpie page frames are sandboxed (connect-src 'none'): explicit connect requests
|
|
321
|
+
// are posted via magpie.options.set({ connectRequest: { target, isProject, nonce } });
|
|
322
|
+
// this watcher runs it and answers in page/connect-status.js (script-src 'self').
|
|
323
|
+
let lastConnectNonce = null;
|
|
324
|
+
let connectBusy = false;
|
|
325
|
+
let pendingConnectRequest = null;
|
|
326
|
+
let lastWrittenConnectStatusSignature = "";
|
|
327
|
+
|
|
328
|
+
export function resetConnectStateForTest() {
|
|
329
|
+
lastConnectNonce = null;
|
|
330
|
+
connectBusy = false;
|
|
331
|
+
pendingConnectRequest = null;
|
|
332
|
+
lastWrittenConnectStatusSignature = "";
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
export function writeConnectStatusFile(payload) {
|
|
336
|
+
try {
|
|
337
|
+
const targetDirs = new Set();
|
|
338
|
+
if (process.env.ASM_CACHE_DIR) {
|
|
339
|
+
targetDirs.add(process.env.ASM_CACHE_DIR);
|
|
340
|
+
} else if (process.env.ASM_TEST !== "1" && process.env.NODE_ENV !== "test") {
|
|
341
|
+
for (const base of SIBLING_DIRS) {
|
|
342
|
+
const pDir = path.join(base, "page");
|
|
343
|
+
if (fs.existsSync(pDir)) targetDirs.add(pDir);
|
|
344
|
+
}
|
|
345
|
+
targetDirs.add(path.join(__dirname, "page"));
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
const sig = `${payload?.success}:${payload?.nonce}:${payload?.targetId}:${payload?.timestamp}`;
|
|
349
|
+
if (sig === lastWrittenConnectStatusSignature && process.env.ASM_TEST !== "1") {
|
|
350
|
+
return;
|
|
351
|
+
}
|
|
352
|
+
lastWrittenConnectStatusSignature = sig;
|
|
353
|
+
|
|
354
|
+
const content = `window.__CONNECT_STATUS__ = ${JSON.stringify(payload)};\n`;
|
|
355
|
+
for (const dir of targetDirs) {
|
|
356
|
+
try {
|
|
357
|
+
const jsFile = path.join(dir, "connect-status.js");
|
|
358
|
+
fs.writeFileSync(jsFile, content, "utf8");
|
|
359
|
+
const jsonFile = path.join(dir, "connect-status.json");
|
|
360
|
+
fs.writeFileSync(jsonFile, JSON.stringify(payload, null, 2), "utf8");
|
|
361
|
+
} catch {}
|
|
362
|
+
}
|
|
363
|
+
} catch {}
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
export function readConnectStatusFile() {
|
|
367
|
+
try {
|
|
368
|
+
const dir = process.env.ASM_CACHE_DIR || path.join(__dirname, "page");
|
|
369
|
+
const jsonFile = path.join(dir, "connect-status.json");
|
|
370
|
+
if (fs.existsSync(jsonFile)) {
|
|
371
|
+
return JSON.parse(fs.readFileSync(jsonFile, "utf8"));
|
|
372
|
+
}
|
|
373
|
+
} catch {}
|
|
374
|
+
return null;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
export function clearConnectRequestFromPluginsJson(nonceToClear = null) {
|
|
378
|
+
try {
|
|
379
|
+
if (!fs.existsSync(MAGPIE_PLUGINS_JSON)) return;
|
|
380
|
+
const raw = fs.readFileSync(MAGPIE_PLUGINS_JSON, "utf8");
|
|
381
|
+
const parsed = JSON.parse(raw);
|
|
382
|
+
const entry = (parsed?.plugins || []).find((p) => {
|
|
383
|
+
const spec = String(p?.spec || "").toLowerCase();
|
|
384
|
+
return spec.includes("agent-space-manager") || spec.includes("smart-middleware");
|
|
385
|
+
});
|
|
386
|
+
if (entry?.options?.connectRequest) {
|
|
387
|
+
if (!nonceToClear || entry.options.connectRequest.nonce === nonceToClear) {
|
|
388
|
+
delete entry.options.connectRequest;
|
|
389
|
+
fs.writeFileSync(MAGPIE_PLUGINS_JSON, JSON.stringify(parsed, null, 2), "utf8");
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
} catch {}
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
export async function runConnectAction(targetIde, isProject = false, nonce = null) {
|
|
396
|
+
const cfg = loadHubConfig();
|
|
397
|
+
const effHub = getEffectiveHubRoot(cfg);
|
|
398
|
+
let connectRes;
|
|
399
|
+
|
|
400
|
+
if (isProject) {
|
|
401
|
+
const plugins = scanPlugins(effHub);
|
|
402
|
+
connectRes = syncAllIdes(cfg, plugins);
|
|
403
|
+
} else {
|
|
404
|
+
connectRes = connectAgent(cfg, targetIde, { effHub });
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
// Ensure bridge and activeAgents are populated from file or return object
|
|
408
|
+
let bridge = connectRes.bridge || null;
|
|
409
|
+
let activeAgents = connectRes.activeAgents || [];
|
|
410
|
+
if (!bridge || Object.keys(bridge).length === 0) {
|
|
411
|
+
try {
|
|
412
|
+
const bridgePath = path.join(effHub, "agent-space-bridge.json");
|
|
413
|
+
if (fs.existsSync(bridgePath)) {
|
|
414
|
+
bridge = JSON.parse(fs.readFileSync(bridgePath, "utf8"));
|
|
415
|
+
activeAgents = bridge.activeAgents || [];
|
|
416
|
+
}
|
|
417
|
+
} catch {}
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
const payload = {
|
|
421
|
+
success: connectRes.success !== false,
|
|
422
|
+
nonce,
|
|
423
|
+
targetId: targetIde?.id || targetIde?.agentType || "custom",
|
|
424
|
+
targetName: targetIde?.name || targetIde?.id || "Agent",
|
|
425
|
+
bridge: bridge || {},
|
|
426
|
+
activeAgents: activeAgents.length > 0 ? activeAgents : (bridge?.activeAgents || []),
|
|
427
|
+
result: connectRes.result || connectRes.sync || connectRes,
|
|
428
|
+
sync: connectRes.sync || connectRes.result || connectRes,
|
|
429
|
+
error: connectRes.error || null,
|
|
430
|
+
timestamp: Date.now(),
|
|
431
|
+
};
|
|
432
|
+
|
|
433
|
+
writeConnectStatusFile(payload);
|
|
434
|
+
if (nonce) {
|
|
435
|
+
clearConnectRequestFromPluginsJson(nonce);
|
|
436
|
+
}
|
|
437
|
+
return payload;
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
export function handleConnectRequest(req) {
|
|
441
|
+
if (!req || typeof req !== "object" || !req.nonce) return;
|
|
442
|
+
if (req.nonce === lastConnectNonce) return;
|
|
443
|
+
if (connectBusy) {
|
|
444
|
+
pendingConnectRequest = req;
|
|
445
|
+
return;
|
|
446
|
+
}
|
|
447
|
+
lastConnectNonce = req.nonce;
|
|
448
|
+
connectBusy = true;
|
|
449
|
+
|
|
450
|
+
const target = req.target || req.ide || { id: req.id, agentType: req.agentType };
|
|
451
|
+
runConnectAction(target, Boolean(req.isProject), req.nonce)
|
|
452
|
+
.catch(() => {})
|
|
453
|
+
.finally(() => {
|
|
454
|
+
connectBusy = false;
|
|
455
|
+
if (pendingConnectRequest) {
|
|
456
|
+
const next = pendingConnectRequest;
|
|
457
|
+
pendingConnectRequest = null;
|
|
458
|
+
handleConnectRequest(next);
|
|
459
|
+
}
|
|
460
|
+
});
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
let magpieWasRunning = false;
|
|
464
|
+
let magpieDeadTicks = 0;
|
|
465
|
+
|
|
466
|
+
export function resetMagpieLivenessForTest() {
|
|
467
|
+
magpieWasRunning = false;
|
|
468
|
+
magpieDeadTicks = 0;
|
|
469
|
+
lastOmnirouteStartAttempt = 0;
|
|
470
|
+
if (typeof resetOmnirouteStartAttemptForTest === "function") {
|
|
471
|
+
resetOmnirouteStartAttemptForTest();
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
export async function handleMagpieLivenessCheck(magpieAlive, customPort = null, stopFn = stopOmniroute) {
|
|
476
|
+
if (magpieAlive) {
|
|
477
|
+
magpieWasRunning = true;
|
|
478
|
+
magpieDeadTicks = 0;
|
|
479
|
+
return { magpieAlive: true, omnirouteStopped: false };
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
magpieDeadTicks++;
|
|
483
|
+
magpieWasRunning = false;
|
|
484
|
+
// OmniRoute runs independently; closing Magpie does NOT disable OmniRoute
|
|
485
|
+
return { magpieAlive: false, omnirouteStopped: false, ticks: magpieDeadTicks };
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
export function startMagpieConfigWatcher() {
|
|
489
|
+
if (magpieWatchInterval || process.env.ASM_NO_SERVER) return;
|
|
490
|
+
// Initialize lastOmnirouteNonce from plugins.json on startup to avoid replaying any old requests
|
|
491
|
+
try {
|
|
492
|
+
const parsed = JSON.parse(fs.readFileSync(MAGPIE_PLUGINS_JSON, "utf8"));
|
|
493
|
+
const entry = (parsed?.plugins || []).find((p) => String(p?.spec || "").toLowerCase().includes("agent-space-manager"));
|
|
494
|
+
lastOmnirouteNonce = entry?.options?.omnirouteRequest?.nonce || null;
|
|
495
|
+
clearOmnirouteRequestFromPluginsJson();
|
|
496
|
+
} catch {}
|
|
497
|
+
// During startup, check status health
|
|
498
|
+
runOmnirouteAction("status").catch(() => {});
|
|
499
|
+
syncFromMagpiePluginsJson(true);
|
|
500
|
+
magpieWatchInterval = setInterval(() => {
|
|
501
|
+
syncFromMagpiePluginsJson(false);
|
|
502
|
+
}, 2000);
|
|
503
|
+
if (typeof magpieWatchInterval.unref === "function") {
|
|
504
|
+
magpieWatchInterval.unref();
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
export function ensureBackgroundDaemon() {
|
|
509
|
+
if (process.env.ASM_NO_SERVER || process.env.ASM_DAEMON_CHILD === "1") return;
|
|
510
|
+
const req = http.get(`http://127.0.0.1:${API_PORT}/api/status`, { timeout: 600 }, (res) => {
|
|
511
|
+
res.resume();
|
|
512
|
+
});
|
|
513
|
+
req.on("error", () => {
|
|
514
|
+
try {
|
|
515
|
+
const serverScript = path.join(__dirname, "server.mjs");
|
|
516
|
+
const child = spawn(process.execPath, [serverScript, "--daemon"], {
|
|
517
|
+
cwd: __dirname,
|
|
518
|
+
detached: true,
|
|
519
|
+
stdio: "ignore",
|
|
520
|
+
windowsHide: true,
|
|
521
|
+
env: { ...process.env, ASM_DAEMON_CHILD: "1" },
|
|
522
|
+
});
|
|
523
|
+
child.unref();
|
|
524
|
+
} catch {}
|
|
525
|
+
});
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
export function startApiServer(port = API_PORT) {
|
|
529
|
+
if (activeServer && port === API_PORT) return activeServer;
|
|
530
|
+
|
|
531
|
+
const server = http.createServer(async (req, res) => {
|
|
532
|
+
const originAllowed = setCorsHeaders(req, res);
|
|
533
|
+
|
|
534
|
+
if (req.method === "OPTIONS") {
|
|
535
|
+
res.writeHead(originAllowed ? 200 : 403);
|
|
536
|
+
res.end();
|
|
537
|
+
return;
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
// Block cross-origin mutating requests from untrusted external websites
|
|
541
|
+
if (!originAllowed && req.method !== "GET") {
|
|
542
|
+
res.writeHead(403, { "Content-Type": "application/json" });
|
|
543
|
+
res.end(JSON.stringify({ success: false, error: "Forbidden origin" }));
|
|
544
|
+
return;
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
const parsedUrl = new URL(req.url || "/", `http://127.0.0.1:${port}`);
|
|
548
|
+
const pathname = parsedUrl.pathname;
|
|
549
|
+
const query = Object.fromEntries(parsedUrl.searchParams.entries());
|
|
550
|
+
|
|
551
|
+
try {
|
|
552
|
+
if (pathname === "/api/status") {
|
|
553
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
554
|
+
res.end(JSON.stringify({ status: "ok", port: server.address()?.port || port, timestamp: Date.now() }));
|
|
555
|
+
return;
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
if (pathname === "/api/agents" && req.method === "GET") {
|
|
559
|
+
const agents = listAgentProfilesForUi();
|
|
560
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
561
|
+
res.end(JSON.stringify({ success: true, agents }));
|
|
562
|
+
return;
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
if (pathname === "/api/config" && req.method === "GET") {
|
|
566
|
+
const cfg = loadHubConfig();
|
|
567
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
568
|
+
res.end(JSON.stringify(cfg));
|
|
569
|
+
return;
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
if (pathname === "/api/omniroute/status" && req.method === "GET") {
|
|
573
|
+
const portParam = query.port ? parseInt(query.port, 10) : null;
|
|
574
|
+
const cfg = loadHubConfig();
|
|
575
|
+
const status = await checkOmnirouteStatus(portParam, cfg);
|
|
576
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
577
|
+
res.end(JSON.stringify({ success: true, ...status }));
|
|
578
|
+
return;
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
if (pathname === "/action-omniroute.js" || pathname === "/api/omniroute/action.js") {
|
|
582
|
+
const action = query.action || "status";
|
|
583
|
+
const portParam = query.port ? parseInt(query.port, 10) : null;
|
|
584
|
+
const nonce = query.nonce || null;
|
|
585
|
+
const payload = await runOmnirouteAction(action, portParam, nonce);
|
|
586
|
+
res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
|
|
587
|
+
res.writeHead(200, { "Content-Type": "application/javascript; charset=utf-8" });
|
|
588
|
+
res.end(`window.__OMNIROUTE_STATUS__ = ${JSON.stringify(payload)};\n`);
|
|
589
|
+
return;
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
if (pathname === "/action-connect.js" || pathname === "/api/connect/action.js") {
|
|
593
|
+
const id = query.id || query.agentType || "antigravity";
|
|
594
|
+
const agentType = query.agentType || query.id || "antigravity";
|
|
595
|
+
const name = query.name || id;
|
|
596
|
+
const nonce = query.nonce || null;
|
|
597
|
+
const targetIde = { id, agentType, name };
|
|
598
|
+
const payload = await runConnectAction(targetIde, false, nonce);
|
|
599
|
+
res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
|
|
600
|
+
res.writeHead(200, { "Content-Type": "application/javascript; charset=utf-8" });
|
|
601
|
+
res.end(`window.__CONNECT_STATUS__ = ${JSON.stringify(payload)};\n`);
|
|
602
|
+
return;
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
if (pathname === "/api/connect-status" && req.method === "GET") {
|
|
606
|
+
const status = readConnectStatusFile();
|
|
607
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
608
|
+
res.end(JSON.stringify(status || { success: true, status: "idle", timestamp: 0 }));
|
|
609
|
+
return;
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
if (pathname === "/api/omniroute/start") {
|
|
613
|
+
if (req.method === "GET") {
|
|
614
|
+
const port = query.port ? parseInt(query.port, 10) : null;
|
|
615
|
+
const payload = await runOmnirouteAction("start", port);
|
|
616
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
617
|
+
res.end(JSON.stringify(payload));
|
|
618
|
+
return;
|
|
619
|
+
}
|
|
620
|
+
if (req.method === "POST") {
|
|
621
|
+
let body = "";
|
|
622
|
+
req.on("data", (chunk) => { body += chunk; });
|
|
623
|
+
req.on("end", async () => {
|
|
624
|
+
try {
|
|
625
|
+
const data = body ? JSON.parse(body) : {};
|
|
626
|
+
const payload = await runOmnirouteAction("start", data.port);
|
|
627
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
628
|
+
res.end(JSON.stringify(payload));
|
|
629
|
+
} catch (err) {
|
|
630
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
631
|
+
res.end(JSON.stringify({ success: false, error: err.message }));
|
|
632
|
+
}
|
|
633
|
+
});
|
|
634
|
+
return;
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
if (pathname === "/api/omniroute/stop") {
|
|
639
|
+
if (req.method === "GET") {
|
|
640
|
+
const port = query.port ? parseInt(query.port, 10) : null;
|
|
641
|
+
const payload = await runOmnirouteAction("stop", port);
|
|
642
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
643
|
+
res.end(JSON.stringify(payload));
|
|
644
|
+
return;
|
|
645
|
+
}
|
|
646
|
+
if (req.method === "POST") {
|
|
647
|
+
let body = "";
|
|
648
|
+
req.on("data", (chunk) => { body += chunk; });
|
|
649
|
+
req.on("end", async () => {
|
|
650
|
+
try {
|
|
651
|
+
const data = body ? JSON.parse(body) : {};
|
|
652
|
+
const payload = await runOmnirouteAction("stop", data.port);
|
|
653
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
654
|
+
res.end(JSON.stringify(payload));
|
|
655
|
+
} catch (err) {
|
|
656
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
657
|
+
res.end(JSON.stringify({ success: false, error: err.message }));
|
|
658
|
+
}
|
|
659
|
+
});
|
|
660
|
+
return;
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
if (pathname === "/api/omniroute/open") {
|
|
665
|
+
if (req.method === "GET") {
|
|
666
|
+
const cfg = loadHubConfig();
|
|
667
|
+
const port = query.port ? parseInt(query.port, 10) : getOmniroutePort(cfg);
|
|
668
|
+
const targetUrl = query.url || `http://localhost:${port}`;
|
|
669
|
+
const ok = openUrlInBrowser(targetUrl);
|
|
670
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
671
|
+
res.end(JSON.stringify({ success: ok, url: targetUrl }));
|
|
672
|
+
return;
|
|
673
|
+
}
|
|
674
|
+
if (req.method === "POST") {
|
|
675
|
+
let body = "";
|
|
676
|
+
req.on("data", (chunk) => { body += chunk; });
|
|
677
|
+
req.on("end", () => {
|
|
678
|
+
try {
|
|
679
|
+
const data = body ? JSON.parse(body) : {};
|
|
680
|
+
const cfg = loadHubConfig();
|
|
681
|
+
const port = data.port || getOmniroutePort(cfg);
|
|
682
|
+
const targetUrl = data.url || query.url || `http://localhost:${port}`;
|
|
683
|
+
const ok = openUrlInBrowser(targetUrl);
|
|
684
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
685
|
+
res.end(JSON.stringify({ success: ok, url: targetUrl }));
|
|
686
|
+
} catch (err) {
|
|
687
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
688
|
+
res.end(JSON.stringify({ success: false, error: err.message }));
|
|
689
|
+
}
|
|
690
|
+
});
|
|
691
|
+
return;
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
if (pathname === "/api/agent/scan-foreign" && req.method === "POST") {
|
|
696
|
+
let body = "";
|
|
697
|
+
req.on("data", (chunk) => { body += chunk; });
|
|
698
|
+
req.on("end", () => {
|
|
699
|
+
try {
|
|
700
|
+
const data = body ? JSON.parse(body) : {};
|
|
701
|
+
const agentDef = data.agent || data.ide || data;
|
|
702
|
+
const cfg = loadHubConfig();
|
|
703
|
+
const effHub = getEffectiveHubRoot(cfg);
|
|
704
|
+
const plugins = scanPlugins(effHub);
|
|
705
|
+
const scan = scanAgentForeignComponents(agentDef, cfg, plugins);
|
|
706
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
707
|
+
res.end(JSON.stringify({ success: true, ...scan }));
|
|
708
|
+
} catch (err) {
|
|
709
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
710
|
+
res.end(JSON.stringify({ success: false, error: err.message }));
|
|
711
|
+
}
|
|
712
|
+
});
|
|
713
|
+
return;
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
if (pathname === "/api/agent/clean-foreign" && req.method === "POST") {
|
|
717
|
+
let body = "";
|
|
718
|
+
req.on("data", (chunk) => { body += chunk; });
|
|
719
|
+
req.on("end", () => {
|
|
720
|
+
try {
|
|
721
|
+
const data = body ? JSON.parse(body) : {};
|
|
722
|
+
const components = Array.isArray(data.components) ? data.components : [];
|
|
723
|
+
const result = cleanAgentForeignComponents(components);
|
|
724
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
725
|
+
res.end(JSON.stringify(result));
|
|
726
|
+
} catch (err) {
|
|
727
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
728
|
+
res.end(JSON.stringify({ success: false, error: err.message }));
|
|
729
|
+
}
|
|
730
|
+
});
|
|
731
|
+
return;
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
if (pathname === "/api/plugins" && req.method === "GET") {
|
|
735
|
+
const rawPath = query.path !== undefined ? String(query.path).trim() : "";
|
|
736
|
+
const reqPath = rawPath || resolveHubRoot();
|
|
737
|
+
const plugins = scanPlugins(reqPath);
|
|
738
|
+
const categories = buildCategoriesRegistry(plugins, reqPath);
|
|
739
|
+
updatePluginsCache(reqPath, plugins, categories);
|
|
740
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
741
|
+
res.end(JSON.stringify({ success: true, path: reqPath, count: plugins.length, plugins, categories }));
|
|
742
|
+
return;
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
if (pathname === "/api/resolve" && req.method === "GET") {
|
|
746
|
+
const rawPath = query.path ? String(query.path).trim() : "";
|
|
747
|
+
const mode = query.mode ? String(query.mode).trim() : "ide";
|
|
748
|
+
const result = resolveDroppedTarget(rawPath, mode);
|
|
749
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
750
|
+
res.end(JSON.stringify(result));
|
|
751
|
+
return;
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
if (pathname === "/api/browse" && req.method === "GET") {
|
|
755
|
+
const type = query.type ? String(query.type).trim() : "file";
|
|
756
|
+
const result = await browseFileSystem(type);
|
|
757
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
758
|
+
res.end(JSON.stringify(result));
|
|
759
|
+
return;
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
if (pathname === "/api/detect-config" && req.method === "GET") {
|
|
763
|
+
const name = query.name ? String(query.name).trim() : "";
|
|
764
|
+
const exePath = query.exePath ? String(query.exePath).trim() : "";
|
|
765
|
+
const agentType = inferAgentType(name, exePath);
|
|
766
|
+
const detected = detectAgentConfigPath(name, exePath);
|
|
767
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
768
|
+
res.end(JSON.stringify({ success: true, agentType, configPath: detected }));
|
|
769
|
+
return;
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
if (pathname === "/api/check-modifications" && req.method === "GET") {
|
|
773
|
+
const rawPath = query.path !== undefined ? String(query.path).trim() : "";
|
|
774
|
+
const reqPath = rawPath || resolveHubRoot();
|
|
775
|
+
const result = checkComponentsModifications(reqPath);
|
|
776
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
777
|
+
res.end(JSON.stringify({ success: true, ...result }));
|
|
778
|
+
return;
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
if (pathname === "/api/startup-sync" && req.method === "POST") {
|
|
782
|
+
let body = "";
|
|
783
|
+
req.on("data", (chunk) => { body += chunk; });
|
|
784
|
+
req.on("end", () => {
|
|
785
|
+
try {
|
|
786
|
+
const customCfg = body ? JSON.parse(body) : null;
|
|
787
|
+
const result = checkAndAutoReconnectOnStartup(customCfg);
|
|
788
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
789
|
+
res.end(JSON.stringify(result));
|
|
790
|
+
} catch (err) {
|
|
791
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
792
|
+
res.end(JSON.stringify({ success: false, error: err.message }));
|
|
793
|
+
}
|
|
794
|
+
});
|
|
795
|
+
return;
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
if (pathname === "/api/central-update-check" && (req.method === "GET" || req.method === "POST")) {
|
|
799
|
+
const handleCheck = (force, reqPath) => {
|
|
800
|
+
try {
|
|
801
|
+
const cleanPath = reqPath || resolveHubRoot();
|
|
802
|
+
const result = checkCentralizedUpstreamUpdates(cleanPath, { force });
|
|
803
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
804
|
+
res.end(JSON.stringify(result));
|
|
805
|
+
} catch (err) {
|
|
806
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
807
|
+
res.end(JSON.stringify({ success: false, error: err.message }));
|
|
808
|
+
}
|
|
809
|
+
};
|
|
810
|
+
|
|
811
|
+
if (req.method === "POST") {
|
|
812
|
+
let body = "";
|
|
813
|
+
req.on("data", (chunk) => { body += chunk; });
|
|
814
|
+
req.on("end", () => {
|
|
815
|
+
try {
|
|
816
|
+
const data = body ? JSON.parse(body) : {};
|
|
817
|
+
handleCheck(Boolean(data.force), data.hubRoot);
|
|
818
|
+
} catch (err) {
|
|
819
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
820
|
+
res.end(JSON.stringify({ success: false, error: err.message }));
|
|
821
|
+
}
|
|
822
|
+
});
|
|
823
|
+
return;
|
|
824
|
+
} else {
|
|
825
|
+
const rawPath = query.path !== undefined ? String(query.path).trim() : "";
|
|
826
|
+
const force = query.force === "true" || query.force === "1";
|
|
827
|
+
handleCheck(force, rawPath);
|
|
828
|
+
return;
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
if (pathname === "/api/central-update-status" && req.method === "GET") {
|
|
833
|
+
const rawPath = query.path !== undefined ? String(query.path).trim() : "";
|
|
834
|
+
const cleanPath = rawPath || resolveHubRoot();
|
|
835
|
+
const state = loadCentralizedUpstreamUpdateState(cleanPath);
|
|
836
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
837
|
+
res.end(JSON.stringify({ success: true, state: state || null }));
|
|
838
|
+
return;
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
if ((pathname === "/api/recheck-status" || pathname === "/api/recheck-status-dots") && (req.method === "GET" || req.method === "POST")) {
|
|
842
|
+
const handleRecheck = (customCfg) => {
|
|
843
|
+
try {
|
|
844
|
+
const cfg = customCfg || loadHubConfig();
|
|
845
|
+
const effHub = getEffectiveHubRoot(cfg);
|
|
846
|
+
const plugins = scanPlugins(effHub);
|
|
847
|
+
const statusResult = recheckConnectedAgentsStatus(cfg, plugins);
|
|
848
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
849
|
+
res.end(JSON.stringify({ success: true, ...statusResult }));
|
|
850
|
+
} catch (err) {
|
|
851
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
852
|
+
res.end(JSON.stringify({ success: false, error: err.message }));
|
|
853
|
+
}
|
|
854
|
+
};
|
|
855
|
+
|
|
856
|
+
if (req.method === "POST") {
|
|
857
|
+
let body = "";
|
|
858
|
+
req.on("data", (chunk) => { body += chunk; });
|
|
859
|
+
req.on("end", () => {
|
|
860
|
+
try {
|
|
861
|
+
const customCfg = body ? JSON.parse(body) : null;
|
|
862
|
+
handleRecheck(customCfg);
|
|
863
|
+
} catch {
|
|
864
|
+
handleRecheck(null);
|
|
865
|
+
}
|
|
866
|
+
});
|
|
867
|
+
} else {
|
|
868
|
+
handleRecheck(null);
|
|
869
|
+
}
|
|
870
|
+
return;
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
if (pathname === "/api/connect" && req.method === "POST") {
|
|
874
|
+
let body = "";
|
|
875
|
+
req.on("data", (chunk) => { body += chunk; });
|
|
876
|
+
req.on("end", () => {
|
|
877
|
+
try {
|
|
878
|
+
const parsed = JSON.parse(body || "{}");
|
|
879
|
+
const targetIde = parsed.ide && typeof parsed.ide === "object" ? parsed.ide : parsed;
|
|
880
|
+
if (!targetIde || (!targetIde.id && !targetIde.agentType)) {
|
|
881
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
882
|
+
res.end(JSON.stringify({ success: false, error: "Missing required agent id or agentType" }));
|
|
883
|
+
return;
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
const config = loadHubConfig();
|
|
887
|
+
const effHub = getEffectiveHubRoot(config);
|
|
888
|
+
const customPlugins = Array.isArray(parsed.plugins) ? parsed.plugins : null;
|
|
889
|
+
const connectRes = connectAgent(config, targetIde, {
|
|
890
|
+
effHub,
|
|
891
|
+
customPlugins,
|
|
892
|
+
});
|
|
893
|
+
|
|
894
|
+
// Ensure bridge and activeAgents are populated from file or return object
|
|
895
|
+
let bridge = connectRes.bridge || null;
|
|
896
|
+
let activeAgents = connectRes.activeAgents || [];
|
|
897
|
+
if (!bridge || Object.keys(bridge).length === 0) {
|
|
898
|
+
try {
|
|
899
|
+
const bridgePath = path.join(effHub, "agent-space-bridge.json");
|
|
900
|
+
if (fs.existsSync(bridgePath)) {
|
|
901
|
+
bridge = JSON.parse(fs.readFileSync(bridgePath, "utf8"));
|
|
902
|
+
activeAgents = bridge.activeAgents || [];
|
|
903
|
+
}
|
|
904
|
+
} catch {}
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
const payload = {
|
|
908
|
+
success: connectRes.success !== false,
|
|
909
|
+
bridge: bridge || {},
|
|
910
|
+
activeAgents: activeAgents.length > 0 ? activeAgents : (bridge?.activeAgents || []),
|
|
911
|
+
result: connectRes.result || connectRes.sync || connectRes,
|
|
912
|
+
hubConfig: connectRes.hubConfig || config,
|
|
913
|
+
};
|
|
914
|
+
|
|
915
|
+
writeConnectStatusFile({
|
|
916
|
+
success: connectRes.success !== false,
|
|
917
|
+
nonce: parsed.nonce || null,
|
|
918
|
+
targetId: targetIde.id || targetIde.agentType,
|
|
919
|
+
targetName: targetIde.name || targetIde.id,
|
|
920
|
+
result: connectRes.result || connectRes.sync || connectRes,
|
|
921
|
+
sync: connectRes.sync || connectRes.result || connectRes,
|
|
922
|
+
timestamp: Date.now(),
|
|
923
|
+
});
|
|
924
|
+
|
|
925
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
926
|
+
res.end(JSON.stringify(payload));
|
|
927
|
+
} catch (err) {
|
|
928
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
929
|
+
res.end(JSON.stringify({ success: false, error: err.message }));
|
|
930
|
+
}
|
|
931
|
+
});
|
|
932
|
+
return;
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
if (pathname === "/api/save" && req.method === "POST") {
|
|
936
|
+
let body = "";
|
|
937
|
+
req.on("data", (chunk) => { body += chunk; });
|
|
938
|
+
req.on("end", () => {
|
|
939
|
+
try {
|
|
940
|
+
const raw = JSON.parse(body || "{}");
|
|
941
|
+
const config = raw.config && typeof raw.config === "object" ? raw.config : raw;
|
|
942
|
+
const shouldSync = Boolean(
|
|
943
|
+
raw.sync === true ||
|
|
944
|
+
raw.connect === true ||
|
|
945
|
+
config.sync === true ||
|
|
946
|
+
config.connect === true
|
|
947
|
+
);
|
|
948
|
+
|
|
949
|
+
saveHubConfig(config);
|
|
950
|
+
const effPath = getEffectiveHubRoot(config);
|
|
951
|
+
const plugins = Array.isArray(raw.plugins) ? raw.plugins : scanPlugins(effPath);
|
|
952
|
+
const categories = buildCategoriesRegistry(plugins, effPath);
|
|
953
|
+
updatePluginsCache(effPath, plugins, categories);
|
|
954
|
+
|
|
955
|
+
let syncRes = null;
|
|
956
|
+
if (shouldSync) {
|
|
957
|
+
syncRes = syncAllIdes(config, plugins);
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
961
|
+
res.end(
|
|
962
|
+
JSON.stringify({
|
|
963
|
+
success: true,
|
|
964
|
+
config,
|
|
965
|
+
pluginCount: plugins.length,
|
|
966
|
+
plugins,
|
|
967
|
+
categories,
|
|
968
|
+
synced: shouldSync,
|
|
969
|
+
...(syncRes ? { sync: syncRes } : {}),
|
|
970
|
+
})
|
|
971
|
+
);
|
|
972
|
+
} catch (err) {
|
|
973
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
974
|
+
res.end(JSON.stringify({ success: false, error: err.message }));
|
|
975
|
+
}
|
|
976
|
+
});
|
|
977
|
+
return;
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
if (pathname === "/api/rescan" && req.method === "POST") {
|
|
981
|
+
let body = "";
|
|
982
|
+
req.on("data", (chunk) => { body += chunk; });
|
|
983
|
+
req.on("end", () => {
|
|
984
|
+
try {
|
|
985
|
+
const data = body ? JSON.parse(body) : {};
|
|
986
|
+
const config = loadHubConfig();
|
|
987
|
+
if (data.hubRoot && typeof data.hubRoot === "string") {
|
|
988
|
+
config.hubRoot = data.hubRoot.trim();
|
|
989
|
+
saveHubConfig(config);
|
|
990
|
+
}
|
|
991
|
+
const effPath = getEffectiveHubRoot(config);
|
|
992
|
+
const plugins = scanPlugins(effPath);
|
|
993
|
+
const categories = buildCategoriesRegistry(plugins, effPath);
|
|
994
|
+
updatePluginsCache(effPath, plugins, categories);
|
|
995
|
+
const syncRes = syncAllIdes(config, plugins);
|
|
996
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
997
|
+
res.end(
|
|
998
|
+
JSON.stringify({
|
|
999
|
+
success: true,
|
|
1000
|
+
hubRoot: effPath,
|
|
1001
|
+
pluginCount: plugins.length,
|
|
1002
|
+
plugins,
|
|
1003
|
+
categories,
|
|
1004
|
+
sync: syncRes,
|
|
1005
|
+
timestamp: Date.now(),
|
|
1006
|
+
})
|
|
1007
|
+
);
|
|
1008
|
+
} catch (err) {
|
|
1009
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
1010
|
+
res.end(JSON.stringify({ success: false, error: err.message }));
|
|
1011
|
+
}
|
|
1012
|
+
});
|
|
1013
|
+
return;
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
if (pathname === "/api/remove-ide" && req.method === "POST") {
|
|
1017
|
+
let body = "";
|
|
1018
|
+
req.on("data", (chunk) => { body += chunk; });
|
|
1019
|
+
req.on("end", () => {
|
|
1020
|
+
try {
|
|
1021
|
+
const { ideId, killProcesses } = JSON.parse(body || "{}");
|
|
1022
|
+
if (!ideId) {
|
|
1023
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
1024
|
+
res.end(JSON.stringify({ success: false, error: "ideId required" }));
|
|
1025
|
+
return;
|
|
1026
|
+
}
|
|
1027
|
+
const config = loadHubConfig();
|
|
1028
|
+
const idx = (config.ides || []).findIndex((i) => i.id === ideId);
|
|
1029
|
+
if (idx === -1) {
|
|
1030
|
+
res.writeHead(404, { "Content-Type": "application/json" });
|
|
1031
|
+
res.end(JSON.stringify({ success: false, error: `IDE '${ideId}' not found` }));
|
|
1032
|
+
return;
|
|
1033
|
+
}
|
|
1034
|
+
const [removedIde] = config.ides.splice(idx, 1);
|
|
1035
|
+
unlinkAllForIde(removedIde, killProcesses === true);
|
|
1036
|
+
config.projects = (config.projects || []).filter((p) => p.ideId !== ideId);
|
|
1037
|
+
saveHubConfig(config);
|
|
1038
|
+
const effPath = getEffectiveHubRoot(config);
|
|
1039
|
+
const plugins = scanPlugins(effPath);
|
|
1040
|
+
const syncRes = syncAllIdes(config, plugins);
|
|
1041
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
1042
|
+
res.end(JSON.stringify({ success: true, removed: ideId, sync: syncRes }));
|
|
1043
|
+
} catch (err) {
|
|
1044
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
1045
|
+
res.end(JSON.stringify({ success: false, error: err.message }));
|
|
1046
|
+
}
|
|
1047
|
+
});
|
|
1048
|
+
return;
|
|
1049
|
+
}
|
|
1050
|
+
|
|
1051
|
+
if (pathname === "/api/remove-project" && req.method === "POST") {
|
|
1052
|
+
let body = "";
|
|
1053
|
+
req.on("data", (chunk) => { body += chunk; });
|
|
1054
|
+
req.on("end", () => {
|
|
1055
|
+
try {
|
|
1056
|
+
const { projectId } = JSON.parse(body || "{}");
|
|
1057
|
+
if (!projectId) {
|
|
1058
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
1059
|
+
res.end(JSON.stringify({ success: false, error: "projectId required" }));
|
|
1060
|
+
return;
|
|
1061
|
+
}
|
|
1062
|
+
const config = loadHubConfig();
|
|
1063
|
+
const idx = (config.projects || []).findIndex((p) => p.id === projectId);
|
|
1064
|
+
if (idx === -1) {
|
|
1065
|
+
res.writeHead(404, { "Content-Type": "application/json" });
|
|
1066
|
+
res.end(JSON.stringify({ success: false, error: `Project '${projectId}' not found` }));
|
|
1067
|
+
return;
|
|
1068
|
+
}
|
|
1069
|
+
const [removedProj] = config.projects.splice(idx, 1);
|
|
1070
|
+
const parentIde = (config.ides || []).find((i) => i.id === removedProj.ideId) || null;
|
|
1071
|
+
unlinkAllForProject(removedProj, parentIde);
|
|
1072
|
+
saveHubConfig(config);
|
|
1073
|
+
const effPath = getEffectiveHubRoot(config);
|
|
1074
|
+
const plugins = scanPlugins(effPath);
|
|
1075
|
+
const syncRes = syncAllIdes(config, plugins);
|
|
1076
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
1077
|
+
res.end(JSON.stringify({ success: true, removed: projectId, sync: syncRes }));
|
|
1078
|
+
} catch (err) {
|
|
1079
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
1080
|
+
res.end(JSON.stringify({ success: false, error: err.message }));
|
|
1081
|
+
}
|
|
1082
|
+
});
|
|
1083
|
+
return;
|
|
1084
|
+
}
|
|
1085
|
+
|
|
1086
|
+
// Serve static files from ./page directory
|
|
1087
|
+
if (!pathname.startsWith("/api")) {
|
|
1088
|
+
let cleanRel = pathname === "/" ? "index.html" : pathname.replace(/^\/+/, "");
|
|
1089
|
+
let filePath = path.join(__dirname, "page", cleanRel);
|
|
1090
|
+
if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
|
|
1091
|
+
const ext = path.extname(filePath).toLowerCase();
|
|
1092
|
+
const mimeTypes = {
|
|
1093
|
+
".html": "text/html; charset=utf-8",
|
|
1094
|
+
".js": "application/javascript; charset=utf-8",
|
|
1095
|
+
".css": "text/css; charset=utf-8",
|
|
1096
|
+
".json": "application/json; charset=utf-8",
|
|
1097
|
+
".png": "image/png",
|
|
1098
|
+
".svg": "image/svg+xml",
|
|
1099
|
+
};
|
|
1100
|
+
res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
|
|
1101
|
+
res.setHeader("Pragma", "no-cache");
|
|
1102
|
+
res.setHeader("Expires", "0");
|
|
1103
|
+
res.writeHead(200, { "Content-Type": mimeTypes[ext] || "text/plain" });
|
|
1104
|
+
fs.createReadStream(filePath).pipe(res);
|
|
1105
|
+
return;
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
res.writeHead(404, { "Content-Type": "application/json" });
|
|
1110
|
+
res.end(JSON.stringify({ error: "Endpoint not found" }));
|
|
1111
|
+
} catch (err) {
|
|
1112
|
+
console.error("API Server Error:", err);
|
|
1113
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
1114
|
+
res.end(JSON.stringify({ success: false, error: err.message }));
|
|
1115
|
+
}
|
|
1116
|
+
});
|
|
1117
|
+
|
|
1118
|
+
server.on("error", (err) => {
|
|
1119
|
+
if (err.code === "EADDRINUSE") {
|
|
1120
|
+
console.error(`Port ${port} already in use, reusing active daemon.`);
|
|
1121
|
+
} else {
|
|
1122
|
+
console.error("API Server error:", err);
|
|
1123
|
+
}
|
|
1124
|
+
});
|
|
1125
|
+
|
|
1126
|
+
server.listen(port, "127.0.0.1", () => {
|
|
1127
|
+
const actualPort = server.address()?.port || port;
|
|
1128
|
+
if (!process.env.ASM_NO_SERVER) {
|
|
1129
|
+
console.error(`Agent Space Manager API Server listening on http://127.0.0.1:${actualPort}`);
|
|
1130
|
+
}
|
|
1131
|
+
});
|
|
1132
|
+
|
|
1133
|
+
if (port === API_PORT) {
|
|
1134
|
+
activeServer = server;
|
|
1135
|
+
try {
|
|
1136
|
+
const startupRes = checkAndAutoReconnectOnStartup();
|
|
1137
|
+
if (!process.env.ASM_NO_SERVER && process.env.NODE_ENV !== "test" && process.env.ASM_TEST !== "1") {
|
|
1138
|
+
console.error(`[Startup] Components Storage Path: ${startupRes.summary}`);
|
|
1139
|
+
if (startupRes.autoReconnected) {
|
|
1140
|
+
console.error(`[Startup] Auto-reconnected ${startupRes.connectedAgentsCount} connected agent(s).`);
|
|
1141
|
+
}
|
|
1142
|
+
if (startupRes.centralUpdates?.checked) {
|
|
1143
|
+
console.error(`[Startup] Central Upstream Update: ${startupRes.centralUpdates.summary}`);
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
} catch {}
|
|
1147
|
+
startMagpieConfigWatcher();
|
|
1148
|
+
}
|
|
1149
|
+
return server;
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
if (process.argv[1] && process.argv[1].endsWith("server.mjs")) {
|
|
1153
|
+
startApiServer();
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
if (!process.env.ASM_NO_SERVER && process.env.NODE_ENV !== "test" && process.env.ASM_TEST !== "1") {
|
|
1157
|
+
const onProcessSignal = () => {
|
|
1158
|
+
try {
|
|
1159
|
+
stopOmnirouteSync();
|
|
1160
|
+
} catch {}
|
|
1161
|
+
process.exit(0);
|
|
1162
|
+
};
|
|
1163
|
+
process.on("SIGINT", onProcessSignal);
|
|
1164
|
+
process.on("SIGTERM", onProcessSignal);
|
|
1165
|
+
}
|