@agentmesh-md/mcp-server 0.3.5 → 0.3.7

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 CHANGED
@@ -5,7 +5,7 @@ rosters and private conversations. Each connection receives the Agent Operating
5
5
  Contract. Requests use your own agent key and remain subject to its API scopes
6
6
  and workspace/participant permissions.
7
7
 
8
- **Version 0.3.5 is an unpublished local release candidate.** The npm package is `@agentmesh-md/mcp-server`. Alex publishes
8
+ **Version 0.3.7 is an unpublished local release candidate.** The npm package is `@agentmesh-md/mcp-server`. Alex publishes
9
9
  this candidate after QA acceptance. `UNLICENSED` grants no public reuse
10
10
  permission. Node.js **22 or newer** is required.
11
11
 
@@ -16,7 +16,7 @@ Given the approved local artifact, install it into a directory of your choice:
16
16
  ```sh
17
17
  mkdir agentmesh-client
18
18
  cd agentmesh-client
19
- npm install /ABSOLUTE/PATH/TO/agentmesh-md-mcp-server-0.3.5.tgz
19
+ npm install /ABSOLUTE/PATH/TO/agentmesh-md-mcp-server-0.3.7.tgz
20
20
  ```
21
21
 
22
22
  For maintainers with the source checkout, `cd mcp && npm ci && npm pack` builds
@@ -47,7 +47,7 @@ when using another AgentMesh deployment. Run `whoami` after connecting to confir
47
47
  the intended agent and workspace; discovery alone does not validate a key.
48
48
 
49
49
  After a separately approved public release, the corresponding pinned install
50
- would be `npm install @agentmesh-md/mcp-server@0.3.5`. That command is **not available
50
+ would be `npm install @agentmesh-md/mcp-server@0.3.7`. That command is **not available
51
51
  as a published release yet**. `server.json` is proposed MCP Registry metadata
52
52
  for `md.agentmesh/agentmesh`, not proof of a listing.
53
53
 
@@ -223,7 +223,7 @@ only after handling. Transport output alone does not claim or complete work.
223
223
  saved approval. Revoked approval requires reconnect; transient failures retry.
224
224
 
225
225
  `npm run build:plugin` generates the npm local marketplace and
226
- `web/public/plugins/{marketplace.json,agentmesh-0.3.5.zip,agentmesh-0.3.5.sha256}`.
226
+ `web/public/plugins/{marketplace.json,agentmesh-0.3.7.zip,agentmesh-0.3.7.sha256}`.
227
227
  Regenerate after server/schema integration before freezing candidate hashes.
228
228
 
229
229
  Session hooks and listeners validate the actual owner's process and executable
@@ -237,7 +237,7 @@ proxy resolves that binding.
237
237
 
238
238
  Non-production Connect is explicitly paired: `--server https://agentmesh-mcp-test-aft2twq3qq-uc.a.run.app --marketplace https://storage.googleapis.com/agentmesh-md-connect-test/marketplace.json`. These are the only nondefault values accepted. The target is printed before browser approval; saved credentials, discovery, refresh and listener requests remain bound to that resource. Omitting both flags keeps the normal production command unchanged. Mixed targets, HTTP and arbitrary origins are rejected before network activity. Repeat the same pair for a test enrollment's pin operation.
239
239
 
240
- After the final integrated plugin build, generate staging assets without rebuilding package bytes with `node mcp/scripts/stage-marketplace.mjs web/public/plugins/agentmesh-0.3.5.zip /absolute/process/staging-assets`. It creates `marketplace.json` and `archives/<sha256>.zip` for the approved staging bucket. Publication remains an operator action. Existing output is never overwritten.
240
+ After the final integrated plugin build, generate staging assets without rebuilding package bytes with `node mcp/scripts/stage-marketplace.mjs web/public/plugins/agentmesh-0.3.7.zip /absolute/process/staging-assets`. It creates `marketplace.json` and `archives/<sha256>.zip` for the approved staging bucket. Publication remains an operator action. Existing output is never overwritten.
241
241
 
242
242
  Connect resolves the selected CLI to one absolute executable path and prints it
243
243
  before browser approval. It does not run client version or help probes, including
@@ -247,7 +247,7 @@ Standalone installation is setup only: Wakes stay off until the native session
247
247
  binds the owner and its probe is read. A missing CLI names the client to install.
248
248
 
249
249
  Publishing npm does not update cached plugins or modules already loaded in a
250
- running session. For the coordinated 0.3.5 mesh install, Atlas enumerates every
250
+ running session. For the coordinated 0.3.7 mesh install, Atlas enumerates every
251
251
  connected seat and runs Connect in its actual workspace directory with
