@agentmesh-md/mcp-server 0.2.1 → 0.3.3
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 +130 -3
- package/dist/client.js +16 -5
- package/dist/codex-hooks.js +142 -0
- package/dist/connect.js +77 -202
- package/dist/context.js +7 -0
- package/dist/contract.js +5 -1
- package/dist/errors.js +0 -55
- package/dist/index.js +33 -7
- package/dist/legacy.js +2 -66
- package/dist/oauth-client.js +188 -36
- package/dist/plugin-install.js +97 -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 +31 -5
- package/dist/session.js +118 -14
- package/dist/terminal-diagnostic.js +1 -1
- package/dist/terminal-runtime.js +149 -151
- 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 +31 -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 +39413 -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 +1934 -0
- package/schemas/tools.json +591 -1
- 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
|
}
|
|
@@ -30,6 +32,9 @@ export function credentialFile(file) {
|
|
|
30
32
|
// children never receive credentials, including during refresh rotation.
|
|
31
33
|
class Provider {
|
|
32
34
|
file;
|
|
35
|
+
requestedAgentId;
|
|
36
|
+
interactive;
|
|
37
|
+
resource;
|
|
33
38
|
verifier = '';
|
|
34
39
|
secrets = new Set();
|
|
35
40
|
redact(value) {
|
|
@@ -47,10 +52,14 @@ class Provider {
|
|
|
47
52
|
saved;
|
|
48
53
|
redirectUrl;
|
|
49
54
|
authorizationStarted = false;
|
|
50
|
-
constructor(file, redirect) {
|
|
55
|
+
constructor(file, redirect, requestedAgentId, interactive = true, resource = RESOURCE) {
|
|
51
56
|
this.file = file;
|
|
52
|
-
this.
|
|
53
|
-
this.
|
|
57
|
+
this.requestedAgentId = requestedAgentId;
|
|
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;
|
|
54
63
|
this.remember(this.saved.tokens);
|
|
55
64
|
}
|
|
56
65
|
get clientMetadata() {
|
|
@@ -67,13 +76,17 @@ class Provider {
|
|
|
67
76
|
saveCodeVerifier(value) { this.verifier = value; }
|
|
68
77
|
codeVerifier() { return this.verifier; }
|
|
69
78
|
async validateResourceURL(server, resource) {
|
|
70
|
-
if (String(server) !==
|
|
79
|
+
if (String(server) !== this.resource || (resource !== undefined && resource !== this.resource))
|
|
71
80
|
throw new Error('ResourceMismatch');
|
|
72
|
-
return new URL(
|
|
81
|
+
return new URL(this.resource);
|
|
73
82
|
}
|
|
74
83
|
async redirectToAuthorization(url) {
|
|
75
|
-
if (
|
|
84
|
+
if (!this.interactive)
|
|
85
|
+
throw new Error('ReconnectRequired');
|
|
86
|
+
if (url.origin !== new URL(this.resource).origin || url.pathname !== '/authorize')
|
|
76
87
|
throw new Error('AuthorizationOriginMismatch');
|
|
88
|
+
if (this.requestedAgentId)
|
|
89
|
+
url.searchParams.set('requested_agent_id', this.requestedAgentId);
|
|
77
90
|
this.authorizationStarted = true;
|
|
78
91
|
process.stderr.write('Approve the connection as your AgentMesh agent in the browser.\n');
|
|
79
92
|
// Never echo the authorization request/response. This URL contains only
|
|
@@ -93,53 +106,114 @@ class Provider {
|
|
|
93
106
|
}
|
|
94
107
|
save() { writeAtomic(this.file, this.saved); fs.chmodSync(this.file, 0o600); }
|
|
95
108
|
}
|
|
96
|
-
// OAuth discovery/token requests stay on the
|
|
109
|
+
// OAuth discovery/token requests stay on the selected exact allowlisted origin;
|
|
97
110
|
// response redirects cannot exfiltrate Authorization or form credentials.
|
|
98
|
-
const safeFetch = async (input, init) => {
|
|
111
|
+
const safeFetch = (resource, timeout = 15_000) => async (input, init) => {
|
|
99
112
|
const url = new URL(input instanceof Request ? input.url : String(input));
|
|
100
|
-
if (url.origin !==
|
|
113
|
+
if (url.origin !== resourceTarget(resource).origin)
|
|
101
114
|
throw new Error('OAuthOriginMismatch');
|
|
102
|
-
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) });
|
|
103
116
|
};
|
|
104
|
-
export async function openOAuth(profile) {
|
|
117
|
+
export async function openOAuth(profile, requestedAgentId, resource = RESOURCE) {
|
|
118
|
+
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
119
|
+
if (requestedAgentId !== undefined && !uuid.test(requestedAgentId))
|
|
120
|
+
throw new Error('IdentityArgument');
|
|
105
121
|
ownerDirectory(profile);
|
|
106
122
|
const file = path.join(profile, 'credentials.json');
|
|
107
|
-
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.3' });
|
|
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
|
+
}
|
|
108
140
|
const server = http.createServer();
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
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); });
|
|
115
147
|
const address = server.address();
|
|
116
148
|
if (!address || typeof address === 'string')
|
|
117
149
|
throw new Error('CallbackUnavailable');
|
|
118
|
-
const provider = new Provider(file, `http://127.0.0.1:${address.port}/callback
|
|
150
|
+
const provider = new Provider(file, `http://127.0.0.1:${address.port}/callback`, requestedAgentId, true, resource);
|
|
119
151
|
let timer;
|
|
152
|
+
let callback;
|
|
153
|
+
let accepted = false, finished = false;
|
|
154
|
+
const failure = 'Approval was not accepted. Return to your terminal and retry Connect.';
|
|
155
|
+
const cleanup = () => { clearTimeout(timer); server.close(); };
|
|
156
|
+
const fail = () => {
|
|
157
|
+
finished = true;
|
|
158
|
+
if (callback && !callback.writableEnded) {
|
|
159
|
+
callback.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
160
|
+
callback.end(failure);
|
|
161
|
+
}
|
|
162
|
+
cleanup();
|
|
163
|
+
};
|
|
120
164
|
const code = new Promise((resolve, reject) => {
|
|
121
|
-
timer = setTimeout(() =>
|
|
165
|
+
timer = setTimeout(() => {
|
|
166
|
+
console.error({ error_class: 'Error', cause: 'ApprovalTimeout', location: 'mcp/src/oauth-client.ts:openOAuth:approvalTimeout' });
|
|
167
|
+
fail();
|
|
168
|
+
reject(new Error('ApprovalTimeout'));
|
|
169
|
+
}, 360_000); // Five-minute server request plus setup budget.
|
|
122
170
|
server.on('request', (req, res) => {
|
|
123
171
|
res.setHeader('Cache-Control', 'no-store');
|
|
124
172
|
res.setHeader('Referrer-Policy', 'no-referrer');
|
|
125
|
-
|
|
173
|
+
let url;
|
|
174
|
+
try {
|
|
175
|
+
url = new URL(req.url ?? '/', provider.redirectUrl);
|
|
176
|
+
}
|
|
177
|
+
catch (error) {
|
|
178
|
+
console.error({ error_class: error instanceof Error ? error.constructor.name : 'UnknownError', cause: 'InvalidCallbackURL', location: 'mcp/src/oauth-client.ts:openOAuth:callbackURL' });
|
|
179
|
+
res.writeHead(400);
|
|
180
|
+
res.end(failure);
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
126
183
|
const value = url.searchParams.get('code');
|
|
127
|
-
if (req.method !== 'GET' || req.headers.host !== `127.0.0.1:${address.port}` || url.pathname !== '/callback'
|
|
184
|
+
if (finished || accepted || req.method !== 'GET' || req.headers.host !== `127.0.0.1:${address.port}` || url.pathname !== '/callback'
|
|
185
|
+
|| url.searchParams.getAll('state').length !== 1 || url.searchParams.getAll('code').length !== 1
|
|
128
186
|
|| !provider.validState(url.searchParams.get('state')) || !value || url.searchParams.has('error')) {
|
|
187
|
+
console.error({ error_class: 'CallbackValidationError', cause: 'InvalidOrReplayedCallback', location: 'mcp/src/oauth-client.ts:openOAuth:callbackValidation' });
|
|
129
188
|
res.writeHead(400);
|
|
130
|
-
res.end(
|
|
189
|
+
res.end(failure);
|
|
131
190
|
return;
|
|
132
191
|
}
|
|
133
|
-
|
|
134
|
-
|
|
192
|
+
// A code is only an input to token exchange, never proof of connection.
|
|
193
|
+
accepted = true;
|
|
194
|
+
callback = res;
|
|
135
195
|
resolve(value);
|
|
136
196
|
});
|
|
137
197
|
});
|
|
198
|
+
const complete = ({ agentId, workspaceId }) => {
|
|
199
|
+
if (!accepted)
|
|
200
|
+
return; // Cached-token launch has no browser response.
|
|
201
|
+
if (finished || !callback || callback.destroyed || !uuid.test(agentId) || !uuid.test(workspaceId)) {
|
|
202
|
+
console.error({ error_class: 'Error', cause: 'ApprovalUnavailable', location: 'mcp/src/oauth-client.ts:openOAuth:complete' });
|
|
203
|
+
throw new Error('ApprovalUnavailable');
|
|
204
|
+
}
|
|
205
|
+
const target = new URL(resourceTarget(resource).origin + '/');
|
|
206
|
+
target.hash = `/connection-complete?workspace=${workspaceId}&agent=${agentId}`;
|
|
207
|
+
callback.writeHead(303, { Location: target.href });
|
|
208
|
+
callback.end();
|
|
209
|
+
finished = true;
|
|
210
|
+
cleanup();
|
|
211
|
+
};
|
|
138
212
|
// A cached-token success never awaits the callback; prevent an unhandled
|
|
139
213
|
// rejection while its timer is being cancelled in finally.
|
|
140
214
|
void code.catch(() => undefined);
|
|
141
|
-
const transport = new StreamableHTTPClientTransport(new URL(
|
|
142
|
-
let client = new Client({ name: 'agentmesh-terminal', version: '0.2.
|
|
215
|
+
const transport = new StreamableHTTPClientTransport(new URL(resource), { authProvider: provider, fetch: safeFetch(resource) });
|
|
216
|
+
let client = new Client({ name: 'agentmesh-terminal', version: '0.2.2' });
|
|
143
217
|
try {
|
|
144
218
|
try {
|
|
145
219
|
await client.connect(transport);
|
|
@@ -149,17 +223,95 @@ export async function openOAuth(profile) {
|
|
|
149
223
|
throw error;
|
|
150
224
|
await transport.finishAuth(await code);
|
|
151
225
|
await client.close();
|
|
152
|
-
client = new Client({ name: 'agentmesh-terminal', version: '0.2.
|
|
153
|
-
await client.connect(new StreamableHTTPClientTransport(new URL(
|
|
226
|
+
client = new Client({ name: 'agentmesh-terminal', version: '0.2.2' });
|
|
227
|
+
await client.connect(new StreamableHTTPClientTransport(new URL(resource), { authProvider: provider, fetch: safeFetch(resource) }));
|
|
154
228
|
}
|
|
155
|
-
|
|
229
|
+
if (!accepted)
|
|
230
|
+
cleanup();
|
|
231
|
+
return { client, redact: (value) => provider.redact(value), complete, close: async () => { if (!finished)
|
|
232
|
+
fail(); await client.close(); } };
|
|
156
233
|
}
|
|
157
234
|
catch (error) {
|
|
235
|
+
console.error({ error_class: error instanceof Error ? error.constructor.name : 'UnknownError', location: 'mcp/src/oauth-client.ts:openOAuth:connect' });
|
|
236
|
+
fail();
|
|
158
237
|
await client.close().catch(() => undefined);
|
|
159
238
|
throw error;
|
|
160
239
|
}
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
240
|
+
}
|
|
241
|
+
// A request owns the profile lock from reload through refresh and completion.
|
|
242
|
+
// No stale provider survives another process rotating the refresh token.
|
|
243
|
+
export async function savedOAuth(profile, operation, resource = RESOURCE) {
|
|
244
|
+
const { locked } = await import('./plugin-storage.js');
|
|
245
|
+
return locked(profile, 'oauth', async () => {
|
|
246
|
+
const file = path.join(profile, 'credentials.json'), saved = credentialFile(file, resource);
|
|
247
|
+
if (!saved?.tokens || !saved.client)
|
|
248
|
+
throw new Error('ReconnectRequired');
|
|
249
|
+
const provider = new Provider(file, saved.redirect, undefined, false, resource);
|
|
250
|
+
const client = new Client({ name: 'agentmesh-session', version: '0.3.3' });
|
|
251
|
+
try {
|
|
252
|
+
await client.connect(new StreamableHTTPClientTransport(new URL(resource), { authProvider: provider, fetch: safeFetch(resource) }));
|
|
253
|
+
return provider.redact(await operation(client));
|
|
254
|
+
}
|
|
255
|
+
catch (error) {
|
|
256
|
+
if (error instanceof UnauthorizedError || error instanceof StreamableHTTPError && (error.code === 401 || error.code === 403))
|
|
257
|
+
throw new Error('ReconnectRequired');
|
|
258
|
+
throw error;
|
|
259
|
+
}
|
|
260
|
+
finally {
|
|
261
|
+
await client.close().catch(() => undefined);
|
|
262
|
+
}
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
/** Listener-owned connection. Only the existing locked provider rotates tokens;
|
|
266
|
+
* no credential lock is held during a server wait or ordinary healthy request. */
|
|
267
|
+
export async function openSavedOAuth(profile, resource = RESOURCE) {
|
|
268
|
+
const file = path.join(profile, 'credentials.json'), lifetime = new AbortController(), secrets = new Set();
|
|
269
|
+
const redact = (value) => { let text = JSON.stringify(value); for (const secret of secrets)
|
|
270
|
+
text = text.split(secret).join('[redacted]'); return JSON.parse(text); };
|
|
271
|
+
const snapshot = () => {
|
|
272
|
+
const saved = credentialFile(file, resource);
|
|
273
|
+
if (!saved?.tokens?.access_token || !saved.client)
|
|
274
|
+
throw new Error('ReconnectRequired');
|
|
275
|
+
for (const token of [saved.tokens.access_token, saved.tokens.refresh_token])
|
|
276
|
+
if (token)
|
|
277
|
+
secrets.add(token);
|
|
278
|
+
return saved.tokens.access_token;
|
|
279
|
+
};
|
|
280
|
+
const transportFetch = async (input, init) => {
|
|
281
|
+
let held = false;
|
|
282
|
+
if (typeof init?.body === 'string')
|
|
283
|
+
try {
|
|
284
|
+
const rpc = JSON.parse(init.body);
|
|
285
|
+
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;
|
|
286
|
+
}
|
|
287
|
+
catch { /* ordinary deadline */ }
|
|
288
|
+
const signal = AbortSignal.any([lifetime.signal, ...init?.signal ? [init.signal] : [], AbortSignal.timeout(held ? 35_000 : 15_000)]);
|
|
289
|
+
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 }); };
|
|
290
|
+
let response = await request();
|
|
291
|
+
if (response.status === 401) {
|
|
292
|
+
await response.body?.cancel();
|
|
293
|
+
signal.throwIfAborted();
|
|
294
|
+
// Reload under the same cross-process lock as proxy calls. Another caller
|
|
295
|
+
// may already have refreshed; connecting with its fresh token does no write.
|
|
296
|
+
await savedOAuth(profile, async () => null, resource);
|
|
297
|
+
signal.throwIfAborted();
|
|
298
|
+
response = await request();
|
|
299
|
+
}
|
|
300
|
+
if (response.status === 401 || response.status === 403) {
|
|
301
|
+
await response.body?.cancel();
|
|
302
|
+
throw new Error('ReconnectRequired');
|
|
303
|
+
}
|
|
304
|
+
return response;
|
|
305
|
+
};
|
|
306
|
+
const client = new Client({ name: 'agentmesh-session-listener', version: '0.3.3' });
|
|
307
|
+
const close = async () => { lifetime.abort(); await client.close().catch(() => undefined); };
|
|
308
|
+
try {
|
|
309
|
+
snapshot();
|
|
310
|
+
await client.connect(new StreamableHTTPClientTransport(new URL(resource), { fetch: transportFetch }));
|
|
311
|
+
return { client, redact, close };
|
|
312
|
+
}
|
|
313
|
+
catch (error) {
|
|
314
|
+
await close();
|
|
315
|
+
throw error;
|
|
164
316
|
}
|
|
165
317
|
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { spawn } from 'node:child_process';
|
|
5
|
+
import { randomUUID, createHash } from 'node:crypto';
|
|
6
|
+
import { privateRoot, locked } from './plugin-storage.js';
|
|
7
|
+
import { ownerDirectory } from './oauth-client.js';
|
|
8
|
+
import { connectionTarget } from './plugin-target.js';
|
|
9
|
+
import { terminalDiagnostic } from './terminal-diagnostic.js';
|
|
10
|
+
import { installCodexHooks } from './codex-hooks.js';
|
|
11
|
+
const VERSION = '0.3.3';
|
|
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
|
+
export async function installPlugin(client, executable, target = connectionTarget()) {
|
|
32
|
+
if (!path.isAbsolute(executable))
|
|
33
|
+
throw new Error('InstallerAbsolutePathRequired');
|
|
34
|
+
if (client === 'claude') {
|
|
35
|
+
await locked(privateRoot(), 'install', async () => {
|
|
36
|
+
await command(executable, ['plugin', 'marketplace', 'add', target.marketplace]);
|
|
37
|
+
await command(executable, ['plugin', 'install', 'agentmesh@agentmesh', '--scope', 'user']);
|
|
38
|
+
// Native install is idempotent for an existing plugin, even at an old version.
|
|
39
|
+
await command(executable, ['plugin', 'update', 'agentmesh@agentmesh', '--scope', 'user']);
|
|
40
|
+
const output = await command(executable, ['plugin', 'list', '--json'], true);
|
|
41
|
+
let entries;
|
|
42
|
+
try {
|
|
43
|
+
entries = JSON.parse(output);
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
throw new Error('PluginInstallReadbackInvalid');
|
|
47
|
+
}
|
|
48
|
+
if (!Array.isArray(entries))
|
|
49
|
+
throw new Error('PluginInstallReadbackInvalid');
|
|
50
|
+
const installed = entries.filter(value => value && value.id === 'agentmesh@agentmesh' && value.scope === 'user');
|
|
51
|
+
if (installed.length !== 1 || installed[0].version !== VERSION)
|
|
52
|
+
throw new Error('PluginInstallVersionMismatch');
|
|
53
|
+
});
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
// npm carries the exact generated marketplace, never a second hand copy.
|
|
57
|
+
const source = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../plugin-marketplace');
|
|
58
|
+
if (!fs.existsSync(path.join(source, '.claude-plugin', 'marketplace.json')))
|
|
59
|
+
throw new Error('PackagedMarketplaceMissing');
|
|
60
|
+
// Codex installs immutable copied bytes. The digest also distinguishes fixes
|
|
61
|
+
// made at the same unpublished version; a stale release must not win.
|
|
62
|
+
const hash = createHash('sha256');
|
|
63
|
+
const digest = (dir) => { for (const name of fs.readdirSync(dir).sort()) {
|
|
64
|
+
const full = path.join(dir, name), stat = fs.lstatSync(full);
|
|
65
|
+
if (stat.isSymbolicLink())
|
|
66
|
+
throw new Error('PluginSymlinkRejected');
|
|
67
|
+
hash.update(path.relative(source, full));
|
|
68
|
+
if (stat.isDirectory())
|
|
69
|
+
digest(full);
|
|
70
|
+
else
|
|
71
|
+
hash.update(fs.readFileSync(full));
|
|
72
|
+
} };
|
|
73
|
+
digest(source);
|
|
74
|
+
const root = privateRoot(), release = path.join(root, 'release-' + VERSION + '-' + hash.digest('hex'));
|
|
75
|
+
await locked(root, 'install', async () => {
|
|
76
|
+
if (!fs.existsSync(release)) {
|
|
77
|
+
const temp = release + '.' + randomUUID();
|
|
78
|
+
fs.cpSync(source, temp, { recursive: true, dereference: false });
|
|
79
|
+
const secure = (dir) => { ownerDirectory(dir); for (const file of fs.readdirSync(dir)) {
|
|
80
|
+
const full = path.join(dir, file), stat = fs.lstatSync(full);
|
|
81
|
+
if (stat.isSymbolicLink())
|
|
82
|
+
throw new Error('PluginSymlinkRejected');
|
|
83
|
+
if (stat.isDirectory())
|
|
84
|
+
secure(full);
|
|
85
|
+
else
|
|
86
|
+
fs.chmodSync(full, 0o600);
|
|
87
|
+
} };
|
|
88
|
+
secure(temp);
|
|
89
|
+
fs.renameSync(temp, release);
|
|
90
|
+
}
|
|
91
|
+
else
|
|
92
|
+
ownerDirectory(release);
|
|
93
|
+
await command(executable, ['plugin', 'marketplace', 'add', release]);
|
|
94
|
+
await command(executable, ['plugin', 'add', 'agentmesh@agentmesh']);
|
|
95
|
+
await installCodexHooks(path.join(release, 'plugins/agentmesh/server/lib/agentmesh-mcp.js'));
|
|
96
|
+
});
|
|
97
|
+
}
|