@agentmesh-md/mcp-server 0.3.6 → 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.6 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.6.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.6`. 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.6.zip,agentmesh-0.3.6.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.6.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.6 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
@@ -260,42 +260,53 @@ The hosted backend, SPA command and npm release must update in the same install.
260
260
 
261
261
  ## Antigravity (agy) Connect
262
262
 
263
- Use the installed CLI for each seat, approving that seat's AgentMesh identity in
264
- its browser sign-in:
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>`.
265
267
 
266
268
  ```sh
267
- agentmesh-mcp connect --client agy --agent <agent-UUID> --workspace <workspace-UUID>
268
- env AGENTMESH_AGENT=<agent-UUID> agy <existing-seat-arguments>
269
+ cd /path/to/your/folder
270
+ agentmesh-mcp connect --client agy
271
+ agy
269
272
  ```
270
273
 
271
- The workspace flag is optional. Each seat must set its own `AGENTMESH_AGENT` in
272
- its launch environment. This selects an OAuth enrollment under the shared OS
273
- account; it is not an OS-user isolation boundary. No API key is needed.
274
-
275
- Connect adds one `agentmesh-connect` stdio entry to
276
- `~/.gemini/config/mcp_config.json`. It uses absolute Node and installed package
277
- paths, so keep that installation in place. Other entries retain their original
278
- bytes. The first Connect saves the raw original file and mode once under
279
- `~/.agentmesh/agy/mcp_config.before.json`; subsequent seats reuse that backup.
280
- Per-agent credentials and enrollments live under `~/.agentmesh/agy` with 0600
281
- files and 0700 directories. Native Claude/Codex enrollments are separate.
282
-
283
- The bridge checks the selected agent and workspace before forwarding each tool
284
- call. Missing, invalid or unconnected selectors return an MCP error without
285
- falling back to another seat or an API key. Approval failures name the selected
286
- agent and the Connect command to run again. Existing agy wake behavior remains
287
- in use; the bridge does not expose native `terminal_wake_*` tools.
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.
288
293
 
289
294
  ```sh
290
295
  agentmesh-mcp connect --client agy --remove
291
296
  ```
292
297
 
293
- Remove disconnects **all agy enrollments on this machine**, including running
294
- bridge processes, and restores the original config bytes/mode or absence. If
295
- someone edited the shared file since Connect, removal refuses to overwrite the
296
- edit, retains the backup, and denies agy access until resolved. Preserve the edit,
297
- resolve the conflict, and rerun removal before connecting again.
298
-
299
- agy accepts `--agent`, `--workspace` and an existing allowlisted MCP URL via
300
- `--server`; native `--disconnect`, `--pin-session` and `--marketplace` flags do
301
- not apply. `--remove` cannot be combined with enrollment options.
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.
@@ -4,7 +4,7 @@ import os from 'node:os';
4
4
  import { randomUUID } from 'node:crypto';
5
5
  import { isUtf8 } from 'node:buffer';
6
6
  import { parseTree } from 'jsonc-parser';
7
- import { digest, directory, lstat, root } from './agy-storage.js';
7
+ import { digest, directory, lstat, root, pluginDirectory, saveFolder } from './agy-storage.js';
8
8
  export const CONFIG = () => path.join(os.homedir(), '.gemini', 'config', 'mcp_config.json');
9
9
  export const BACKUP = () => path.join(root(), 'mcp_config.before.json');
10
10
  function identity(s) { return [s.dev, s.ino, s.ctimeMs, s.mtimeMs, s.size, s.mode].join(':'); }
@@ -45,7 +45,7 @@ export function replace(file, bytes, mode, before) {
45
45
  fs.rmSync(temporary, { force: true });
46
46
  }
47
47
  }