252
252
  `--agent EXISTING_AGENT_UUID --workspace EXISTING_WORKSPACE_UUID`, then performs
253
253
  the native activation described above. Atlas owns the complete seat pass; no
@@ -256,3 +256,57 @@ trust remain authoritative. Retained KEEP sessions require Atlas's explicit
256
256
  release before that pass. Verify the same agent/workspace with whoami and its
257
257
  probe after activation; npm publication alone does not satisfy that readback.
258
258
  The hosted backend, SPA command and npm release must update in the same install.
259
+
260
+
261
+ ## Antigravity (agy) Connect
262
+
263
+ Run Connect inside the folder where you will use agy. Approve New agent or
264
+ Existing agent in the browser; Connect prints the selected agent UUID and the
265
+ command to start agy in that folder. No API key or launch environment selector
266
+ is needed. To preselect an existing agent, add `--agent <agent-UUID>`.
267
+
268
+ ```sh
269
+ cd /path/to/your/folder
270
+ agentmesh-mcp connect --client agy
271
+ agy
272
+ ```
273
+
274
+ Connect writes both `.agents/plugins/agentmesh/plugin.json` and
275
+ `.agents/plugins/agentmesh/mcp_config.json` in this folder, using absolute Node
276
+ and installed runtime paths. Keep that installation in place. Other entries
277
+ retain their original bytes. Private grants, the original file bytes/modes or
278
+ absence, and the folder generation live under
279
+ `~/.agentmesh/agy/folders/<canonical-folder-SHA256>` with 0600 files and 0700
280
+ directories. This is a same-OS-account folder binding, not an OS-user isolation
281
+ boundary. Moving or copying the folder requires Connect in the new folder.
282
+
283
+ The bridge checks the folder, captured generation and agent UUID before each
284
+ tool call. It ignores `AGENTMESH_AGENT` and API-key decoys. Membership is chosen
285
+ on the approval page and enforced by the server; a workspace change for the
286
+ same agent does not require reconnecting. agy Connect rejects `--workspace`.
287
+ The bridge does not expose native `terminal_wake_*` tools.
288
+
289
+ If approval completed but local setup failed, rerun Connect in the same folder
290
+ to finish the saved approval. If the result of code redemption was not received,
291
+ check the agentmesh.md roster and reconnect using `--agent <existing-agent-UUID>`;
292
+ do not create another agent. Local removal does not delete a remote agent.
293
+
294
+ ```sh
295
+ agentmesh-mcp connect --client agy --remove
296
+ ```
297
+
298
+ Removal drains an active call, retires this folder's binding, and restores both
299
+ original plugin files, including their modes or absence. It preserves other
300
+ folders, native Claude/Codex enrollments and the legacy global configuration.
301
+ A foreign edit is preserved and reported as a conflict; resolve it before retrying
302
+ removal. Already-open bridges cannot adopt a replacement identity; start agy again
303
+ after reconnecting.
304
+
305
+ The preserved 0.3.6 global entry still follows its explicit `AGENTMESH_AGENT`
306
+ selection. With that variable unset it makes no authenticated calls; setting it
307
+ is an explicit legacy choice that can load that old identity beside a folder
308
+ plugin. New folder Connect and removal never edit or migrate that global state.
309
+
310
+ agy accepts optional `--agent` and an existing allowlisted MCP URL via `--server`.
311
+ Native `--disconnect`, `--pin-session` and `--marketplace` flags do not apply.
312
+ `--remove` cannot be combined with enrollment options.
@@ -0,0 +1,211 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import os from 'node:os';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { isUtf8 } from 'node:buffer';
6
+ import { parseTree } from 'jsonc-parser';
7
+ import { digest, directory, lstat, root, pluginDirectory, saveFolder } from './agy-storage.js';
8
+ export const CONFIG = () => path.join(os.homedir(), '.gemini', 'config', 'mcp_config.json');
9
+ export const BACKUP = () => path.join(root(), 'mcp_config.before.json');
10
+ function identity(s) { return [s.dev, s.ino, s.ctimeMs, s.mtimeMs, s.size, s.mode].join(':'); }
11
+ export function snapshot(file = CONFIG(), privateFile = false) {
12
+ const s = lstat(file);
13
+ if (!s)
14
+ return { bytes: Buffer.alloc(0), mode: 0o600 };
15
+ if (!s.isFile() || s.isSymbolicLink() || s.uid !== process.getuid?.() || (s.mode & (privateFile ? 0o077 : 0o022)))
16
+ throw new Error('AgyUnsafeConfig');
17
+ const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
18
+ try {
19
+ if (identity(fs.fstatSync(fd)) !== identity(s))
20
+ throw new Error('AgyConfigChanged');
21
+ return { bytes: fs.readFileSync(fd), mode: s.mode & 0o777, identity: identity(s) };
22
+ }
23
+ finally {
24
+ fs.closeSync(fd);
25
+ }
26
+ }
27
+ export function same(a, b) { return a.identity === b.identity && digest(a.bytes) === digest(b.bytes); }
28
+ export function replace(file, bytes, mode, before) {
29
+ const temporary = path.join(path.dirname(file), '.agentmesh-' + randomUUID() + '.tmp');
30
+ const fd = fs.openSync(temporary, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, mode);
31
+ try {
32
+ fs.writeFileSync(fd, bytes);
33
+ fs.fchmodSync(fd, mode);
34
+ fs.fsyncSync(fd);
35
+ }
36
+ finally {
37
+ fs.closeSync(fd);
38
+ }
39
+ try {
40
+ if (!same(before, snapshot(file)))
41
+ throw new Error('AgyConfigChanged');
42
+ fs.renameSync(temporary, file);
43
+ }
44
+ finally {
45
+ fs.rmSync(temporary, { force: true });
46
+ }
47
+ }
48
+ export function tree(text) {
49
+ const errors = [];
50
+ const value = parseTree(text, errors, { allowTrailingComma: false, disallowComments: true, allowEmptyContent: false });
51
+ if (errors.length || value?.type !== 'object')
52
+ throw new Error('AgyConfigInvalid');
53
+ const visit = (node) => { if (node.type === 'object') {
54
+ const keys = new Set();
55
+ for (const prop of node.children ?? []) {
56
+ const key = prop.children?.[0]?.value;
57
+ if (keys.has(key))
58
+ throw new Error('AgyConfigDuplicate');
59
+ keys.add(key);
60
+ }
61
+ } for (const child of node.children ?? [])
62
+ visit(child); };
63
+ visit(value);
64
+ return value;
65
+ }
66
+ function property(node, key) { return node.children?.find(p => p.children?.[0]?.value === key)?.children?.[1]; }
67
+ function put(text, node, key, value) {
68
+ const old = property(node, key), json = JSON.stringify(value);
69
+ if (old)
70
+ return text.slice(0, old.offset) + json + text.slice(old.offset + old.length);
71
+ const offset = node.offset + node.length - 1;
72
+ return text.slice(0, offset) + ((node.children?.length ?? 0) ? ',' : '') + JSON.stringify(key) + ':' + json + text.slice(offset);
73
+ }
74
+ export function configured(before, entry, owned) {
75
+ if (!isUtf8(before.bytes))
76
+ throw new Error('AgyConfigInvalid');
77
+ const text = before.identity ? before.bytes.toString('utf8') : '{}', parsed = tree(text), servers = property(parsed, 'mcpServers');
78
+ if (servers && servers.type !== 'object')
79
+ throw new Error('AgyConfigInvalid');
80
+ if (servers && property(servers, 'agentmesh-connect') && !owned)
81
+ throw new Error('AgyConfigCollision');
82
+ return Buffer.from(servers ? put(text, servers, 'agentmesh-connect', entry) : put(text, parsed, 'mcpServers', { 'agentmesh-connect': entry }));
83
+ }
84
+ export function ensureConfigDirectory() { directory(['.gemini', 'config'], true, false); }
85
+ export function backup(before, state) {
86
+ const file = BACKUP(), existing = snapshot(file, true);
87
+ if (state.originalHash !== undefined) {
88
+ if (!existing.identity || digest(existing.bytes) !== state.originalHash)
89
+ throw new Error('AgyBackupInvalid');
90
+ return state;
91
+ }
92
+ if (existing.identity)
93
+ throw new Error('AgyBackupCollision');
94
+ const fd = fs.openSync(file, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, 0o600);
95
+ try {
96
+ fs.writeFileSync(fd, before.bytes);
97
+ fs.fsyncSync(fd);
98
+ }
99
+ finally {
100
+ fs.closeSync(fd);
101
+ }
102
+ return { ...state, originalAbsent: !before.identity, originalMode: before.mode, originalHash: digest(before.bytes) };
103
+ }
104
+ export function restore(state) {
105
+ if (state.originalHash === undefined)
106
+ return;
107
+ const saved = snapshot(BACKUP(), true);
108
+ if (!saved.identity || digest(saved.bytes) !== state.originalHash)
109
+ throw new Error('AgyBackupInvalid');
110
+ ensureConfigDirectory();
111
+ const current = snapshot();
112
+ if (digest(current.bytes) !== state.configHash && !(digest(current.bytes) === state.originalHash && (!state.originalAbsent || !current.identity)))
113
+ throw new Error('AgyRecoveryConflict');
114
+ if (state.originalAbsent) {
115
+ if (current.identity) {
116
+ if (!same(current, snapshot()))
117
+ throw new Error('AgyConfigChanged');
118
+ fs.unlinkSync(CONFIG());
119
+ }
120
+ }
121
+ else
122
+ replace(CONFIG(), saved.bytes, state.originalMode, current);
123
+ }
124
+ const fileNames = ['plugin.json', 'mcp_config.json'];
125
+ export function folderSnapshots(folder) {
126
+ const dir = pluginDirectory(folder, true);
127
+ return fileNames.map(name => snapshot(path.join(dir, name)));
128
+ }
129
+ function image(s, index) { return { name: fileNames[index], bytes: s.bytes.toString('base64'), mode: s.mode, absent: !s.identity }; }
130
+ export function configuredManifest(before, owned) {
131
+ if (!isUtf8(before.bytes))
132
+ throw new Error('AgyConfigInvalid');
133
+ let text = before.identity ? before.bytes.toString('utf8') : '{}';
134
+ let parsed = tree(text);
135
+ for (const key of ['name', 'version', 'description'])
136
+ if (property(parsed, key) && !owned)
137
+ throw new Error('AgyConfigCollision');
138
+ for (const [key, value] of Object.entries({ name: 'agentmesh', version: '0.3.7', description: 'AgentMesh tools for this folder' })) {
139
+ text = put(text, parsed, key, value);
140
+ parsed = tree(text);
141
+ }
142
+ return Buffer.from(text);
143
+ }
144
+ function matches(current, before) {
145
+ return !!current.identity !== before.absent && digest(current.bytes) === digest(Buffer.from(before.bytes, 'base64')) && current.mode === before.mode;
146
+ }
147
+ // Precheck BOTH files before restoring either. Never overwrite a foreign edit.
148
+ function restoreImages(folder, images, installed, modes) {
149
+ const dir = pluginDirectory(folder, true), current = folderSnapshots(folder);
150
+ for (let i = 0; i < 2; i++)
151
+ if (!matches(current[i], images[i]) && (!current[i].identity || digest(current[i].bytes) !== installed[i] || current[i].mode !== modes[i]))
152
+ throw new Error('AgyConfigChanged');
153
+ for (let i = 0; i < 2; i++) {
154
+ const before = images[i], now = current[i], file = path.join(dir, before.name);
155
+ if (matches(now, before))
156
+ continue;
157
+ if (before.absent) {
158
+ if (!same(now, snapshot(file)))
159
+ throw new Error('AgyConfigChanged');
160
+ fs.unlinkSync(file);
161
+ }
162
+ else
163
+ replace(file, Buffer.from(before.bytes, 'base64'), before.mode, now);
164
+ }
165
+ const readback = folderSnapshots(folder);
166
+ if (readback.some((s, i) => !matches(s, images[i])))
167
+ throw new Error('AgyConfigChanged');
168
+ }
169
+ export function recoverPublication(state) {
170
+ if (!state.transaction)
171
+ return state;
172
+ try {
173
+ restoreImages(state.folder, state.transaction.before, state.transaction.after, state.transaction.modes);
174
+ }
175
+ catch (error) {
176
+ saveFolder({ ...state, status: 'retired' });
177
+ throw error;
178
+ }
179
+ const next = { ...state };
180
+ delete next.transaction;
181
+ saveFolder(next);
182
+ return next;
183
+ }
184
+ export function publishFolder(state, entry, binding) {
185
+ const dir = pluginDirectory(state.folder, true), before = folderSnapshots(state.folder);
186
+ if (state.installed && before.some((s, i) => !s.identity || digest(s.bytes) !== state.installed[i] || s.mode !== state.installedModes[i]))
187
+ throw new Error('AgyConfigChanged');
188
+ const next = [configuredManifest(before[0], !!state.installed), configured(before[1], entry, !!state.installed)];
189
+ const transaction = { before: before.map(image), after: next.map(digest), modes: before.map(s => s.identity ? s.mode : 0o600) };
190
+ const prepared = { ...state, originals: state.originals ?? transaction.before, transaction };
191
+ saveFolder(prepared);
192
+ try {
193
+ for (let i = 0; i < 2; i++)
194
+ replace(path.join(dir, fileNames[i]), next[i], transaction.modes[i], before[i]);
195
+ if (folderSnapshots(state.folder).some((s, i) => !s.identity || digest(s.bytes) !== transaction.after[i] || s.mode !== transaction.modes[i]))
196
+ throw new Error('AgyConfigChanged');
197
+ const active = { ...prepared, ...binding, installed: transaction.after, installedModes: transaction.modes, status: 'active' };
198
+ delete active.transaction;
199
+ delete active.pending;
200
+ saveFolder(active);
201
+ return active;
202
+ }
203
+ catch (error) {
204
+ recoverPublication(prepared);
205
+ throw error;
206
+ }
207
+ }
208
+ export function restoreFolder(state) {
209
+ if (state.originals && state.installed)
210
+ restoreImages(state.folder, state.originals, state.installed, state.installedModes);
211
+ }
@@ -0,0 +1,185 @@
1
+ import fs from 'node:fs';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { openOAuth, RESOURCE, savedOAuth } from './oauth-client.js';
5
+ import { resourceTarget } from './plugin-target.js';
6
+ import { UUID, locked } from './plugin-storage.js';
7
+ import { agentUUID, digest, canonicalFolder, folderRoot, folderProfile, folderState, saveFolder, folderLifecycle, credentials, agyReason, receivedCredentials } from './agy-storage.js';
8
+ import { configured, configuredManifest, folderSnapshots, publishFolder, restoreFolder, recoverPublication } from './agy-config.js';
9
+ export function principal(result) {
10
+ const r = result;
11
+ if (r?.isError)
12
+ throw new Error('AgyIdentityMismatch');
13
+ let data;
14
+ try {
15
+ data = (r?.structuredContent ?? JSON.parse(r?.content?.find(v => v.type === 'text')?.text ?? '{}'));
16
+ }
17
+ catch {
18
+ throw new Error('AgyIdentityMismatch');
19
+ }
20
+ const p = data?.principal;
21
+ if (p?.kind !== 'agent' || typeof p.id !== 'string' || !UUID.test(p.id) || typeof p.workspace_id !== 'string' || !UUID.test(p.workspace_id))
22
+ throw new Error('AgyIdentityMismatch');
23
+ return { id: p.id.toLowerCase(), workspace_id: p.workspace_id.toLowerCase() };
24
+ }
25
+ export async function agyConnect(args) {
26
+ const options = new Map();
27
+ let remove = false;
28
+ for (let i = 0; i < args.length; i++) {
29
+ const key = args[i];
30
+ if (key === '--workspace')
31
+ throw new Error('AgyWorkspace');
32
+ if (key === '--remove') {
33
+ if (remove)
34
+ throw new Error('AgyArgumentsInvalid');
35
+ remove = true;
36
+ continue;
37
+ }
38
+ if (!['--client', '--agent', '--server'].includes(key) || options.has(key) || !args[i + 1] || args[i + 1].startsWith('--'))
39
+ throw new Error('AgyArgumentsInvalid');
40
+ options.set(key, args[++i]);
41
+ }
42
+ if (options.get('--client') !== 'agy')
43
+ throw new Error('AgyArgumentsInvalid');
44
+ if (remove && options.size !== 1)
45
+ throw new Error('AgyArgumentsInvalid');
46
+ const requested = options.has('--agent') ? agentUUID(options.get('--agent')) : undefined;
47
+ const resource = options.get('--server') ?? RESOURCE;
48
+ resourceTarget(resource);
49
+ const folder = canonicalFolder();
50
+ if (remove) {
51
+ await removeAgy(folder);
52
+ return;
53
+ }
54
+ // A separate Connect lock prevents two browsers creating agents for one folder.
55
+ // Remove and tools use only the lifecycle lock, so approval cannot block them.
56
+ await locked(folderRoot(folder, true), 'connect', async () => {
57
+ const pending = await folderLifecycle(folder, async () => {
58
+ let state = folderState(folder);
59
+ if (state)
60
+ state = recoverPublication(state);
61
+ if (state?.status === 'retired')
62
+ throw new Error('AgyConfigChanged');
63
+ if (!state || state.status === 'removed')
64
+ state = { schema: 1, folder, generation: randomUUID(), status: 'pending' };
65
+ // Validate both files before opening a browser or creating a remote agent.
66
+ const before = folderSnapshots(folder);
67
+ if (state.installed && before.some((s, i) => !s.identity || digest(s.bytes) !== state.installed[i] || s.mode !== state.installedModes[i]))
68
+ throw new Error('AgyConfigChanged');
69
+ configuredManifest(before[0], !!state.installed);
70
+ configured(before[1], {}, !!state.installed);
71
+ const p = state.pending;
72
+ if (p?.phase === 'received') {
73
+ if (resource !== p.resource || requested && requested !== p.requestedAgent)
74
+ throw new Error('AgyApprovalReceived');
75
+ // A durable credential save can precede its phase checkpoint on interruption.
76
+ credentials(folderProfile(folder, p.generation), p.resource);
77
+ return p;
78
+ }
79
+ if (p?.phase === 'exchange') {
80
+ const prior = folderProfile(folder, p.generation);
81
+ if (receivedCredentials(prior, p.resource)) {
82
+ if (resource !== p.resource || requested && requested !== p.requestedAgent)
83
+ throw new Error('AgyApprovalReceived');
84
+ p.phase = 'received';
85
+ saveFolder(state);
86
+ return p;
87
+ }
88
+ if (!requested)
89
+ throw new Error('AgyApprovalUnknown');
90
+ }
91
+ const next = { generation: randomUUID(), resource, requestedAgent: requested, phase: 'approval' };
92
+ state.pending = next;
93
+ saveFolder(state);
94
+ return next;
95
+ });
96
+ const stage = folderProfile(folder, pending.generation, true), abort = new AbortController();
97
+ const cancel = () => abort.abort(new Error('ApprovalCancelled'));
98
+ process.once('SIGINT', cancel);
99
+ process.once('SIGTERM', cancel);
100
+ let oauth, committed = false;
101
+ const phase = async (value) => folderLifecycle(folder, async () => {
102
+ const state = folderState(folder);
103
+ if (!state || state.status === 'retired' || state.status === 'removed' || state.pending?.generation !== pending.generation)
104
+ throw new Error('AgyGenerationChanged');
105
+ state.pending.phase = value;
106
+ saveFolder(state);
107
+ pending.phase = value;
108
+ });
109
+ const publish = async (result) => {
110
+ const identity = principal(result);
111
+ if (pending.requestedAgent && identity.id !== pending.requestedAgent)
112
+ throw new Error('AgyIdentityMismatch');
113
+ await folderLifecycle(folder, async () => {
114
+ const state = folderState(folder);
115
+ if (!state || state.status === 'retired' || state.status === 'removed' || state.pending?.generation !== pending.generation)
116
+ throw new Error('AgyGenerationChanged');
117
+ credentials(stage, resource);
118
+ const entry = { command: fs.realpathSync(process.execPath), args: [fs.realpathSync(fileURLToPath(import.meta.url.replace(/agy-connect\.js$/, 'index.js'))), 'agy-stdio', '--folder', folder], disabled: false };
119
+ publishFolder(state, entry, { generation: pending.generation, agentId: identity.id, resource });
120
+ committed = true;
121
+ });
122
+ process.stdout.write(`AgentMesh agent ${identity.id} connected for agy.\nFolder: ${folder}\nStart agy here: cd '${folder.replace(/'/g, "'\\''")}' && agy\n`);
123
+ try {
124
+ oauth?.complete({ agentId: identity.id, workspaceId: identity.workspace_id });
125
+ }
126
+ catch {
127
+ process.stderr.write('The connection is saved. Browser completion could not be opened; use the start command above.\n');
128
+ }
129
+ };
130
+ try {
131
+ if (pending.phase === 'received')
132
+ await savedOAuth(stage, async (client) => publish(await client.callTool({ name: 'whoami', arguments: {} }, undefined, { signal: abort.signal })), resource);
133
+ else {
134
+ oauth = await openOAuth(stage, requested, resource, true, { signal: abort.signal, onExchange: () => phase('exchange'), onTokens: () => phase('received') });
135
+ await publish(await oauth.client.callTool({ name: 'whoami', arguments: {} }, undefined, { signal: abort.signal }));
136
+ }
137
+ }
138
+ catch (error) {
139
+ if (committed)
140
+ return;
141
+ const reason = abort.signal.aborted ? 'ApprovalCancelled' : agyReason(error, 'AgyApprovalFailed');
142
+ if (reason === 'AgyIdentityMismatch')
143
+ await folderLifecycle(folder, async () => {
144
+ const state = folderState(folder);
145
+ if (state?.pending?.generation === pending.generation) {
146
+ delete state.pending;
147
+ saveFolder(state);
148
+ }
149
+ });
150
+ if (['AgyGenerationChanged', 'AgyIdentityMismatch', 'AgyConfigChanged', 'AgyConfigInvalid', 'AgyUnsafeState'].includes(reason))
151
+ throw new Error(reason);
152
+ if (pending.phase === 'exchange')
153
+ throw new Error('AgyApprovalUnknown');
154
+ if (pending.phase === 'received') {
155
+ if (error instanceof Error && (['InvalidGrantError', 'InvalidClientError'].includes(error.constructor.name) || error.message === 'ReconnectRequired'))
156
+ throw new Error('ReconnectRequired');
157
+ throw new Error('AgyApprovalReceived');
158
+ }
159
+ throw new Error(reason);
160
+ }
161
+ finally {
162
+ process.removeListener('SIGINT', cancel);
163
+ process.removeListener('SIGTERM', cancel);
164
+ await oauth?.close().catch(() => undefined);
165
+ // Retain received or unknown approval privately for recovery. Never erase an
166
+ // active profile or the only evidence of a possibly committed redemption.
167
+ }
168
+ });
169
+ }
170
+ export async function removeAgy(folder = canonicalFolder()) {
171
+ await folderLifecycle(folder, async () => {
172
+ let state = folderState(folder);
173
+ if (!state || state.status === 'removed')
174
+ return;
175
+ if (state.transaction)
176
+ state = recoverPublication(state);
177
+ state = { ...state, status: 'retired' };
178
+ saveFolder(state);
179
+ restoreFolder(state);
180
+ const removed = { ...state, status: 'removed' };
181
+ delete removed.pending;
182
+ saveFolder(removed);
183
+ });
184
+ process.stdout.write('AgentMesh connection removed from this folder; original plugin files restored.\n');
185
+ }
@@ -0,0 +1,135 @@
1
+ import fs from 'node:fs';
2
+ import { serveStdio } from '@modelcontextprotocol/server/stdio';
3
+ import { buildServer } from './server.js';
4
+ import { MCP_INSTRUCTIONS } from './contract.js';
5
+ import { HOSTED_TOOL_NAMES } from './schemas.js';
6
+ import { savedOAuth } from './oauth-client.js';
7
+ import { agentUUID, root, lifecycle, install, enrollment, profile, credentials, canonicalFolder, pluginDirectory, folderState, folderProfile, folderLifecycle, agyReason, agyMessages, digest } from './agy-storage.js';
8
+ import { folderSnapshots } from './agy-config.js';
9
+ import { principal } from './agy-connect.js';
10
+ import { terminalDiagnostic } from './terminal-diagnostic.js';
11
+ function failure(cause, agent) {
12
+ const remedy = `Run connect --client agy --agent ${agent} again.`;
13
+ const messages = {
14
+ AgyMissingSelection: "AgentMesh agent is not selected. Set AGENTMESH_AGENT=<agent UUID> in this seat's agy launch command, then run connect --client agy --agent <agent UUID> again.",
15
+ AgyInvalidSelection: "AgentMesh agent selection is invalid. Set AGENTMESH_AGENT to a UUID in this seat's agy launch command, then run connect --client agy --agent <agent UUID> again.",
16
+ AgyNotConnected: `AgentMesh agent ${agent} is not connected. ${remedy}`,
17
+ AgyDisconnected: `AgentMesh agent ${agent} is disconnected. ${remedy}`,
18
+ AgyUnsafeState: `AgentMesh agent ${agent} has unsafe or invalid local credentials. Repair owner-only local files, then run connect --client agy --agent ${agent} again.`,
19
+ ReconnectRequired: `AgentMesh approval for agent ${agent} expired or was revoked. ${remedy}`,
20
+ AgyUnavailable: `AgentMesh is unavailable for agent ${agent}. Check the connection, then run connect --client agy --agent ${agent} again.`,
21
+ AgyIdentityMismatch: `AgentMesh identity for agent ${agent} did not match. ${remedy}`,
22
+ };
23
+ return { isError: true, content: [{ type: 'text', text: messages[cause] ?? messages.AgyUnsafeState }] };
24
+ }
25
+ export async function agyCall(name, args, signal) {
26
+ let agent, cause = 'AgyUnsafeState';
27
+ try {
28
+ const selected = process.env.AGENTMESH_AGENT;
29
+ if (!selected)
30
+ throw new Error('AgyMissingSelection');
31
+ agent = agentUUID(selected);
32
+ root();
33
+ return await lifecycle(async () => {
34
+ const state = install();
35
+ if (!state)
36
+ throw new Error('AgyNotConnected');
37
+ if (state.status === 'retired' || state.status === 'removed')
38
+ throw new Error('AgyDisconnected');
39
+ if (state.status !== 'active')
40
+ throw new Error('AgyNotConnected');
41
+ const e = enrollment(agent);
42
+ if (!e)
43
+ throw new Error('AgyNotConnected');
44
+ if (e.generation !== state.generation)
45
+ throw new Error('AgyDisconnected');
46
+ const dir = profile(agent, e.resource);
47
+ credentials(dir, e.resource);
48
+ cause = 'AgyUnavailable';
49
+ return await savedOAuth(dir, async (client) => {
50
+ const proof = await client.callTool({ name: 'whoami', arguments: {} }, undefined, { signal });
51
+ const identity = principal(proof);
52
+ if (identity.id !== agent || identity.workspace_id !== e.workspaceId)
53
+ throw new Error('AgyIdentityMismatch');
54
+ return name === 'whoami' ? proof : await client.callTool({ name, arguments: args }, undefined, { signal });
55
+ }, e.resource);
56
+ });
57
+ }
58
+ catch (error) {
59
+ const code = error instanceof Error ? error.message : '';
60
+ if (error instanceof Error && ['InvalidGrantError', 'InvalidClientError', 'UnauthorizedError'].includes(error.constructor.name))
61
+ cause = 'ReconnectRequired';
62
+ if (['AgyMissingSelection', 'AgyInvalidSelection', 'AgyNotConnected', 'AgyDisconnected', 'AgyIdentityMismatch', 'ReconnectRequired'].includes(code))
63
+ cause = code;
64
+ else if (error instanceof SyntaxError || ['AgyUnsafeState', 'OwnerCredentialsRequired', 'PrivateFileRequired', 'OwnerDirectoryRequired', 'UnapprovedResource', 'ResourceMismatch'].includes(code))
65
+ cause = 'AgyUnsafeState';
66
+ process.stderr.write(`AgentMesh ${cause}; ${terminalDiagnostic(error, 'agy-proxy.js', 'agyCall')}.\n`);
67
+ return failure(cause, agent);
68
+ }
69
+ }
70
+ // Capture once, before serving initialize. A preopened process never learns a
71
+ // replacement UUID/generation from a later Connect.
72
+ function folderDispatch(args) {
73
+ let binding, startError;
74
+ try {
75
+ if (args.length !== 2 || args[0] !== '--folder' || !args[1])
76
+ throw new Error('AgyNotConnected');
77
+ const folder = canonicalFolder(args[1]);
78
+ if (folder !== args[1] || fs.realpathSync(process.cwd()) !== pluginDirectory(folder))
79
+ throw new Error('AgyNotConnected');
80
+ const state = folderState(folder);
81
+ if (!state || state.status !== 'active' || !state.agentId || !state.resource)
82
+ throw new Error('AgyNotConnected');
83
+ binding = { folder, generation: state.generation, agentId: state.agentId, resource: state.resource };
84
+ }
85
+ catch (error) {
86
+ startError = error;
87
+ }
88
+ return async (name, args, signal) => {
89
+ let cause = 'AgyUnsafeState';
90
+ try {
91
+ if (!binding)
92
+ throw startError;
93
+ const captured = binding;
94
+ return await folderLifecycle(captured.folder, async () => {
95
+ if (fs.realpathSync(process.cwd()) !== pluginDirectory(captured.folder))
96
+ throw new Error('AgyNotConnected');
97
+ const state = folderState(captured.folder);
98
+ if (!state || state.status !== 'active' || state.generation !== captured.generation || state.agentId !== captured.agentId || state.resource !== captured.resource || state.transaction)
99
+ throw new Error('AgyGenerationChanged');
100
+ if (folderSnapshots(captured.folder).some((s, i) => !s.identity || digest(s.bytes) !== state.installed?.[i] || s.mode !== state.installedModes?.[i]))
101
+ throw new Error('AgyConfigChanged');
102
+ const dir = folderProfile(captured.folder, captured.generation);
103
+ credentials(dir, captured.resource);
104
+ cause = 'AgyUnavailable';
105
+ return await savedOAuth(dir, async (client) => {
106
+ const proof = await client.callTool({ name: 'whoami', arguments: {} }, undefined, { signal });
107
+ let id;
108
+ try {
109
+ id = principal(proof).id;
110
+ }
111
+ catch {
112
+ throw new Error('AgyRuntimeIdentity');
113
+ }
114
+ if (id !== captured.agentId)
115
+ throw new Error('AgyRuntimeIdentity');
116
+ return name === 'whoami' ? proof : await client.callTool({ name, arguments: args }, undefined, { signal });
117
+ }, captured.resource);
118
+ });
119
+ }
120
+ catch (error) {
121
+ if (error instanceof Error && ['InvalidGrantError', 'InvalidClientError', 'UnauthorizedError'].includes(error.constructor.name))
122
+ cause = 'ReconnectRequired';
123
+ else
124
+ cause = agyReason(error, cause);
125
+ process.stderr.write(`AgentMesh ${cause}; ${terminalDiagnostic(error, 'agy-proxy.js', 'folderCall')}.\n`);
126
+ return { isError: true, content: [{ type: 'text', text: agyMessages[cause] }] };
127
+ }
128
+ };
129
+ }
130
+ export function agyProxy(args = process.argv.slice(3)) {
131
+ const dispatch = args.length ? folderDispatch(args) : agyCall;
132
+ serveStdio(() => buildServer({ instructions: MCP_INSTRUCTIONS, allowedTools: HOSTED_TOOL_NAMES.filter(name => !name.startsWith('terminal_wake_')), dispatch }), {
133
+ onerror: error => process.stderr.write(`AgentMesh stdio unavailable; ${terminalDiagnostic(error, 'agy-proxy.js', 'agyProxy')}.\n`)
134
+ });
135
+ }