localmcp-cli 0.0.1 → 0.0.11
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/LICENSE +21 -0
- package/README.md +104 -2
- package/bin/cli.js +26 -1
- package/package.json +21 -9
- package/src/agents/hub.js +663 -0
- package/src/agents/providers.js +840 -0
- package/src/agents/store.js +524 -0
- package/src/cli/options.js +177 -0
- package/src/cli/runtime.js +126 -0
- package/src/cli/service.js +29 -0
- package/src/cli/tunnel.js +242 -0
- package/src/core/audit.js +105 -0
- package/src/core/auth.js +326 -0
- package/src/core/bounded-log.js +39 -0
- package/src/core/config.js +319 -0
- package/src/core/context-discovery.js +245 -0
- package/src/core/mesh.js +103 -0
- package/src/core/protocol.js +112 -0
- package/src/core/updater-client.js +165 -0
- package/src/server.js +260 -0
- package/src/tools/agents.js +149 -0
- package/src/tools/apply-patch.js +454 -0
- package/src/tools/diagnostics.js +158 -0
- package/src/tools/filesystem.js +1122 -0
- package/src/tools/gui-windows.js +268 -0
- package/src/tools/registry.js +119 -0
- package/src/tools/system.js +591 -0
|
@@ -0,0 +1,524 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import {
|
|
3
|
+
appendFileSync,
|
|
4
|
+
existsSync,
|
|
5
|
+
mkdirSync,
|
|
6
|
+
readFileSync,
|
|
7
|
+
renameSync,
|
|
8
|
+
rmSync,
|
|
9
|
+
statSync,
|
|
10
|
+
writeFileSync,
|
|
11
|
+
} from "node:fs";
|
|
12
|
+
import path from "node:path";
|
|
13
|
+
|
|
14
|
+
export const TASK_STATUSES = new Set([
|
|
15
|
+
"working",
|
|
16
|
+
"input_required",
|
|
17
|
+
"completed",
|
|
18
|
+
"failed",
|
|
19
|
+
"cancelled",
|
|
20
|
+
]);
|
|
21
|
+
|
|
22
|
+
export const TERMINAL_TASK_STATUSES = new Set([
|
|
23
|
+
"completed",
|
|
24
|
+
"failed",
|
|
25
|
+
"cancelled",
|
|
26
|
+
]);
|
|
27
|
+
|
|
28
|
+
export const DEFAULT_AGENT_TTL_MS = 24 * 60 * 60 * 1000;
|
|
29
|
+
export const DEFAULT_TASK_TTL_MS = 24 * 60 * 60 * 1000;
|
|
30
|
+
export const DEFAULT_POLL_INTERVAL_MS = 3000;
|
|
31
|
+
const MAX_INBOX_PER_AGENT = 200;
|
|
32
|
+
const MAX_TASKS_INDEX = 500;
|
|
33
|
+
|
|
34
|
+
export function sanitizeSensitiveText(value) {
|
|
35
|
+
return String(value ?? "")
|
|
36
|
+
.replace(/(secret-key=|x-secret-key[=: ]+)[^\s&"'`]+/gi, "$1[REDACTED]")
|
|
37
|
+
.replace(/(ANTIGRAVITY_CSRF_TOKEN[=: ]+)[^\s&"'`]+/gi, "$1[REDACTED]")
|
|
38
|
+
.replace(/("csrfToken"\s*:\s*")[^"]+(")/gi, "$1[REDACTED]$2");
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function normalizeId(raw) {
|
|
42
|
+
return String(raw ?? "").trim();
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function normalizeKey(raw) {
|
|
46
|
+
return normalizeId(raw).toLowerCase();
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function atomicWriteJson(filePath, data) {
|
|
50
|
+
mkdirSync(path.dirname(filePath), { recursive: true });
|
|
51
|
+
const tmp = `${filePath}.tmp.${process.pid}.${randomBytes(4).toString("hex")}`;
|
|
52
|
+
writeFileSync(tmp, `${JSON.stringify(data, null, 2)}\n`, "utf8");
|
|
53
|
+
renameSync(tmp, filePath);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function safeReadJson(filePath, fallback) {
|
|
57
|
+
try {
|
|
58
|
+
if (!existsSync(filePath)) return fallback;
|
|
59
|
+
return JSON.parse(readFileSync(filePath, "utf8"));
|
|
60
|
+
} catch {
|
|
61
|
+
return fallback;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export class AgentStore {
|
|
66
|
+
constructor(baseDir) {
|
|
67
|
+
this.hubDir = path.join(baseDir, "agent-hub");
|
|
68
|
+
this.registryPath = path.join(this.hubDir, "registry.json");
|
|
69
|
+
this.inboxPath = path.join(this.hubDir, "inbox.json");
|
|
70
|
+
this.tasksDir = path.join(this.hubDir, "tasks");
|
|
71
|
+
this.tasksIndexPath = path.join(this.tasksDir, "index.json");
|
|
72
|
+
mkdirSync(this.tasksDir, { recursive: true });
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
_loadRegistry() {
|
|
76
|
+
const raw = safeReadJson(this.registryPath, { agents: {} });
|
|
77
|
+
const agents = raw && typeof raw.agents === "object" && raw.agents ? raw.agents : {};
|
|
78
|
+
const now = Date.now();
|
|
79
|
+
let changed = false;
|
|
80
|
+
for (const [id, rec] of Object.entries(agents)) {
|
|
81
|
+
if (rec?.expiresAt && Date.parse(rec.expiresAt) <= now) {
|
|
82
|
+
delete agents[id];
|
|
83
|
+
changed = true;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
if (changed) {
|
|
87
|
+
atomicWriteJson(this.registryPath, { agents });
|
|
88
|
+
}
|
|
89
|
+
return Object.assign(Object.create(null), agents);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
_saveRegistry(agents) {
|
|
93
|
+
atomicWriteJson(this.registryPath, { agents });
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
_loadInbox() {
|
|
97
|
+
const raw = safeReadJson(this.inboxPath, { mailboxes: {} });
|
|
98
|
+
if (raw && typeof raw.mailboxes === "object" && raw.mailboxes) {
|
|
99
|
+
return Object.assign(Object.create(null), raw.mailboxes);
|
|
100
|
+
}
|
|
101
|
+
return Object.create(null);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
_saveInbox(mailboxes) {
|
|
105
|
+
atomicWriteJson(this.inboxPath, { mailboxes });
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
_loadTasksIndex() {
|
|
109
|
+
const raw = safeReadJson(this.tasksIndexPath, { order: [] });
|
|
110
|
+
return Array.isArray(raw?.order) ? raw.order : [];
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
_saveTasksIndex(order) {
|
|
114
|
+
atomicWriteJson(this.tasksIndexPath, { order: order.slice(-MAX_TASKS_INDEX) });
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
_taskDir(taskId) {
|
|
118
|
+
const safe = String(taskId || "");
|
|
119
|
+
if (!/^tsk_[a-f0-9]{16}$/.test(safe)) throw new Error("Invalid task_id.");
|
|
120
|
+
return path.join(this.tasksDir, safe);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
registerAgent({
|
|
124
|
+
agentId,
|
|
125
|
+
aliases = [],
|
|
126
|
+
engine = "custom",
|
|
127
|
+
role = "",
|
|
128
|
+
workspace = "",
|
|
129
|
+
deliveryMode = "inbox",
|
|
130
|
+
targetId = "",
|
|
131
|
+
status = "idle",
|
|
132
|
+
ttlSeconds,
|
|
133
|
+
implicit = false,
|
|
134
|
+
}) {
|
|
135
|
+
const cleanId = normalizeId(agentId);
|
|
136
|
+
if (!cleanId) {
|
|
137
|
+
throw new Error("agent_id is required.");
|
|
138
|
+
}
|
|
139
|
+
const agents = this._loadRegistry();
|
|
140
|
+
const existing = this._findExistingRecord(agents, cleanId);
|
|
141
|
+
const canonicalId = existing ? existing.agentId : cleanId;
|
|
142
|
+
const nowIso = new Date().toISOString();
|
|
143
|
+
const ttlMs =
|
|
144
|
+
ttlSeconds !== undefined && ttlSeconds !== null
|
|
145
|
+
? Math.max(60, Number(ttlSeconds)) * 1000
|
|
146
|
+
: existing?.ttlMs || DEFAULT_AGENT_TTL_MS;
|
|
147
|
+
|
|
148
|
+
const mergedAliases = Array.from(
|
|
149
|
+
new Set(
|
|
150
|
+
[
|
|
151
|
+
...(existing?.aliases || []),
|
|
152
|
+
...(Array.isArray(aliases) ? aliases : []),
|
|
153
|
+
]
|
|
154
|
+
.map((a) => normalizeId(a))
|
|
155
|
+
.filter((a) => a && normalizeKey(a) !== normalizeKey(canonicalId))
|
|
156
|
+
)
|
|
157
|
+
);
|
|
158
|
+
|
|
159
|
+
const record = {
|
|
160
|
+
agentId: canonicalId,
|
|
161
|
+
aliases: mergedAliases,
|
|
162
|
+
engine: implicit && existing ? existing.engine : normalizeId(engine) || existing?.engine || "custom",
|
|
163
|
+
role: implicit && existing ? existing.role : normalizeId(role) || existing?.role || "",
|
|
164
|
+
workspace:
|
|
165
|
+
implicit && existing
|
|
166
|
+
? existing.workspace
|
|
167
|
+
: normalizeId(workspace) || existing?.workspace || "",
|
|
168
|
+
deliveryMode:
|
|
169
|
+
implicit && existing
|
|
170
|
+
? existing.deliveryMode
|
|
171
|
+
: deliveryMode === "push" || deliveryMode === "inbox"
|
|
172
|
+
? deliveryMode
|
|
173
|
+
: existing?.deliveryMode || "inbox",
|
|
174
|
+
targetId:
|
|
175
|
+
implicit && existing
|
|
176
|
+
? existing.targetId
|
|
177
|
+
: normalizeId(targetId) || existing?.targetId || "",
|
|
178
|
+
status: implicit && existing ? existing.status : normalizeId(status) || existing?.status || "idle",
|
|
179
|
+
ttlMs,
|
|
180
|
+
registeredAt: existing?.registeredAt || nowIso,
|
|
181
|
+
lastSeenAt: nowIso,
|
|
182
|
+
expiresAt: new Date(Date.now() + ttlMs).toISOString(),
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
agents[canonicalId] = record;
|
|
186
|
+
this._saveRegistry(agents);
|
|
187
|
+
return record;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
touchAgent(agentId) {
|
|
191
|
+
const cleanId = normalizeId(agentId);
|
|
192
|
+
if (!cleanId) return null;
|
|
193
|
+
return this.registerAgent({
|
|
194
|
+
agentId: cleanId,
|
|
195
|
+
engine: "custom",
|
|
196
|
+
deliveryMode: "inbox",
|
|
197
|
+
implicit: true,
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
_findExistingRecord(agents, idOrAlias) {
|
|
202
|
+
const targetKey = normalizeKey(idOrAlias);
|
|
203
|
+
if (!targetKey) return null;
|
|
204
|
+
for (const rec of Object.values(agents)) {
|
|
205
|
+
if (normalizeKey(rec.agentId) === targetKey) return rec;
|
|
206
|
+
if (rec.targetId && normalizeKey(rec.targetId) === targetKey) return rec;
|
|
207
|
+
if (Array.isArray(rec.aliases) && rec.aliases.some((a) => normalizeKey(a) === targetKey)) {
|
|
208
|
+
return rec;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
return null;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
resolveAgent(idOrAlias) {
|
|
215
|
+
const agents = this._loadRegistry();
|
|
216
|
+
return this._findExistingRecord(agents, idOrAlias);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
setAgentStatus(agentId, status) {
|
|
220
|
+
const agents = this._loadRegistry();
|
|
221
|
+
const rec = this._findExistingRecord(agents, agentId);
|
|
222
|
+
if (!rec) return null;
|
|
223
|
+
rec.status = status;
|
|
224
|
+
rec.lastSeenAt = new Date().toISOString();
|
|
225
|
+
rec.expiresAt = new Date(Date.now() + (rec.ttlMs || DEFAULT_AGENT_TTL_MS)).toISOString();
|
|
226
|
+
agents[rec.agentId] = rec;
|
|
227
|
+
this._saveRegistry(agents);
|
|
228
|
+
return rec;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
listRegistered({ engine } = {}) {
|
|
232
|
+
const agents = this._loadRegistry();
|
|
233
|
+
const mailboxes = this._loadInbox();
|
|
234
|
+
const filterEngine = engine ? normalizeKey(engine) : "";
|
|
235
|
+
return Object.values(agents)
|
|
236
|
+
.filter((rec) => !filterEngine || normalizeKey(rec.engine) === filterEngine)
|
|
237
|
+
.map((rec) => {
|
|
238
|
+
const msgs = mailboxes[rec.agentId] || [];
|
|
239
|
+
const unreadCount = msgs.filter((m) => !m.readAt).length;
|
|
240
|
+
return {
|
|
241
|
+
...rec,
|
|
242
|
+
supportsPush: rec.deliveryMode === "push" && Boolean(rec.targetId || rec.engine === "antigravity"),
|
|
243
|
+
unreadCount,
|
|
244
|
+
};
|
|
245
|
+
})
|
|
246
|
+
.sort((a, b) => Date.parse(b.lastSeenAt) - Date.parse(a.lastSeenAt));
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
createTask({
|
|
250
|
+
engine,
|
|
251
|
+
targetAgent = "",
|
|
252
|
+
fromAgent = "",
|
|
253
|
+
sessionId = "",
|
|
254
|
+
title = "",
|
|
255
|
+
prompt = "",
|
|
256
|
+
cwd = "",
|
|
257
|
+
status = "working",
|
|
258
|
+
statusMessage = "Task created",
|
|
259
|
+
ttlMs = DEFAULT_TASK_TTL_MS,
|
|
260
|
+
pollIntervalMs = DEFAULT_POLL_INTERVAL_MS,
|
|
261
|
+
pid = null,
|
|
262
|
+
remoteStopSupported = true,
|
|
263
|
+
}) {
|
|
264
|
+
const taskId = `tsk_${randomBytes(8).toString("hex")}`;
|
|
265
|
+
const nowIso = new Date().toISOString();
|
|
266
|
+
const task = {
|
|
267
|
+
taskId,
|
|
268
|
+
status: TASK_STATUSES.has(status) ? status : "working",
|
|
269
|
+
statusMessage: sanitizeSensitiveText(statusMessage),
|
|
270
|
+
createdAt: nowIso,
|
|
271
|
+
lastUpdatedAt: nowIso,
|
|
272
|
+
ttlMs: ttlMs === null ? null : Math.max(60_000, Number(ttlMs) || DEFAULT_TASK_TTL_MS),
|
|
273
|
+
...(TERMINAL_TASK_STATUSES.has(status) ? {} : { pollIntervalMs }),
|
|
274
|
+
engine: normalizeId(engine) || "custom",
|
|
275
|
+
targetAgent: normalizeId(targetAgent),
|
|
276
|
+
fromAgent: normalizeId(fromAgent),
|
|
277
|
+
sessionId: normalizeId(sessionId),
|
|
278
|
+
title: normalizeId(title),
|
|
279
|
+
cwd: normalizeId(cwd),
|
|
280
|
+
pid: typeof pid === "number" ? pid : null,
|
|
281
|
+
remoteStopSupported: Boolean(remoteStopSupported),
|
|
282
|
+
};
|
|
283
|
+
|
|
284
|
+
const dir = this._taskDir(taskId);
|
|
285
|
+
mkdirSync(dir, { recursive: true });
|
|
286
|
+
atomicWriteJson(path.join(dir, "meta.json"), task);
|
|
287
|
+
writeFileSync(path.join(dir, "output.log"), "", "utf8");
|
|
288
|
+
|
|
289
|
+
const order = this._loadTasksIndex().filter((id) => id !== taskId);
|
|
290
|
+
order.push(taskId);
|
|
291
|
+
this._saveTasksIndex(order);
|
|
292
|
+
this.pruneExpiredTasks();
|
|
293
|
+
return task;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
getTask(taskId) {
|
|
297
|
+
const dir = this._taskDir(taskId);
|
|
298
|
+
const meta = safeReadJson(path.join(dir, "meta.json"), null);
|
|
299
|
+
if (!meta) return null;
|
|
300
|
+
if (meta.ttlMs !== null && typeof meta.ttlMs === "number") {
|
|
301
|
+
const created = Date.parse(meta.createdAt);
|
|
302
|
+
if (Number.isFinite(created) && created + meta.ttlMs <= Date.now()) {
|
|
303
|
+
return null;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
return meta;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
updateTask(taskId, patch = {}) {
|
|
310
|
+
const current = this.getTask(taskId);
|
|
311
|
+
if (!current) return null;
|
|
312
|
+
if (TERMINAL_TASK_STATUSES.has(current.status)) return current;
|
|
313
|
+
if (patch.status && !TASK_STATUSES.has(patch.status)) throw new Error("Invalid task status.");
|
|
314
|
+
const nextStatus =
|
|
315
|
+
patch.status && TASK_STATUSES.has(patch.status)
|
|
316
|
+
? patch.status
|
|
317
|
+
: current.status;
|
|
318
|
+
|
|
319
|
+
const next = {
|
|
320
|
+
...current,
|
|
321
|
+
...patch,
|
|
322
|
+
taskId: current.taskId,
|
|
323
|
+
createdAt: current.createdAt,
|
|
324
|
+
status: nextStatus,
|
|
325
|
+
lastUpdatedAt: new Date().toISOString(),
|
|
326
|
+
};
|
|
327
|
+
if (patch.statusMessage !== undefined) {
|
|
328
|
+
next.statusMessage = sanitizeSensitiveText(patch.statusMessage);
|
|
329
|
+
}
|
|
330
|
+
if (next.status !== "input_required") delete next.inputRequests;
|
|
331
|
+
if (TERMINAL_TASK_STATUSES.has(next.status)) {
|
|
332
|
+
delete next.pollIntervalMs;
|
|
333
|
+
delete next.inputRequests;
|
|
334
|
+
} else if (!next.pollIntervalMs) {
|
|
335
|
+
next.pollIntervalMs = DEFAULT_POLL_INTERVAL_MS;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
const dir = this._taskDir(taskId);
|
|
339
|
+
atomicWriteJson(path.join(dir, "meta.json"), next);
|
|
340
|
+
return next;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
appendTaskOutput(taskId, chunk) {
|
|
344
|
+
if (!chunk) return;
|
|
345
|
+
const dir = this._taskDir(taskId);
|
|
346
|
+
mkdirSync(dir, { recursive: true });
|
|
347
|
+
appendFileSync(path.join(dir, "output.log"), sanitizeSensitiveText(chunk), "utf8");
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
readTaskOutput(taskId, { cursor = null, maxChars = 4000 } = {}) {
|
|
351
|
+
const logPath = path.join(this._taskDir(taskId), "output.log");
|
|
352
|
+
if (!existsSync(logPath)) {
|
|
353
|
+
return { text: "", totalChars: 0, cursor: 0, nextCursor: null, hasMore: false };
|
|
354
|
+
}
|
|
355
|
+
const full = readFileSync(logPath, "utf8");
|
|
356
|
+
const totalChars = full.length;
|
|
357
|
+
const limit = Math.min(Math.max(Number(maxChars) || 4000, 200), 32000);
|
|
358
|
+
|
|
359
|
+
if (cursor === null || cursor === undefined) {
|
|
360
|
+
const start = Math.max(0, totalChars - limit);
|
|
361
|
+
return {
|
|
362
|
+
text: full.slice(start),
|
|
363
|
+
totalChars,
|
|
364
|
+
cursor: start,
|
|
365
|
+
nextCursor: totalChars,
|
|
366
|
+
hasMore: false,
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
const start = Math.min(Math.max(0, Number(cursor) || 0), totalChars);
|
|
371
|
+
const end = Math.min(totalChars, start + limit);
|
|
372
|
+
return {
|
|
373
|
+
text: full.slice(start, end),
|
|
374
|
+
totalChars,
|
|
375
|
+
cursor: start,
|
|
376
|
+
nextCursor: end,
|
|
377
|
+
hasMore: end < totalChars,
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
listTasks({ limit = 20, status, targetAgent } = {}) {
|
|
382
|
+
const order = this._loadTasksIndex();
|
|
383
|
+
const out = [];
|
|
384
|
+
for (let i = order.length - 1; i >= 0 && out.length < limit; i -= 1) {
|
|
385
|
+
const t = this.getTask(order[i]);
|
|
386
|
+
if (!t) continue;
|
|
387
|
+
if (status && t.status !== status) continue;
|
|
388
|
+
if (targetAgent && normalizeKey(t.targetAgent) !== normalizeKey(targetAgent)) continue;
|
|
389
|
+
out.push(t);
|
|
390
|
+
}
|
|
391
|
+
return out;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
pruneExpiredTasks() {
|
|
395
|
+
const order = this._loadTasksIndex();
|
|
396
|
+
const kept = [];
|
|
397
|
+
const now = Date.now();
|
|
398
|
+
for (const id of order) {
|
|
399
|
+
const dir = this._taskDir(id);
|
|
400
|
+
const meta = safeReadJson(path.join(dir, "meta.json"), null);
|
|
401
|
+
if (!meta) continue;
|
|
402
|
+
const expired =
|
|
403
|
+
meta.ttlMs !== null &&
|
|
404
|
+
typeof meta.ttlMs === "number" &&
|
|
405
|
+
Date.parse(meta.createdAt) + meta.ttlMs <= now;
|
|
406
|
+
if (expired && TERMINAL_TASK_STATUSES.has(meta.status)) {
|
|
407
|
+
rmSync(dir, { recursive: true, force: true });
|
|
408
|
+
} else {
|
|
409
|
+
kept.push(id);
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
if (kept.length !== order.length) {
|
|
413
|
+
this._saveTasksIndex(kept);
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
enqueueMessage({
|
|
418
|
+
toAgent,
|
|
419
|
+
fromAgent = "unknown",
|
|
420
|
+
title = "",
|
|
421
|
+
content = "",
|
|
422
|
+
taskId = "",
|
|
423
|
+
delivery = "inbox",
|
|
424
|
+
}) {
|
|
425
|
+
const cleanTo = normalizeId(toAgent);
|
|
426
|
+
if (!cleanTo) throw new Error("to_agent is required.");
|
|
427
|
+
const reg = this.resolveAgent(cleanTo);
|
|
428
|
+
const bucketKey = reg ? reg.agentId : cleanTo;
|
|
429
|
+
|
|
430
|
+
const mailboxes = this._loadInbox();
|
|
431
|
+
const list = Array.isArray(mailboxes[bucketKey]) ? mailboxes[bucketKey] : [];
|
|
432
|
+
const entry = {
|
|
433
|
+
messageId: `msg_${randomBytes(6).toString("hex")}`,
|
|
434
|
+
toAgent: bucketKey,
|
|
435
|
+
fromAgent: normalizeId(fromAgent) || "unknown",
|
|
436
|
+
title: sanitizeSensitiveText(title).slice(0, 140),
|
|
437
|
+
content: sanitizeSensitiveText(content),
|
|
438
|
+
taskId: normalizeId(taskId),
|
|
439
|
+
delivery,
|
|
440
|
+
createdAt: new Date().toISOString(),
|
|
441
|
+
readAt: null,
|
|
442
|
+
};
|
|
443
|
+
list.push(entry);
|
|
444
|
+
mailboxes[bucketKey] = list.slice(-MAX_INBOX_PER_AGENT);
|
|
445
|
+
this._saveInbox(mailboxes);
|
|
446
|
+
return entry;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
getUnreadSummary(agentId, { limit = 5 } = {}) {
|
|
450
|
+
const cleanId = normalizeId(agentId);
|
|
451
|
+
if (!cleanId) return null;
|
|
452
|
+
const reg = this.resolveAgent(cleanId);
|
|
453
|
+
const bucketKey = reg ? reg.agentId : cleanId;
|
|
454
|
+
const mailboxes = this._loadInbox();
|
|
455
|
+
const list = Array.isArray(mailboxes[bucketKey]) ? mailboxes[bucketKey] : [];
|
|
456
|
+
const unread = list.filter((m) => !m.readAt);
|
|
457
|
+
if (unread.length === 0) return null;
|
|
458
|
+
return {
|
|
459
|
+
agentId: bucketKey,
|
|
460
|
+
unreadCount: unread.length,
|
|
461
|
+
hint: `You have ${unread.length} unread inbox message(s). Call agent_notify with action='inbox' and from_agent='${bucketKey}' to read them.`,
|
|
462
|
+
latest: unread.slice(-limit).map((m) => ({
|
|
463
|
+
messageId: m.messageId,
|
|
464
|
+
fromAgent: m.fromAgent,
|
|
465
|
+
title: m.title,
|
|
466
|
+
taskId: m.taskId || undefined,
|
|
467
|
+
preview: m.content.slice(0, 140),
|
|
468
|
+
createdAt: m.createdAt,
|
|
469
|
+
})),
|
|
470
|
+
};
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
readInbox(agentId, { markRead = true, includeRead = false, limit = 20 } = {}) {
|
|
474
|
+
const cleanId = normalizeId(agentId);
|
|
475
|
+
if (!cleanId) throw new Error("agent_id or from_agent is required to read inbox.");
|
|
476
|
+
const reg = this.resolveAgent(cleanId);
|
|
477
|
+
const bucketKey = reg ? reg.agentId : cleanId;
|
|
478
|
+
const mailboxes = this._loadInbox();
|
|
479
|
+
const list = Array.isArray(mailboxes[bucketKey]) ? mailboxes[bucketKey] : [];
|
|
480
|
+
const selected = (includeRead ? list : list.filter((m) => !m.readAt)).slice(-Math.max(1, limit));
|
|
481
|
+
const nowIso = new Date().toISOString();
|
|
482
|
+
|
|
483
|
+
if (markRead && selected.length > 0) {
|
|
484
|
+
const ids = new Set(selected.map((m) => m.messageId));
|
|
485
|
+
let touched = false;
|
|
486
|
+
for (const m of list) {
|
|
487
|
+
if (ids.has(m.messageId) && !m.readAt) {
|
|
488
|
+
m.readAt = nowIso;
|
|
489
|
+
touched = true;
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
if (touched) {
|
|
493
|
+
mailboxes[bucketKey] = list;
|
|
494
|
+
this._saveInbox(mailboxes);
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
const remainingUnread = list.filter((m) => !m.readAt).length;
|
|
499
|
+
return {
|
|
500
|
+
agentId: bucketKey,
|
|
501
|
+
messages: selected,
|
|
502
|
+
returnedCount: selected.length,
|
|
503
|
+
remainingUnread,
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
getStats() {
|
|
508
|
+
const registry = this._loadRegistry();
|
|
509
|
+
const order = this._loadTasksIndex();
|
|
510
|
+
const logBytes = order.reduce((acc, id) => {
|
|
511
|
+
const p = path.join(this._taskDir(id), "output.log");
|
|
512
|
+
try {
|
|
513
|
+
return acc + (existsSync(p) ? statSync(p).size : 0);
|
|
514
|
+
} catch {
|
|
515
|
+
return acc;
|
|
516
|
+
}
|
|
517
|
+
}, 0);
|
|
518
|
+
return {
|
|
519
|
+
registeredCount: Object.keys(registry).length,
|
|
520
|
+
taskCount: order.length,
|
|
521
|
+
logBytes,
|
|
522
|
+
};
|
|
523
|
+
}
|
|
524
|
+
}
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { parseArgs } from "node:util";
|
|
3
|
+
import { createInterface } from "node:readline";
|
|
4
|
+
import { TUNNEL_PROVIDERS } from "./tunnel.js";
|
|
5
|
+
|
|
6
|
+
const flags = ["resume", "daemon", "foreground", "full-control", "read-only", "help"];
|
|
7
|
+
const strings = ["port", "lang", "root", "tunnel", "cf-token", "cf-hostname", "frp-server", "frp-port", "frp-token", "frp-domain"];
|
|
8
|
+
export const translate = lang => (en, zh) => lang === "zh" ? zh : en;
|
|
9
|
+
export function options(args, env = process.env) {
|
|
10
|
+
const schema = Object.fromEntries(flags.map(key => [key, { type: "boolean" }]));
|
|
11
|
+
schema.help.short = "h";
|
|
12
|
+
schema.version = { type: "boolean", short: "v" };
|
|
13
|
+
for (const key of strings) schema[key] = { type: "string" };
|
|
14
|
+
const { values, positionals } = parseArgs({ args, options: schema, allowPositionals: true });
|
|
15
|
+
const lang = values.lang ?? (/^zh(?:[_@.-]|$)/i.test(env.LC_ALL || env.LANG || "") ? "zh" : "en");
|
|
16
|
+
const t = translate(lang);
|
|
17
|
+
if (!["en", "zh"].includes(lang)) throw Error("--lang zh|en");
|
|
18
|
+
if (values.daemon && values.foreground || values["read-only"] && values["full-control"])
|
|
19
|
+
throw Error(t("Conflicting options", "参数冲突"));
|
|
20
|
+
if (values.tunnel !== undefined && !TUNNEL_PROVIDERS.includes(values.tunnel))
|
|
21
|
+
throw Error(t("Supported tunnels: ", "支持的通道: ") + TUNNEL_PROVIDERS.join("|"));
|
|
22
|
+
const command = positionals.join(" ") || "start";
|
|
23
|
+
if (!["start", "status", "url", "stop", "mesh install", "mesh uninstall", "service install", "service uninstall"].includes(command))
|
|
24
|
+
throw Error(t("Unknown command", "未知命令"));
|
|
25
|
+
const overrides = {};
|
|
26
|
+
if (values.tunnel) overrides.tunnel = values.tunnel;
|
|
27
|
+
if (values["cf-token"]) overrides.cfToken = values["cf-token"];
|
|
28
|
+
if (values["cf-hostname"]) overrides.cfHostname = values["cf-hostname"];
|
|
29
|
+
if (values["frp-server"]) overrides.frpServer = values["frp-server"];
|
|
30
|
+
if (values["frp-port"]) overrides.frpPort = Number(values["frp-port"]);
|
|
31
|
+
if (values["frp-token"]) overrides.frpToken = values["frp-token"];
|
|
32
|
+
if (values["frp-domain"]) overrides.frpDomain = values["frp-domain"];
|
|
33
|
+
if (values.port !== undefined) {
|
|
34
|
+
const port = Number(values.port);
|
|
35
|
+
if (!/^\d+$/.test(values.port) || port < 1 || port > 65535) throw Error("--port 1..65535");
|
|
36
|
+
overrides.port = port;
|
|
37
|
+
}
|
|
38
|
+
if (values.root !== undefined) {
|
|
39
|
+
if (!values.root.trim()) throw Error("--root <path>");
|
|
40
|
+
overrides.root = path.resolve(values.root);
|
|
41
|
+
}
|
|
42
|
+
if (values.daemon || values.foreground) overrides.daemon = !!values.daemon;
|
|
43
|
+
if (values["read-only"] || values["full-control"]) overrides.mode = values["read-only"] ? "read" : "full";
|
|
44
|
+
return { command, lang, overrides, resume: values.resume, help: values.help, version: values.version,
|
|
45
|
+
interactive: !positionals.length && Object.keys(values).every(key => key === "lang") };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function helpText(t) {
|
|
49
|
+
return [
|
|
50
|
+
"LocalMCP CLI",
|
|
51
|
+
t("Usage: localmcp [command] [options]", "用法: localmcp [命令] [参数]"),
|
|
52
|
+
"",
|
|
53
|
+
" start " + t("Start MCP", "启动 MCP"),
|
|
54
|
+
" status | url | stop " + t("Show status, print URL, or stop", "查看状态、输出地址或停止"),
|
|
55
|
+
" mesh install | mesh uninstall",
|
|
56
|
+
" service install | service uninstall",
|
|
57
|
+
"",
|
|
58
|
+
" --root PATH " + t("Working directory", "工作目录"),
|
|
59
|
+
" --read-only | --full-control",
|
|
60
|
+
" --tunnel MODE " + t("auto|local|tunnl_gg|localhost_run|cloudflare_quick|cloudflare_auth|frp_custom", "通道: auto|local|tunnl_gg|localhost_run|cloudflare_quick|cloudflare_auth|frp_custom"),
|
|
61
|
+
" --port N " + t("Listening port", "监听端口"),
|
|
62
|
+
" --daemon | --foreground",
|
|
63
|
+
" --resume " + t("Use saved settings", "使用保存的配置"),
|
|
64
|
+
" --lang zh|en",
|
|
65
|
+
" -h, --help " + t("Show help", "查看帮助"),
|
|
66
|
+
" -v, --version " + t("Show version", "查看版本"),
|
|
67
|
+
].join("\n");
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export async function menu(config, t, input = process.stdin, output = process.stdout) {
|
|
71
|
+
const rl = createInterface({ input, terminal: false });
|
|
72
|
+
const lines = rl[Symbol.asyncIterator]();
|
|
73
|
+
const back = t("Back", "返回上一级");
|
|
74
|
+
const def = t(" (default)", "(默认)");
|
|
75
|
+
const stages = {
|
|
76
|
+
main: ["LocalMCP CLI", [t("Automatic full-control MCP", "自动全权限 MCP") + def, t("Custom MCP", "自定义 MCP")], 1],
|
|
77
|
+
mode: [t("Permissions", "权限"), [t("Read only", "只读"), t("Read and write", "文件读写"), t("Full control", "完全控制") + def], 3],
|
|
78
|
+
root: [t("Directory", "目录"), [t("Entire disk /", "全盘 /") + def, t("Current directory", "当前目录"), t("Specify path", "指定路径")], 1],
|
|
79
|
+
tunnel: [
|
|
80
|
+
t("Tunnel", "通道"),
|
|
81
|
+
[
|
|
82
|
+
t("Smart route", "智能路由") + def,
|
|
83
|
+
t("Local only (no auth)", "仅本机(免鉴权)"),
|
|
84
|
+
"Tunnl.gg",
|
|
85
|
+
"localhost.run",
|
|
86
|
+
t("CF quick tunnel", "CF 临时隧道"),
|
|
87
|
+
t("CF account auth", "CF 账号授权"),
|
|
88
|
+
t("Custom FRP", "自定义 FRP"),
|
|
89
|
+
],
|
|
90
|
+
1,
|
|
91
|
+
],
|
|
92
|
+
run: [t("Run", "运行"), [t("Background", "后台常驻") + def, t("Foreground", "前台运行")], 1],
|
|
93
|
+
};
|
|
94
|
+
const tunnelValues = ["auto", "local", "tunnl_gg", "localhost_run", "cloudflare_quick", "cloudflare_auth", "frp_custom"];
|
|
95
|
+
const disk = path.parse(process.cwd()).root;
|
|
96
|
+
let stage = "main", mode, root, rootChoice, tunnel = "auto";
|
|
97
|
+
const extra = {};
|
|
98
|
+
async function askLine(label) {
|
|
99
|
+
output.write(label);
|
|
100
|
+
const { value, done } = await lines.next();
|
|
101
|
+
if (done) return null;
|
|
102
|
+
return value.trim();
|
|
103
|
+
}
|
|
104
|
+
try {
|
|
105
|
+
while (true) {
|
|
106
|
+
if (stage === "path") {
|
|
107
|
+
const val = await askLine(t("Path: ", "路径: "));
|
|
108
|
+
if (val === null) return null;
|
|
109
|
+
if (val === "0") stage = "root";
|
|
110
|
+
else if (val) {
|
|
111
|
+
root = path.resolve(val);
|
|
112
|
+
stage = "tunnel";
|
|
113
|
+
}
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
if (stage === "cf_auth") {
|
|
117
|
+
const token = await askLine(t("CF Token (0 to back): ", "CF Token(0 返回): "));
|
|
118
|
+
if (token === null) return null;
|
|
119
|
+
if (token === "0") { stage = "tunnel"; continue; }
|
|
120
|
+
const host = await askLine(t("Hostname (0 to back): ", "访问域名(0 返回): "));
|
|
121
|
+
if (host === null) return null;
|
|
122
|
+
if (host === "0") { stage = "tunnel"; continue; }
|
|
123
|
+
if (token && host) { extra.cfToken = token; extra.cfHostname = host; stage = "run"; }
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
if (stage === "frp_cfg") {
|
|
127
|
+
const server = await askLine(t("FRP Server (0 to back): ", "FRP 服务器(0 返回): "));
|
|
128
|
+
if (server === null) return null;
|
|
129
|
+
if (server === "0") { stage = "tunnel"; continue; }
|
|
130
|
+
const portVal = await askLine(t("FRP Port [7000] (0 to back): ", "FRP 端口 [7000](0 返回): "));
|
|
131
|
+
if (portVal === null) return null;
|
|
132
|
+
if (portVal === "0") { stage = "tunnel"; continue; }
|
|
133
|
+
const token = await askLine(t("FRP Token (0 to back): ", "FRP Token(0 返回): "));
|
|
134
|
+
if (token === null) return null;
|
|
135
|
+
if (token === "0") { stage = "tunnel"; continue; }
|
|
136
|
+
const domain = await askLine(t("Custom Domain (0 to back): ", "访问域名(0 返回): "));
|
|
137
|
+
if (domain === null) return null;
|
|
138
|
+
if (domain === "0") { stage = "tunnel"; continue; }
|
|
139
|
+
if (server && domain) {
|
|
140
|
+
extra.frpServer = server;
|
|
141
|
+
extra.frpPort = Number(portVal || 7000);
|
|
142
|
+
extra.frpToken = token;
|
|
143
|
+
extra.frpDomain = domain;
|
|
144
|
+
stage = "run";
|
|
145
|
+
}
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
const [heading, items, fallback] = stages[stage];
|
|
149
|
+
output.write(heading + "\n" + items.map((item, i) => " " + (i + 1) + ". " + item).join("\n") +
|
|
150
|
+
"\n 0. " + (stage === "main" ? t("Exit", "退出") : back) + "\n" + t("Choose", "选择") + " [" + fallback + "]: ");
|
|
151
|
+
const { value, done } = await lines.next();
|
|
152
|
+
if (done) return null;
|
|
153
|
+
const answer = value.trim() || String(fallback);
|
|
154
|
+
if (!/^\d$/.test(answer) || Number(answer) > items.length) continue;
|
|
155
|
+
const n = Number(answer);
|
|
156
|
+
if (n === 0) {
|
|
157
|
+
if (stage === "main") return null;
|
|
158
|
+
stage = { mode: "main", root: "mode", tunnel: rootChoice === 3 ? "path" : "root", run: "tunnel" }[stage];
|
|
159
|
+
} else if (stage === "main") {
|
|
160
|
+
if (n === 1) return { ...config, mode: "full", root: disk, daemon: true, tunnel: "auto" };
|
|
161
|
+
stage = "mode";
|
|
162
|
+
} else if (stage === "mode") {
|
|
163
|
+
mode = ["read", "write", "full"][n - 1];
|
|
164
|
+
stage = "root";
|
|
165
|
+
} else if (stage === "root") {
|
|
166
|
+
rootChoice = n;
|
|
167
|
+
root = n === 1 ? disk : process.cwd();
|
|
168
|
+
stage = n === 3 ? "path" : "tunnel";
|
|
169
|
+
} else if (stage === "tunnel") {
|
|
170
|
+
tunnel = tunnelValues[n - 1];
|
|
171
|
+
if (tunnel === "cloudflare_auth") stage = "cf_auth";
|
|
172
|
+
else if (tunnel === "frp_custom") stage = "frp_cfg";
|
|
173
|
+
else stage = "run";
|
|
174
|
+
} else return { ...config, ...extra, mode, root, daemon: n === 1, tunnel };
|
|
175
|
+
}
|
|
176
|
+
} finally { rl.close(); }
|
|
177
|
+
}
|