@agentmesh-md/mcp-server 0.2.2 → 0.3.4
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/README.md +143 -4
- package/dist/client.js +16 -5
- package/dist/codex-hooks.js +142 -0
- package/dist/connect.js +75 -205
- package/dist/context.js +7 -0
- package/dist/contract.js +5 -1
- package/dist/errors.js +0 -55
- package/dist/index.js +41 -8
- package/dist/legacy.js +2 -66
- package/dist/oauth-client.js +131 -26
- package/dist/plugin-install.js +154 -0
- package/dist/plugin-monitor.js +292 -0
- package/dist/plugin-permissions.js +212 -0
- package/dist/plugin-proxy.js +75 -0
- package/dist/plugin-session.js +381 -0
- package/dist/plugin-storage.js +94 -0
- package/dist/plugin-target.js +16 -0
- package/dist/schemas.js +8 -2
- package/dist/server.js +30 -5
- package/dist/session.js +118 -14
- package/dist/terminal-diagnostic.js +1 -1
- package/dist/terminal-runtime.js +96 -161
- package/dist/tool-annotations.js +57 -0
- package/dist/tools.js +36 -55
- package/dist/wake-storage.js +33 -49
- package/package.json +5 -4
- package/plugin-marketplace/.claude-plugin/marketplace.json +11 -0
- package/plugin-marketplace/plugins/agentmesh/.claude-plugin/plugin.json +23 -0
- package/plugin-marketplace/plugins/agentmesh/README.md +36 -0
- package/plugin-marketplace/plugins/agentmesh/hooks/codex.json +44 -0
- package/plugin-marketplace/plugins/agentmesh/hooks/hooks.json +44 -0
- package/plugin-marketplace/plugins/agentmesh/mcp.json +15 -0
- package/plugin-marketplace/plugins/agentmesh/monitors/monitors.json +7 -0
- package/plugin-marketplace/plugins/agentmesh/plugin.json +6 -0
- package/plugin-marketplace/plugins/agentmesh/release.json +1 -0
- package/plugin-marketplace/plugins/agentmesh/server/lib/agent-operating-contract.txt +120 -0
- package/plugin-marketplace/plugins/agentmesh/server/lib/agentmesh-mcp.js +39419 -0
- package/plugin-marketplace/plugins/agentmesh/server/package.json +4 -0
- package/plugin-marketplace/plugins/agentmesh/server/schemas/defs.json +121 -0
- package/plugin-marketplace/plugins/agentmesh/server/schemas/tools.json +1933 -0
- package/schemas/tools.json +592 -3
- package/dist/connect-bridge.js +0 -62
- package/dist/mentions.cjs +0 -22
- package/dist/wake-monitor.js +0 -117
- package/dist/wake.js +0 -521
package/dist/oauth-client.js
CHANGED
|
@@ -4,8 +4,9 @@ import path from 'node:path';
|
|
|
4
4
|
import { randomBytes } from 'node:crypto';
|
|
5
5
|
import { spawn } from 'node:child_process';
|
|
6
6
|
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
7
|
-
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
|
|
7
|
+
import { StreamableHTTPClientTransport, StreamableHTTPError } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
|
|
8
8
|
import { UnauthorizedError } from '@modelcontextprotocol/sdk/client/auth.js';
|
|
9
|
+
import { resourceTarget } from './plugin-target.js';
|
|
9
10
|
import { readJson, writeAtomic } from './wake-storage.js';
|
|
10
11
|
export const RESOURCE = 'https://agentmesh.md/mcp';
|
|
11
12
|
export function ownerDirectory(dir) {
|
|
@@ -15,14 +16,15 @@ export function ownerDirectory(dir) {
|
|
|
15
16
|
throw new Error('OwnerDirectoryRequired');
|
|
16
17
|
fs.chmodSync(dir, 0o700);
|
|
17
18
|
}
|
|
18
|
-
export function credentialFile(file) {
|
|
19
|
+
export function credentialFile(file, resource = RESOURCE) {
|
|
20
|
+
resourceTarget(resource);
|
|
19
21
|
if (!fs.existsSync(file))
|
|
20
22
|
return undefined;
|
|
21
23
|
const stat = fs.lstatSync(file);
|
|
22
24
|
if (!stat.isFile() || stat.isSymbolicLink() || stat.uid !== process.getuid?.() || (stat.mode & 0o077) !== 0)
|
|
23
25
|
throw new Error('OwnerCredentialsRequired');
|
|
24
26
|
const saved = readJson(file);
|
|
25
|
-
if (saved.resource !==
|
|
27
|
+
if (saved.resource !== resource)
|
|
26
28
|
throw new Error('ResourceMismatch');
|
|
27
29
|
return saved;
|
|
28
30
|
}
|
|
@@ -31,6 +33,8 @@ export function credentialFile(file) {
|
|
|
31
33
|
class Provider {
|
|
32
34
|
file;
|
|
33
35
|
requestedAgentId;
|
|
36
|
+
interactive;
|
|
37
|
+
resource;
|
|
34
38
|
verifier = '';
|
|
35
39
|
secrets = new Set();
|
|
36
40
|
redact(value) {
|
|
@@ -48,11 +52,14 @@ class Provider {
|
|
|
48
52
|
saved;
|
|
49
53
|
redirectUrl;
|
|
50
54
|
authorizationStarted = false;
|
|
51
|
-
constructor(file, redirect, requestedAgentId) {
|
|
55
|
+
constructor(file, redirect, requestedAgentId, interactive = true, resource = RESOURCE) {
|
|
52
56
|
this.file = file;
|
|
53
57
|
this.requestedAgentId = requestedAgentId;
|
|
54
|
-
this.
|
|
55
|
-
this.
|
|
58
|
+
this.interactive = interactive;
|
|
59
|
+
this.resource = resource;
|
|
60
|
+
this.saved = credentialFile(file, resource) ?? { resource, redirect };
|
|
61
|
+
this.redirectUrl = redirect;
|
|
62
|
+
this.saved.redirect = redirect;
|
|
56
63
|
this.remember(this.saved.tokens);
|
|
57
64
|
}
|
|
58
65
|
get clientMetadata() {
|
|
@@ -69,12 +76,14 @@ class Provider {
|
|
|
69
76
|
saveCodeVerifier(value) { this.verifier = value; }
|
|
70
77
|
codeVerifier() { return this.verifier; }
|
|
71
78
|
async validateResourceURL(server, resource) {
|
|
72
|
-
if (String(server) !==
|
|
79
|
+
if (String(server) !== this.resource || (resource !== undefined && resource !== this.resource))
|
|
73
80
|
throw new Error('ResourceMismatch');
|
|
74
|
-
return new URL(
|
|
81
|
+
return new URL(this.resource);
|
|
75
82
|
}
|
|
76
83
|
async redirectToAuthorization(url) {
|
|
77
|
-
if (
|
|
84
|
+
if (!this.interactive)
|
|
85
|
+
throw new Error('ReconnectRequired');
|
|
86
|
+
if (url.origin !== new URL(this.resource).origin || url.pathname !== '/authorize')
|
|
78
87
|
throw new Error('AuthorizationOriginMismatch');
|
|
79
88
|
if (this.requestedAgentId)
|
|
80
89
|
url.searchParams.set('requested_agent_id', this.requestedAgentId);
|
|
@@ -97,32 +106,48 @@ class Provider {
|
|
|
97
106
|
}
|
|
98
107
|
save() { writeAtomic(this.file, this.saved); fs.chmodSync(this.file, 0o600); }
|
|
99
108
|
}
|
|
100
|
-
// OAuth discovery/token requests stay on the
|
|
109
|
+
// OAuth discovery/token requests stay on the selected exact allowlisted origin;
|
|
101
110
|
// response redirects cannot exfiltrate Authorization or form credentials.
|
|
102
|
-
const safeFetch = async (input, init) => {
|
|
111
|
+
const safeFetch = (resource, timeout = 15_000) => async (input, init) => {
|
|
103
112
|
const url = new URL(input instanceof Request ? input.url : String(input));
|
|
104
|
-
if (url.origin !==
|
|
113
|
+
if (url.origin !== resourceTarget(resource).origin)
|
|
105
114
|
throw new Error('OAuthOriginMismatch');
|
|
106
|
-
return fetch(input, { ...init, redirect: 'error', signal: init?.signal ? AbortSignal.any([init.signal, AbortSignal.timeout(
|
|
115
|
+
return fetch(input, { ...init, redirect: 'error', signal: init?.signal ? AbortSignal.any([init.signal, AbortSignal.timeout(timeout)]) : AbortSignal.timeout(timeout) });
|
|
107
116
|
};
|
|
108
|
-
export async function openOAuth(profile, requestedAgentId) {
|
|
117
|
+
export async function openOAuth(profile, requestedAgentId, resource = RESOURCE) {
|
|
109
118
|
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
110
119
|
if (requestedAgentId !== undefined && !uuid.test(requestedAgentId))
|
|
111
120
|
throw new Error('IdentityArgument');
|
|
112
121
|
ownerDirectory(profile);
|
|
113
122
|
const file = path.join(profile, 'credentials.json');
|
|
114
|
-
const saved = credentialFile(file);
|
|
123
|
+
const saved = credentialFile(file, resource);
|
|
124
|
+
// Try cached/refresh authorization without reserving any callback socket.
|
|
125
|
+
if (saved?.tokens && saved.client) {
|
|
126
|
+
const cached = new Provider(file, saved.redirect, requestedAgentId, false, resource);
|
|
127
|
+
const client = new Client({ name: 'agentmesh-terminal', version: '0.3.4' });
|
|
128
|
+
try {
|
|
129
|
+
// Connect already owns the profile OAuth lock. Reuse it rather than
|
|
130
|
+
// recursively acquiring the refresh lock through openSavedOAuth.
|
|
131
|
+
await client.connect(new StreamableHTTPClientTransport(new URL(resource), { authProvider: cached, fetch: safeFetch(resource) }));
|
|
132
|
+
return { client, redact: (value) => cached.redact(value), complete: () => undefined, close: () => client.close() };
|
|
133
|
+
}
|
|
134
|
+
catch (error) {
|
|
135
|
+
await client.close().catch(() => undefined);
|
|
136
|
+
if (!(error instanceof UnauthorizedError) && !(error instanceof StreamableHTTPError && (error.code === 401 || error.code === 403)) && !(error instanceof Error && error.message === 'ReconnectRequired'))
|
|
137
|
+
throw error;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
115
140
|
const server = http.createServer();
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
await new Promise((resolve, reject) => { server.once('error', reject); server.listen(
|
|
141
|
+
if (saved) {
|
|
142
|
+
const u = new URL(saved.redirect);
|
|
143
|
+
if (u.hostname !== '127.0.0.1' || u.protocol !== 'http:' || u.pathname !== '/callback')
|
|
144
|
+
throw new Error('CallbackMismatch');
|
|
145
|
+
}
|
|
146
|
+
await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });
|
|
122
147
|
const address = server.address();
|
|
123
148
|
if (!address || typeof address === 'string')
|
|
124
149
|
throw new Error('CallbackUnavailable');
|
|
125
|
-
const provider = new Provider(file, `http://127.0.0.1:${address.port}/callback`, requestedAgentId);
|
|
150
|
+
const provider = new Provider(file, `http://127.0.0.1:${address.port}/callback`, requestedAgentId, true, resource);
|
|
126
151
|
let timer;
|
|
127
152
|
let callback;
|
|
128
153
|
let accepted = false, finished = false;
|
|
@@ -141,7 +166,7 @@ export async function openOAuth(profile, requestedAgentId) {
|
|
|
141
166
|
console.error({ error_class: 'Error', cause: 'ApprovalTimeout', location: 'mcp/src/oauth-client.ts:openOAuth:approvalTimeout' });
|
|
142
167
|
fail();
|
|
143
168
|
reject(new Error('ApprovalTimeout'));
|
|
144
|
-
},
|
|
169
|
+
}, 360_000); // Five-minute server request plus setup budget.
|
|
145
170
|
server.on('request', (req, res) => {
|
|
146
171
|
res.setHeader('Cache-Control', 'no-store');
|
|
147
172
|
res.setHeader('Referrer-Policy', 'no-referrer');
|
|
@@ -177,7 +202,7 @@ export async function openOAuth(profile, requestedAgentId) {
|
|
|
177
202
|
console.error({ error_class: 'Error', cause: 'ApprovalUnavailable', location: 'mcp/src/oauth-client.ts:openOAuth:complete' });
|
|
178
203
|
throw new Error('ApprovalUnavailable');
|
|
179
204
|
}
|
|
180
|
-
const target = new URL('
|
|
205
|
+
const target = new URL(resourceTarget(resource).origin + '/');
|
|
181
206
|
target.hash = `/connection-complete?workspace=${workspaceId}&agent=${agentId}`;
|
|
182
207
|
callback.writeHead(303, { Location: target.href });
|
|
183
208
|
callback.end();
|
|
@@ -187,9 +212,12 @@ export async function openOAuth(profile, requestedAgentId) {
|
|
|
187
212
|
// A cached-token success never awaits the callback; prevent an unhandled
|
|
188
213
|
// rejection while its timer is being cancelled in finally.
|
|
189
214
|
void code.catch(() => undefined);
|
|
190
|
-
const transport = new StreamableHTTPClientTransport(new URL(
|
|
215
|
+
const transport = new StreamableHTTPClientTransport(new URL(resource), { authProvider: provider, fetch: safeFetch(resource) });
|
|
191
216
|
let client = new Client({ name: 'agentmesh-terminal', version: '0.2.2' });
|
|
192
217
|
try {
|
|
218
|
+
// A new callback port needs its own registration. Valid cached grants have
|
|
219
|
+
// already returned above; only the interactive provider is reset here.
|
|
220
|
+
provider.invalidateCredentials('all');
|
|
193
221
|
try {
|
|
194
222
|
await client.connect(transport);
|
|
195
223
|
}
|
|
@@ -199,7 +227,7 @@ export async function openOAuth(profile, requestedAgentId) {
|
|
|
199
227
|
await transport.finishAuth(await code);
|
|
200
228
|
await client.close();
|
|
201
229
|
client = new Client({ name: 'agentmesh-terminal', version: '0.2.2' });
|
|
202
|
-
await client.connect(new StreamableHTTPClientTransport(new URL(
|
|
230
|
+
await client.connect(new StreamableHTTPClientTransport(new URL(resource), { authProvider: provider, fetch: safeFetch(resource) }));
|
|
203
231
|
}
|
|
204
232
|
if (!accepted)
|
|
205
233
|
cleanup();
|
|
@@ -213,3 +241,80 @@ export async function openOAuth(profile, requestedAgentId) {
|
|
|
213
241
|
throw error;
|
|
214
242
|
}
|
|
215
243
|
}
|
|
244
|
+
// A request owns the profile lock from reload through refresh and completion.
|
|
245
|
+
// No stale provider survives another process rotating the refresh token.
|
|
246
|
+
export async function savedOAuth(profile, operation, resource = RESOURCE) {
|
|
247
|
+
const { locked } = await import('./plugin-storage.js');
|
|
248
|
+
return locked(profile, 'oauth', async () => {
|
|
249
|
+
const file = path.join(profile, 'credentials.json'), saved = credentialFile(file, resource);
|
|
250
|
+
if (!saved?.tokens || !saved.client)
|
|
251
|
+
throw new Error('ReconnectRequired');
|
|
252
|
+
const provider = new Provider(file, saved.redirect, undefined, false, resource);
|
|
253
|
+
const client = new Client({ name: 'agentmesh-session', version: '0.3.4' });
|
|
254
|
+
try {
|
|
255
|
+
await client.connect(new StreamableHTTPClientTransport(new URL(resource), { authProvider: provider, fetch: safeFetch(resource) }));
|
|
256
|
+
return provider.redact(await operation(client));
|
|
257
|
+
}
|
|
258
|
+
catch (error) {
|
|
259
|
+
if (error instanceof UnauthorizedError || error instanceof StreamableHTTPError && (error.code === 401 || error.code === 403))
|
|
260
|
+
throw new Error('ReconnectRequired');
|
|
261
|
+
throw error;
|
|
262
|
+
}
|
|
263
|
+
finally {
|
|
264
|
+
await client.close().catch(() => undefined);
|
|
265
|
+
}
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
/** Listener-owned connection. Only the existing locked provider rotates tokens;
|
|
269
|
+
* no credential lock is held during a server wait or ordinary healthy request. */
|
|
270
|
+
export async function openSavedOAuth(profile, resource = RESOURCE) {
|
|
271
|
+
const file = path.join(profile, 'credentials.json'), lifetime = new AbortController(), secrets = new Set();
|
|
272
|
+
const redact = (value) => { let text = JSON.stringify(value); for (const secret of secrets)
|
|
273
|
+
text = text.split(secret).join('[redacted]'); return JSON.parse(text); };
|
|
274
|
+
const snapshot = () => {
|
|
275
|
+
const saved = credentialFile(file, resource);
|
|
276
|
+
if (!saved?.tokens?.access_token || !saved.client)
|
|
277
|
+
throw new Error('ReconnectRequired');
|
|
278
|
+
for (const token of [saved.tokens.access_token, saved.tokens.refresh_token])
|
|
279
|
+
if (token)
|
|
280
|
+
secrets.add(token);
|
|
281
|
+
return saved.tokens.access_token;
|
|
282
|
+
};
|
|
283
|
+
const transportFetch = async (input, init) => {
|
|
284
|
+
let held = false;
|
|
285
|
+
if (typeof init?.body === 'string')
|
|
286
|
+
try {
|
|
287
|
+
const rpc = JSON.parse(init.body);
|
|
288
|
+
held = rpc.method === 'tools/call' && rpc.params?.name === 'terminal_wake_poll' && Number.isInteger(rpc.params.arguments?.wait_seconds) && rpc.params.arguments.wait_seconds > 0 && rpc.params.arguments.wait_seconds <= 25;
|
|
289
|
+
}
|
|
290
|
+
catch { /* ordinary deadline */ }
|
|
291
|
+
const signal = AbortSignal.any([lifetime.signal, ...init?.signal ? [init.signal] : [], AbortSignal.timeout(held ? 35_000 : 15_000)]);
|
|
292
|
+
const request = () => { const headers = new Headers(init?.headers); headers.set('Authorization', 'Bearer ' + snapshot()); return safeFetch(resource, held ? 35_000 : 15_000)(input, { ...init, headers, signal }); };
|
|
293
|
+
let response = await request();
|
|
294
|
+
if (response.status === 401) {
|
|
295
|
+
await response.body?.cancel();
|
|
296
|
+
signal.throwIfAborted();
|
|
297
|
+
// Reload under the same cross-process lock as proxy calls. Another caller
|
|
298
|
+
// may already have refreshed; connecting with its fresh token does no write.
|
|
299
|
+
await savedOAuth(profile, async () => null, resource);
|
|
300
|
+
signal.throwIfAborted();
|
|
301
|
+
response = await request();
|
|
302
|
+
}
|
|
303
|
+
if (response.status === 401 || response.status === 403) {
|
|
304
|
+
await response.body?.cancel();
|
|
305
|
+
throw new Error('ReconnectRequired');
|
|
306
|
+
}
|
|
307
|
+
return response;
|
|
308
|
+
};
|
|
309
|
+
const client = new Client({ name: 'agentmesh-session-listener', version: '0.3.4' });
|
|
310
|
+
const close = async () => { lifetime.abort(); await client.close().catch(() => undefined); };
|
|
311
|
+
try {
|
|
312
|
+
snapshot();
|
|
313
|
+
await client.connect(new StreamableHTTPClientTransport(new URL(resource), { fetch: transportFetch }));
|
|
314
|
+
return { client, redact, close };
|
|
315
|
+
}
|
|
316
|
+
catch (error) {
|
|
317
|
+
await close();
|
|
318
|
+
throw error;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { spawn } from 'node:child_process';
|
|
6
|
+
import { randomUUID, createHash } from 'node:crypto';
|
|
7
|
+
import { privateRoot, locked } from './plugin-storage.js';
|
|
8
|
+
import { ownerDirectory } from './oauth-client.js';
|
|
9
|
+
import { connectionTarget } from './plugin-target.js';
|
|
10
|
+
import { terminalDiagnostic } from './terminal-diagnostic.js';
|
|
11
|
+
import { installCodexHooks } from './codex-hooks.js';
|
|
12
|
+
async function command(executable, args, capture = false) {
|
|
13
|
+
const child = spawn(executable, args, { stdio: ['ignore', capture ? 'pipe' : 'ignore', 'ignore'] });
|
|
14
|
+
try {
|
|
15
|
+
return await new Promise((resolve, reject) => {
|
|
16
|
+
let output = '';
|
|
17
|
+
const timer = setTimeout(() => { child.kill(); reject(new Error('PluginInstallTimeout')); }, 60000);
|
|
18
|
+
child.stdout?.on('data', (chunk) => { output += chunk.toString('utf8'); if (Buffer.byteLength(output) > 262144) {
|
|
19
|
+
child.kill();
|
|
20
|
+
reject(new Error('PluginInstallReadbackTooLarge'));
|
|
21
|
+
} });
|
|
22
|
+
child.once('error', () => { clearTimeout(timer); reject(new Error('PluginInstallerUnavailable')); });
|
|
23
|
+
child.once('close', code => { clearTimeout(timer); code === 0 ? resolve(output) : reject(new Error('PluginInstallFailedConnectionSaved')); });
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
catch (error) {
|
|
27
|
+
process.stderr.write(`AgentMesh ${terminalDiagnostic(error, 'plugin-install.js', 'command')}.\n`);
|
|
28
|
+
throw error;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
// Both native clients consume the one generated marketplace shipped in npm.
|
|
32
|
+
function packagedMarketplace(root) {
|
|
33
|
+
const source = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../plugin-marketplace');
|
|
34
|
+
if (!fs.existsSync(path.join(source, '.claude-plugin', 'marketplace.json')))
|
|
35
|
+
throw new Error('PackagedMarketplaceMissing');
|
|
36
|
+
const hash = createHash('sha256');
|
|
37
|
+
const digest = (dir) => { for (const name of fs.readdirSync(dir).sort()) {
|
|
38
|
+
const full = path.join(dir, name), stat = fs.lstatSync(full);
|
|
39
|
+
if (stat.isSymbolicLink())
|
|
40
|
+
throw new Error('PluginSymlinkRejected');
|
|
41
|
+
hash.update(path.relative(source, full));
|
|
42
|
+
if (stat.isDirectory())
|
|
43
|
+
digest(full);
|
|
44
|
+
else if (stat.isFile())
|
|
45
|
+
hash.update(fs.readFileSync(full));
|
|
46
|
+
else
|
|
47
|
+
throw new Error('PluginFileRequired');
|
|
48
|
+
} };
|
|
49
|
+
digest(source);
|
|
50
|
+
const release = path.join(root, 'release-' + hash.digest('hex'));
|
|
51
|
+
if (!fs.existsSync(release)) {
|
|
52
|
+
const temp = release + '.' + randomUUID();
|
|
53
|
+
try {
|
|
54
|
+
fs.cpSync(source, temp, { recursive: true, dereference: false });
|
|
55
|
+
const secure = (dir) => { ownerDirectory(dir); for (const file of fs.readdirSync(dir)) {
|
|
56
|
+
const full = path.join(dir, file), stat = fs.lstatSync(full);
|
|
57
|
+
if (stat.isSymbolicLink())
|
|
58
|
+
throw new Error('PluginSymlinkRejected');
|
|
59
|
+
if (stat.isDirectory())
|
|
60
|
+
secure(full);
|
|
61
|
+
else if (stat.isFile())
|
|
62
|
+
fs.chmodSync(full, 0o600);
|
|
63
|
+
else
|
|
64
|
+
throw new Error('PluginFileRequired');
|
|
65
|
+
} };
|
|
66
|
+
secure(temp);
|
|
67
|
+
fs.renameSync(temp, release);
|
|
68
|
+
}
|
|
69
|
+
finally {
|
|
70
|
+
fs.rmSync(temp, { recursive: true, force: true });
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
else
|
|
74
|
+
ownerDirectory(release);
|
|
75
|
+
return release;
|
|
76
|
+
}
|
|
77
|
+
function jsonArray(output) {
|
|
78
|
+
let entries;
|
|
79
|
+
try {
|
|
80
|
+
entries = JSON.parse(output);
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
throw new Error('PluginInstallReadbackInvalid');
|
|
84
|
+
}
|
|
85
|
+
if (!Array.isArray(entries) || entries.some(e => !e || typeof e !== 'object' || Array.isArray(e)))
|
|
86
|
+
throw new Error('PluginInstallReadbackInvalid');
|
|
87
|
+
return entries;
|
|
88
|
+
}
|
|
89
|
+
function settings(file) {
|
|
90
|
+
if (!fs.existsSync(file))
|
|
91
|
+
return {};
|
|
92
|
+
try {
|
|
93
|
+
const value = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
94
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
95
|
+
throw new Error();
|
|
96
|
+
return value;
|
|
97
|
+
}
|
|
98
|
+
catch {
|
|
99
|
+
throw new Error('PluginInstallReadbackInvalid');
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
export async function installPlugin(client, executable, _target = connectionTarget()) {
|
|
103
|
+
if (!path.isAbsolute(executable))
|
|
104
|
+
throw new Error('InstallerAbsolutePathRequired');
|
|
105
|
+
const root = privateRoot();
|
|
106
|
+
try {
|
|
107
|
+
await locked(root, 'install', async () => {
|
|
108
|
+
// Prepare all shipped bytes before changing native installation state.
|
|
109
|
+
const release = packagedMarketplace(root);
|
|
110
|
+
if (client === 'claude') {
|
|
111
|
+
const entries = jsonArray(await command(executable, ['plugin', 'list', '--json'], true));
|
|
112
|
+
const catalogs = jsonArray(await command(executable, ['plugin', 'marketplace', 'list', '--json'], true));
|
|
113
|
+
const userFile = path.join(process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude'), 'settings.json');
|
|
114
|
+
const user = settings(userFile), userReal = fs.existsSync(userFile) ? fs.realpathSync(userFile) : userFile;
|
|
115
|
+
const userCatalog = Object.hasOwn(user.extraKnownMarketplaces ?? {}, 'agentmesh');
|
|
116
|
+
// Removal must never uninstall another consumer or remove another scope.
|
|
117
|
+
if (entries.some(e => typeof e.id === 'string' && e.id.endsWith('@agentmesh') && (e.id !== 'agentmesh@agentmesh' || e.scope !== 'user')))
|
|
118
|
+
throw new Error('PluginInstallScopeConflict');
|
|
119
|
+
if (catalogs.some(e => e.name === 'agentmesh') && !userCatalog)
|
|
120
|
+
throw new Error('PluginInstallScopeConflict');
|
|
121
|
+
for (let dir = process.cwd();; dir = path.dirname(dir)) {
|
|
122
|
+
for (const name of ['settings.json', 'settings.local.json']) {
|
|
123
|
+
const file = path.join(dir, '.claude', name);
|
|
124
|
+
if (fs.existsSync(file) && fs.realpathSync(file) === userReal)
|
|
125
|
+
continue;
|
|
126
|
+
const project = settings(file);
|
|
127
|
+
if (Object.hasOwn(project.extraKnownMarketplaces ?? {}, 'agentmesh') || Object.hasOwn(project.enabledPlugins ?? {}, 'agentmesh@agentmesh'))
|
|
128
|
+
throw new Error('PluginInstallScopeConflict');
|
|
129
|
+
}
|
|
130
|
+
if (path.dirname(dir) === dir)
|
|
131
|
+
break;
|
|
132
|
+
}
|
|
133
|
+
if (entries.some(e => e.id === 'agentmesh@agentmesh' && e.scope === 'user'))
|
|
134
|
+
await command(executable, ['plugin', 'uninstall', 'agentmesh@agentmesh', '--scope', 'user', '--keep-data']);
|
|
135
|
+
if (userCatalog)
|
|
136
|
+
await command(executable, ['plugin', 'marketplace', 'remove', 'agentmesh', '--scope', 'user']);
|
|
137
|
+
await command(executable, ['plugin', 'marketplace', 'add', release, '--scope', 'user']);
|
|
138
|
+
await command(executable, ['plugin', 'install', 'agentmesh@agentmesh', '--scope', 'user']);
|
|
139
|
+
const installed = jsonArray(await command(executable, ['plugin', 'list', '--json'], true)).filter(e => e.id === 'agentmesh@agentmesh' && e.scope === 'user');
|
|
140
|
+
if (installed.length !== 1 || installed[0].enabled !== true)
|
|
141
|
+
throw new Error('PluginInstallNotEnabled');
|
|
142
|
+
}
|
|
143
|
+
else {
|
|
144
|
+
await command(executable, ['plugin', 'marketplace', 'add', release]);
|
|
145
|
+
await command(executable, ['plugin', 'add', 'agentmesh@agentmesh']);
|
|
146
|
+
await installCodexHooks(path.join(release, 'plugins/agentmesh/server/lib/agentmesh-mcp.js'));
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
catch (error) {
|
|
151
|
+
process.stderr.write(`AgentMesh ${terminalDiagnostic(error, 'plugin-install.js', 'installPlugin')}.\n`);
|
|
152
|
+
throw error;
|
|
153
|
+
}
|
|
154
|
+
}
|