48
- function tree(text) {
48
+ export function tree(text) {
49
49
  const errors = [];
50
50
  const value = parseTree(text, errors, { allowTrailingComma: false, disallowComments: true, allowEmptyContent: false });
51
51
  if (errors.length || value?.type !== 'object')
@@ -121,3 +121,91 @@ export function restore(state) {
121
121
  else
122
122
  replace(CONFIG(), saved.bytes, state.originalMode, current);
123
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
+ }
@@ -1,12 +1,11 @@
1
1
  import fs from 'node:fs';
2
- import path from 'node:path';
2
+ import { randomUUID } from 'node:crypto';
3
3
  import { fileURLToPath } from 'node:url';
4
- import { openOAuth, RESOURCE, credentialFile } from './oauth-client.js';
4
+ import { openOAuth, RESOURCE, savedOAuth } from './oauth-client.js';
5
5
  import { resourceTarget } from './plugin-target.js';
6
- import { UUID } from './plugin-storage.js';
7
- import { writeAtomic } from './wake-storage.js';
8
- import { readPrivate, agentUUID, root, profile, lifecycle, install, saveInstall, freshInstall, saveEnrollment, digest } from './agy-storage.js';
9
- import { snapshot, configured, backup, replace, ensureConfigDirectory, CONFIG, BACKUP, restore } from './agy-config.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';
10
9
  export function principal(result) {
11
10
  const r = result;
12
11
  if (r?.isError)
@@ -28,105 +27,159 @@ export async function agyConnect(args) {
28
27
  let remove = false;
29
28
  for (let i = 0; i < args.length; i++) {
30
29
  const key = args[i];
30
+ if (key === '--workspace')
31
+ throw new Error('AgyWorkspace');
31
32
  if (key === '--remove') {
32
33
  if (remove)
33
34
  throw new Error('AgyArgumentsInvalid');
34
35
  remove = true;
35
36
  continue;
36
37
  }
37
- if (!['--client', '--agent', '--workspace', '--server'].includes(key) || options.has(key) || !args[i + 1] || args[i + 1].startsWith('--'))
38
+ if (!['--client', '--agent', '--server'].includes(key) || options.has(key) || !args[i + 1] || args[i + 1].startsWith('--'))
38
39
  throw new Error('AgyArgumentsInvalid');
39
40
  options.set(key, args[++i]);
40
41
  }
41
42
  if (options.get('--client') !== 'agy')
42
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();
43
50
  if (remove) {
44
- if (options.size !== 1)
45
- throw new Error('AgyArgumentsInvalid');
46
- await removeAgy();
51
+ await removeAgy(folder);
47
52
  return;
48
53
  }
49
- const agent = agentUUID(options.get('--agent') ?? ''), workspace = options.has('--workspace') ? agentUUID(options.get('--workspace')) : undefined;
50
- const resource = options.get('--server') ?? RESOURCE;
51
- resourceTarget(resource);
52
- const generation = await lifecycle(async () => {
53
- let state = install();
54
- if (state?.status === 'retired')
55
- throw new Error('AgyRecoveryConflict');
56
- if (!state || state.status === 'removed') {
57
- state = freshInstall();
58
- saveInstall(state);
59
- }
60
- return state.generation;
61
- });
62
- // OAuth approval is outside the shared lock. Stage credentials separately so
63
- // interrupted/incorrect approval never replaces an already-working profile.
64
- const stage = fs.mkdtempSync(path.join(root(), 'approval-'));
65
- fs.chmodSync(stage, 0o700);
66
- try {
67
- try {
68
- readPrivate(path.join(profile(agent, resource), 'credentials.json'));
69
- }
70
- catch (error) {
71
- if (!(error instanceof Error && error.message === 'AgyNotConnected'))
72
- throw error;
73
- }
74
- // Never copy an active refresh grant outside its profile lock. A fresh
75
- // staged approval leaves active bridge refreshes independent until commit.
76
- const oauth = await openOAuth(stage, agent, resource, true);
77
- try {
78
- const identity = principal(await oauth.client.callTool({ name: 'whoami', arguments: {} }));
79
- if (identity.id !== agent || workspace && workspace !== identity.workspace_id)
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)
80
112
  throw new Error('AgyIdentityMismatch');
81
- await lifecycle(async () => {
82
- let state = install();
83
- if (!state || state.generation !== generation || !['active', 'pending'].includes(state.status))
113
+ await folderLifecycle(folder, async () => {
114
+ const state = folderState(folder);
115
+ if (!state || state.status === 'retired' || state.status === 'removed' || state.pending?.generation !== pending.generation)
84
116
  throw new Error('AgyGenerationChanged');
85
- ensureConfigDirectory();
86
- const before = snapshot();
87
- if (state.configHash && digest(before.bytes) !== state.configHash && !(state.status === 'pending' && digest(before.bytes) === state.originalHash))
88
- throw new Error('AgyConfigChanged');
89
- const entry = { command: fs.realpathSync(process.execPath), args: [fs.realpathSync(fileURLToPath(import.meta.url.replace(/agy-connect\.js$/, 'index.js'))), 'agy-stdio'], disabled: false };
90
- const next = configured(before, entry, state.configHash !== undefined);
91
- state = backup(before, state);
92
- state = { ...state, configHash: digest(next) };
93
- saveInstall(state);
94
- replace(CONFIG(), next, before.mode, before);
95
- const target = profile(agent, resource, true), credentials = credentialFile(path.join(stage, 'credentials.json'), resource);
96
- if (!credentials?.tokens)
97
- throw new Error('AgyUnsafeState');
98
- readPrivate(path.join(target, 'credentials.json'));
99
- writeAtomic(path.join(target, 'credentials.json'), credentials);
100
- saveEnrollment({ schema: 1, generation, agentId: agent, workspaceId: identity.workspace_id, resource });
101
- if (digest(snapshot().bytes) !== state.configHash)
102
- throw new Error('AgyConfigChanged');
103
- saveInstall({ ...state, status: 'active' });
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;
104
121
  });
105
- oauth.complete({ agentId: identity.id, workspaceId: identity.workspace_id });
106
- process.stdout.write(`AgentMesh agent ${agent} connected for agy. Set AGENTMESH_AGENT=${agent} in this seat's agy launch command.\n`);
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);
107
160
  }
108
161
  finally {
109
- await oauth.close();
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.
110
167
  }
111
- }
112
- finally {
113
- fs.rmSync(stage, { recursive: true, force: true });
114
- }
168
+ });
115
169
  }
116
- export async function removeAgy() {
117
- await lifecycle(async () => {
118
- const state = install();
170
+ export async function removeAgy(folder = canonicalFolder()) {
171
+ await folderLifecycle(folder, async () => {
172
+ let state = folderState(folder);
119
173
  if (!state || state.status === 'removed')
120
174
  return;
121
- // Deny first, including on a restoration conflict. Calls and remove share
122
- // this lock, so success cannot race an authenticated in-flight request.
123
- const retired = { ...state, status: 'retired' };
124
- saveInstall(retired);
125
- restore(retired);
126
- for (const name of ['agents', 'enrollments'])
127
- fs.rmSync(path.join(root(), name), { recursive: true, force: true });
128
- fs.rmSync(BACKUP(), { force: true });
129
- saveInstall({ ...retired, status: 'removed' });
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);
130
183
  });
131
- process.stdout.write('AgentMesh agy connections removed; original shared config restored.\n');
184
+ process.stdout.write('AgentMesh connection removed from this folder; original plugin files restored.\n');
132
185
  }
package/dist/agy-proxy.js CHANGED
@@ -1,9 +1,11 @@
1
+ import fs from 'node:fs';
1
2
  import { serveStdio } from '@modelcontextprotocol/server/stdio';
2
3
  import { buildServer } from './server.js';
3
4
  import { MCP_INSTRUCTIONS } from './contract.js';
4
5
  import { HOSTED_TOOL_NAMES } from './schemas.js';
5
6
  import { savedOAuth } from './oauth-client.js';
6
- import { agentUUID, root, lifecycle, install, enrollment, profile, credentials } from './agy-storage.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';
7
9
  import { principal } from './agy-connect.js';
8
10
  import { terminalDiagnostic } from './terminal-diagnostic.js';
9
11
  function failure(cause, agent) {
@@ -65,8 +67,69 @@ export async function agyCall(name, args, signal) {
65
67
  return failure(cause, agent);
66
68
  }
67
69
  }
68
- export function agyProxy() {
69
- serveStdio(() => buildServer({ instructions: MCP_INSTRUCTIONS, allowedTools: HOSTED_TOOL_NAMES.filter(name => !name.startsWith('terminal_wake_')), dispatch: agyCall }), {
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 }), {
70
133
  onerror: error => process.stderr.write(`AgentMesh stdio unavailable; ${terminalDiagnostic(error, 'agy-proxy.js', 'agyProxy')}.\n`)
71
134
  });
72
135
  }