@agentmesh-md/mcp-server 0.2.2 → 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 +127 -0
- package/dist/client.js +16 -5
- package/dist/codex-hooks.js +142 -0
- package/dist/connect.js +77 -205
- 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 +128 -26
- 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
|
}
|
|
@@ -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.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
|
+
}
|
|
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,7 +212,7 @@ 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 {
|
|
193
218
|
try {
|
|
@@ -199,7 +224,7 @@ export async function openOAuth(profile, requestedAgentId) {
|
|
|
199
224
|
await transport.finishAuth(await code);
|
|
200
225
|
await client.close();
|
|
201
226
|
client = new Client({ name: 'agentmesh-terminal', version: '0.2.2' });
|
|
202
|
-
await client.connect(new StreamableHTTPClientTransport(new URL(
|
|
227
|
+
await client.connect(new StreamableHTTPClientTransport(new URL(resource), { authProvider: provider, fetch: safeFetch(resource) }));
|
|
203
228
|
}
|
|
204
229
|
if (!accepted)
|
|
205
230
|
cleanup();
|
|
@@ -213,3 +238,80 @@ export async function openOAuth(profile, requestedAgentId) {
|
|
|
213
238
|
throw error;
|
|
214
239
|
}
|
|
215
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;
|
|
316
|
+
}
|
|
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
|
+
}
|
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import { openSavedOAuth } from './oauth-client.js';
|
|
3
|
+
import { parsed } from './connect.js';
|
|
4
|
+
import { spawn } from 'node:child_process';
|
|
5
|
+
import { UUID, pause, privateRead, processIdentity } from './plugin-storage.js';
|
|
6
|
+
import { wakeLine, unfinishedLine, enrolled, currentBinding, alive, waitCatalog, validCatalog, catalogFile, pollerFile, activityStamp, generation, supersededCatalog } from './plugin-session.js';
|
|
7
|
+
import { queueExecutable, RESTART_RUNTIME } from './terminal-runtime.js';
|
|
8
|
+
import { writeAtomic } from './wake-storage.js';
|
|
9
|
+
import { retireProfile } from './plugin-permissions.js';
|
|
10
|
+
import { terminalDiagnostic } from './terminal-diagnostic.js';
|
|
11
|
+
export { wakeLine, unfinishedLine } from './plugin-session.js';
|
|
12
|
+
export async function queueThread(session, line, executable) {
|
|
13
|
+
if (!UUID.test(session))
|
|
14
|
+
throw new Error('SessionIdentityInvalid');
|
|
15
|
+
const child = spawn(executable, ['queue', '--thread', session, '--message', line], { stdio: 'ignore' });
|
|
16
|
+
await new Promise((resolve, reject) => { const timer = setTimeout(() => { child.kill(); reject(new Error('QueueDeliveryUnknown')); }, 10000); child.once('error', () => { clearTimeout(timer); reject(new Error('QueueNotStarted')); }); child.once('exit', c => { clearTimeout(timer); c === 0 ? resolve() : reject(new Error('QueueDeliveryUnknown')); }); });
|
|
17
|
+
}
|
|
18
|
+
const cheapAlive = (pid) => { try {
|
|
19
|
+
process.kill(pid, 0);
|
|
20
|
+
return true;
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return false;
|
|
24
|
+
} };
|
|
25
|
+
export async function monitor(kind) {
|
|
26
|
+
// Before enrollment: no ancestry/version subprocesses, network, or output.
|
|
27
|
+
let lastActivity = 0;
|
|
28
|
+
let stopped = false, ended = false, b, registered = false, errors = 0, blocked;
|
|
29
|
+
let session, abort;
|
|
30
|
+
const parent = process.ppid, delivered = new Set(), unfinished = new Set();
|
|
31
|
+
const diagnose = (message, error) => {
|
|
32
|
+
const text = message + ' ' + terminalDiagnostic(error, 'plugin-monitor.js', 'monitor') + '\n';
|
|
33
|
+
if (kind === 'codex' && process.argv[6] === 'tty')
|
|
34
|
+
try {
|
|
35
|
+
fs.writeSync(3, text);
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
catch { /* Closed native terminal: retain stderr diagnostics. */ }
|
|
39
|
+
process.stderr.write(text);
|
|
40
|
+
};
|
|
41
|
+
const stop = () => { stopped = true; abort?.abort(); };
|
|
42
|
+
const end = () => { ended = true; stop(); };
|
|
43
|
+
for (const sig of ['SIGINT', 'SIGTERM', 'SIGHUP'])
|
|
44
|
+
process.once(sig, stop);
|
|
45
|
+
process.once('SIGUSR1', end);
|
|
46
|
+
const call = async (op, args = {}, signal) => {
|
|
47
|
+
if (!b || !alive(b))
|
|
48
|
+
throw new Error('NativeOwnerEnded');
|
|
49
|
+
session ??= await openSavedOAuth(b.enrollment.profile, b.enrollment.resource);
|
|
50
|
+
const result = session.redact(await session.client.callTool({ name: 'terminal_wake_' + op, arguments: { ...args, connection_id: b.id } }, undefined, { signal }));
|
|
51
|
+
// Only a poll's typed missing-connection error resets registration. A stale
|
|
52
|
+
// receipt/claim must not reconnect or replay an external delivery.
|
|
53
|
+
if (op === 'poll' && result.isError && Array.isArray(result.content) && result.content.some(c => c.type === 'text' && typeof c.text === 'string' && c.text.startsWith('NOT_FOUND:')))
|
|
54
|
+
throw new Error('WakeConnectionUnavailable');
|
|
55
|
+
return parsed(result);
|
|
56
|
+
};
|
|
57
|
+
const superseded = () => {
|
|
58
|
+
if (kind !== 'claude' || !b)
|
|
59
|
+
return false;
|
|
60
|
+
try {
|
|
61
|
+
return supersededCatalog(b, privateRead(catalogFile(kind, b.owner)));
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
return false;
|
|
65
|
+
} // Invalid state is diagnosed by the normal catalog validation, never retirement authority.
|
|
66
|
+
};
|
|
67
|
+
const drop = async (close) => {
|
|
68
|
+
if (close && registered && session && b)
|
|
69
|
+
await session.client.callTool({ name: 'terminal_wake_checkin', arguments: { connection_id: b.id, state: 'closed' } }).catch(() => undefined);
|
|
70
|
+
await session?.close();
|
|
71
|
+
session = undefined;
|
|
72
|
+
registered = false;
|
|
73
|
+
};
|
|
74
|
+
try {
|
|
75
|
+
while (!stopped) {
|
|
76
|
+
if (superseded())
|
|
77
|
+
break;
|
|
78
|
+
if (b ? processIdentity(b.owner) !== b.start : kind === 'claude' && !cheapAlive(parent)) {
|
|
79
|
+
ended = true;
|
|
80
|
+
break;
|
|
81
|
+
}
|
|
82
|
+
let bindingReady = false, activityChanged = false;
|
|
83
|
+
try {
|
|
84
|
+
if (!enrolled(kind)) {
|
|
85
|
+
await drop(true);
|
|
86
|
+
b = undefined;
|
|
87
|
+
if (kind === 'codex')
|
|
88
|
+
break;
|
|
89
|
+
await pause(2000);
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
const next = await currentBinding(kind);
|
|
93
|
+
if (b?.id !== next.id) {
|
|
94
|
+
await drop(true);
|
|
95
|
+
b = next;
|
|
96
|
+
lastActivity = activityStamp(b);
|
|
97
|
+
errors = 0;
|
|
98
|
+
}
|
|
99
|
+
else
|
|
100
|
+
b = next;
|
|
101
|
+
if (blocked === generation(b.enrollment)) {
|
|
102
|
+
await pause(2000);
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
bindingReady = true;
|
|
106
|
+
if (superseded())
|
|
107
|
+
break;
|
|
108
|
+
if (kind === 'claude') {
|
|
109
|
+
if (!registered)
|
|
110
|
+
await waitCatalog(b);
|
|
111
|
+
else if (!validCatalog(b, privateRead(catalogFile(kind, b.owner))))
|
|
112
|
+
throw new Error('NativeCatalogNotReady');
|
|
113
|
+
}
|
|
114
|
+
if (!registered) {
|
|
115
|
+
await call('start', { binding_id: b.id, client: kind, runtime_version: b.version, protocol: 2, session_id: b.session, host_id: b.host, folder_id: b.folder });
|
|
116
|
+
registered = true;
|
|
117
|
+
}
|
|
118
|
+
abort = new AbortController();
|
|
119
|
+
const active = b, stamp = activityStamp(b);
|
|
120
|
+
const watch = setInterval(() => { try {
|
|
121
|
+
if (activityStamp(active) !== stamp) {
|
|
122
|
+
activityChanged = true;
|
|
123
|
+
abort?.abort();
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
if (!alive(active) || superseded() || kind === 'claude' && !validCatalog(active, privateRead(catalogFile(kind, active.owner))))
|
|
127
|
+
abort?.abort();
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
abort?.abort();
|
|
131
|
+
} }, 500);
|
|
132
|
+
let pending;
|
|
133
|
+
// A close-before-reload catalog gap can drop the stamp to zero. Only
|
|
134
|
+
// forward user activity advances server priority; never the missing state.
|
|
135
|
+
try {
|
|
136
|
+
pending = await call('poll', { wait_seconds: 25, ...stamp > lastActivity ? { activity: true, session_id: b.session } : {} }, abort.signal);
|
|
137
|
+
lastActivity = Math.max(lastActivity, stamp);
|
|
138
|
+
}
|
|
139
|
+
finally {
|
|
140
|
+
clearInterval(watch);
|
|
141
|
+
abort = undefined;
|
|
142
|
+
}
|
|
143
|
+
if (activityChanged || stopped || !alive(b) || superseded())
|
|
144
|
+
continue;
|
|
145
|
+
if (kind === 'claude' && !validCatalog(b, privateRead(catalogFile(kind, b.owner))))
|
|
146
|
+
continue;
|
|
147
|
+
if (pending.connection_id !== b.id || pending.agent_id !== b.enrollment.agentId || pending.workspace_id !== b.enrollment.workspaceId || !Array.isArray(pending.events))
|
|
148
|
+
throw new Error('WakeIdentityMismatch');
|
|
149
|
+
for (const item of pending.unhandled ?? []) {
|
|
150
|
+
const key = [item.event_id, item.claim_id, item.owned].join(':');
|
|
151
|
+
if (unfinished.has(key))
|
|
152
|
+
continue;
|
|
153
|
+
const line = unfinishedLine(item), executable = kind === 'codex' ? queueExecutable(b.runtime) : '';
|
|
154
|
+
unfinished.add(key);
|
|
155
|
+
try {
|
|
156
|
+
if (kind === 'codex')
|
|
157
|
+
await queueThread(b.session, line, executable);
|
|
158
|
+
else
|
|
159
|
+
process.stdout.write(line + '\n');
|
|
160
|
+
}
|
|
161
|
+
catch (error) {
|
|
162
|
+
if (error instanceof Error && error.message === 'QueueNotStarted')
|
|
163
|
+
unfinished.delete(key);
|
|
164
|
+
throw error;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
for (const event of pending.events) {
|
|
168
|
+
if (stopped || !alive(b))
|
|
169
|
+
break;
|
|
170
|
+
const line = wakeLine(event);
|
|
171
|
+
if (!delivered.has(event.offer_id)) {
|
|
172
|
+
const executable = kind === 'codex' ? queueExecutable(b.runtime) : '';
|
|
173
|
+
// Validation failures are not delivery attempts. Ambiguous queue failures
|
|
174
|
+
// are never replayed for this offer.
|
|
175
|
+
delivered.add(event.offer_id);
|
|
176
|
+
try {
|
|
177
|
+
if (kind === 'codex')
|
|
178
|
+
await queueThread(b.session, line, executable);
|
|
179
|
+
else
|
|
180
|
+
process.stdout.write(line + '\n');
|
|
181
|
+
}
|
|
182
|
+
catch (error) {
|
|
183
|
+
if (error instanceof Error && error.message === 'QueueNotStarted')
|
|
184
|
+
delivered.delete(event.offer_id);
|
|
185
|
+
throw error;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
await call('receipt', { event_id: event.event_id, offer_id: event.offer_id, stage: 'transport' });
|
|
189
|
+
}
|
|
190
|
+
errors = 0;
|
|
191
|
+
// Bound immediate results (including legacy-wait/unhandled-only servers).
|
|
192
|
+
await pause(1000);
|
|
193
|
+
}
|
|
194
|
+
catch (error) {
|
|
195
|
+
if (superseded())
|
|
196
|
+
break;
|
|
197
|
+
if (stopped)
|
|
198
|
+
continue;
|
|
199
|
+
if (activityChanged)
|
|
200
|
+
continue;
|
|
201
|
+
if (b ? processIdentity(b.owner) !== b.start : kind === 'claude' && !cheapAlive(parent)) {
|
|
202
|
+
ended = true;
|
|
203
|
+
break;
|
|
204
|
+
}
|
|
205
|
+
if (kind === 'codex' && !b) {
|
|
206
|
+
diagnose(error instanceof Error && error.message === 'RuntimeRestartRequired' ? RESTART_RUNTIME : 'AgentMesh listener unavailable.', error);
|
|
207
|
+
break;
|
|
208
|
+
}
|
|
209
|
+
// Enrollment may disappear/change while async native version discovery runs.
|
|
210
|
+
// Corrupt or unsafe state is diagnosed and retried, never treated as absent.
|
|
211
|
+
let available = false, invalid = false, bindingLive = false;
|
|
212
|
+
try {
|
|
213
|
+
available = enrolled(kind);
|
|
214
|
+
bindingLive = !!b && alive(b);
|
|
215
|
+
}
|
|
216
|
+
catch {
|
|
217
|
+
invalid = true;
|
|
218
|
+
}
|
|
219
|
+
if (!invalid && !available) {
|
|
220
|
+
await drop(true);
|
|
221
|
+
b = undefined;
|
|
222
|
+
errors = 0;
|
|
223
|
+
if (kind === 'codex')
|
|
224
|
+
break;
|
|
225
|
+
await pause(2000);
|
|
226
|
+
continue;
|
|
227
|
+
}
|
|
228
|
+
if (invalid || !bindingReady || !bindingLive) {
|
|
229
|
+
await drop(false);
|
|
230
|
+
b = undefined;
|
|
231
|
+
if (errors === 0)
|
|
232
|
+
diagnose(error instanceof Error && error.message === 'RuntimeRestartRequired' ? RESTART_RUNTIME : 'AgentMesh local listener state unavailable; retrying.', error);
|
|
233
|
+
errors++;
|
|
234
|
+
await pause(Math.min(30000, 1000 * 2 ** Math.min(errors, 5)));
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
const reason = error instanceof Error ? error.message : '';
|
|
238
|
+
if (!b)
|
|
239
|
+
continue;
|
|
240
|
+
if (reason === 'ReconnectRequired') {
|
|
241
|
+
blocked = generation(b.enrollment);
|
|
242
|
+
process.stderr.write('AgentMesh approval expired or was revoked. Re-run Connect; this folder is offline. ' + terminalDiagnostic(error, 'plugin-monitor.js', 'monitor') + '\n');
|
|
243
|
+
try {
|
|
244
|
+
await retireProfile(b.enrollment.profile);
|
|
245
|
+
}
|
|
246
|
+
catch (error) {
|
|
247
|
+
process.stderr.write('AgentMesh local permission cleanup failed. ' + terminalDiagnostic(error, 'plugin-monitor.js', 'monitor') + '\n');
|
|
248
|
+
}
|
|
249
|
+
await drop(false);
|
|
250
|
+
continue;
|
|
251
|
+
}
|
|
252
|
+
if (reason === 'NativeCatalogNotReady') {
|
|
253
|
+
if (errors === 0)
|
|
254
|
+
process.stderr.write('AgentMesh native tools are not ready; this session is offline. ' + terminalDiagnostic(error, 'plugin-monitor.js', 'monitor') + '\n');
|
|
255
|
+
}
|
|
256
|
+
else
|
|
257
|
+
diagnose(reason === 'RuntimeRestartRequired' ? RESTART_RUNTIME : 'AgentMesh listener unavailable; retrying.', error);
|
|
258
|
+
// A transient tool/HTTP failure retains OAuth and registration. Only explicit
|
|
259
|
+
// transport/session loss reinitializes this transport, never every poll error.
|
|
260
|
+
if (reason === 'WakeConnectionUnavailable')
|
|
261
|
+
registered = false;
|
|
262
|
+
else if (/(?:closed|not connected|session.*not found)/i.test(reason)) {
|
|
263
|
+
await drop(false);
|
|
264
|
+
}
|
|
265
|
+
errors++;
|
|
266
|
+
await pause(Math.min(30000, 1000 * 2 ** Math.min(errors, 5)) * (.9 + Math.random() * .2));
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
finally {
|
|
271
|
+
abort?.abort();
|
|
272
|
+
let close = ended;
|
|
273
|
+
try {
|
|
274
|
+
close = close || !!b && !alive(b);
|
|
275
|
+
}
|
|
276
|
+
catch { /* Invalid local state is recoverable, not an explicit close. */ }
|
|
277
|
+
await drop(close);
|
|
278
|
+
if (kind === 'codex' && b) {
|
|
279
|
+
const file = pollerFile(b.owner), r = privateRead(file);
|
|
280
|
+
if (r?.pid === process.pid && r.start === processIdentity(process.pid)) {
|
|
281
|
+
if (r.runtime)
|
|
282
|
+
writeAtomic(file, { ...r, pid: 0, start: '', session: ended ? '' : r.session });
|
|
283
|
+
else
|
|
284
|
+
fs.rmSync(file, { force: true });
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
for (const sig of ['SIGINT', 'SIGTERM', 'SIGHUP'])
|
|
288
|
+
process.removeListener(sig, stop);
|
|
289
|
+
process.removeListener('SIGUSR1', end);
|
|
290
|
+
}
|
|
291
|
+
return 0;
|
|
292
|
+
}
|