@agentmesh-md/mcp-server 0.3.6 → 0.3.8

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.8 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.8.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.8`. 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.8.zip,agentmesh-0.3.8.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.8.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.8 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,64 @@ 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 `.agents/plugins/agentmesh/{plugin.json,mcp_config.json,hooks.json}`
275
+ 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 and installation revision 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. The selected agent and workspace are
285
+ verified before each call. agy Connect rejects `--workspace`. To change the
286
+ selection, remove this folder connection and connect again.
287
+
288
+ After starting agy, send your first message and normally approve the AgentMesh
289
+ startup command. Until then Roster shows Wakes Off. The own-host daemon uses
290
+ the public agentapi command to wake this same conversation; On requires both
291
+ transport and the model reading and completing a wake. Missing host context or
292
+ unconfirmed delivery leaves wakes Off. Only the bound native conversation can
293
+ use `terminal_wake_read` and `terminal_wake_complete`; other wake tools remain
294
+ private to the daemon. Ordinary tools remain available before startup.
295
+
296
+ To upgrade an existing 037 folder, run the new Connect command in that folder,
297
+ restart agy, and approve startup on the first message. Connect reuses the saved
298
+ agent and OAuth profile without another browser approval or agent creation.
299
+
300
+ If approval completed but local setup failed, rerun Connect in the same folder
301
+ to finish the saved approval. If the result of code redemption was not received,
302
+ check the agentmesh.md roster and reconnect using `--agent <existing-agent-UUID>`;
303
+ do not create another agent. Local removal does not delete a remote agent.
288
304
 
289
305
  ```sh
290
306
  agentmesh-mcp connect --client agy --remove
291
307
  ```
292
308
 
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.
309
+ Removal drains an active call, retires this folder's binding, and restores all three
310
+ original plugin files, including their modes or absence. It preserves other
311
+ folders, native Claude/Codex enrollments and the legacy global configuration.
312
+ A foreign edit is preserved and reported as a conflict; resolve it before retrying
313
+ removal. Already-open bridges cannot adopt a replacement identity; start agy again
314
+ after reconnecting.
315
+
316
+ The preserved 0.3.6 global entry still follows its explicit `AGENTMESH_AGENT`
317
+ selection. With that variable unset it makes no authenticated calls; setting it
318
+ is an explicit legacy choice that can load that old identity beside a folder
319
+ plugin. New folder Connect and removal never edit or migrate that global state.
320
+
321
+ agy accepts optional `--agent` and an existing allowlisted MCP URL via `--server`.
322
+ Native `--disconnect`, `--pin-session` and `--marketplace` flags do not apply.
323
+ `--remove` cannot be combined with enrollment options.
@@ -1,14 +1,11 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
- import os from 'node:os';
4
3
  import { randomUUID } from 'node:crypto';
5
4
  import { isUtf8 } from 'node:buffer';
6
5
  import { parseTree } from 'jsonc-parser';
7
- import { digest, directory, lstat, root } 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');
6
+ import { digest, lstat, pluginDirectory, saveFolder } from './agy-storage.js';
10
7
  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) {
8
+ export function snapshot(file, privateFile = false) {
12
9
  const s = lstat(file);
13
10
  if (!s)
14
11
  return { bytes: Buffer.alloc(0), mode: 0o600 };
@@ -45,7 +42,7 @@ export function replace(file, bytes, mode, before) {
45
42
  fs.rmSync(temporary, { force: true });
46
43
  }
47
44
  }
48
- function tree(text) {
45
+ export function tree(text) {
49
46
  const errors = [];
50
47
  const value = parseTree(text, errors, { allowTrailingComma: false, disallowComments: true, allowEmptyContent: false });
51
48
  if (errors.length || value?.type !== 'object')
@@ -81,43 +78,99 @@ export function configured(before, entry, owned) {
81
78
  throw new Error('AgyConfigCollision');
82
79
  return Buffer.from(servers ? put(text, servers, 'agentmesh-connect', entry) : put(text, parsed, 'mcpServers', { 'agentmesh-connect': entry }));
83
80
  }
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;
81
+ const fileNames = ['plugin.json', 'mcp_config.json', 'hooks.json'];
82
+ export function folderSnapshots(folder) {
83
+ const dir = pluginDirectory(folder, true);
84
+ return fileNames.map(name => snapshot(path.join(dir, name)));
85
+ }
86
+ function image(s, index) { return { name: fileNames[index], bytes: s.bytes.toString('base64'), mode: s.mode, absent: !s.identity }; }
87
+ export function configuredManifest(before, owned) {
88
+ if (!isUtf8(before.bytes))
89
+ throw new Error('AgyConfigInvalid');
90
+ let text = before.identity ? before.bytes.toString('utf8') : '{}';
91
+ let parsed = tree(text);
92
+ for (const key of ['name', 'version', 'description'])
93
+ if (property(parsed, key) && !owned)
94
+ throw new Error('AgyConfigCollision');
95
+ for (const [key, value] of Object.entries({ name: 'agentmesh', version: '0.3.8', description: 'AgentMesh tools for this folder' })) {
96
+ text = put(text, parsed, key, value);
97
+ parsed = tree(text);
91
98
  }
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);
99
+ return Buffer.from(text);
100
+ }
101
+ function matches(current, before) {
102
+ return !!current.identity !== before.absent && digest(current.bytes) === digest(Buffer.from(before.bytes, 'base64')) && current.mode === before.mode;
103
+ }
104
+ // Precheck every owned file before restoring any. Preserve foreign edits.
105
+ function restoreImages(folder, images, installed, modes) {
106
+ const dir = pluginDirectory(folder, true), current = folderSnapshots(folder);
107
+ for (let i = 0; i < images.length; i++)
108
+ if (!matches(current[i], images[i]) && (!current[i].identity || digest(current[i].bytes) !== installed[i] || current[i].mode !== modes[i]))
109
+ throw new Error('AgyConfigChanged');
110
+ for (let i = 0; i < images.length; i++) {
111
+ const before = images[i], now = current[i], file = path.join(dir, before.name);
112
+ if (matches(now, before))
113
+ continue;
114
+ if (before.absent) {
115
+ if (!same(now, snapshot(file)))
116
+ throw new Error('AgyConfigChanged');
117
+ fs.unlinkSync(file);
118
+ }
119
+ else
120
+ replace(file, Buffer.from(before.bytes, 'base64'), before.mode, now);
121
+ }
122
+ const readback = folderSnapshots(folder);
123
+ if (images.some((img, i) => !matches(readback[i], img)))
124
+ throw new Error('AgyConfigChanged');
125
+ }
126
+ export function recoverPublication(state) {
127
+ if (!state.transaction)
128
+ return state;
95
129
  try {
96
- fs.writeFileSync(fd, before.bytes);
97
- fs.fsyncSync(fd);
130
+ restoreImages(state.folder, state.transaction.before, state.transaction.after, state.transaction.modes);
98
131
  }
99
- finally {
100
- fs.closeSync(fd);
132
+ catch (error) {
133
+ saveFolder({ ...state, status: 'retired' });
134
+ throw error;
101
135
  }
102
- return { ...state, originalAbsent: !before.identity, originalMode: before.mode, originalHash: digest(before.bytes) };
136
+ const next = { ...state };
137
+ delete next.transaction;
138
+ saveFolder(next);
139
+ return next;
103
140
  }
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
- }
141
+ export function publishFolder(state, entry, binding, hook) {
142
+ const dir = pluginDirectory(state.folder, true), before = folderSnapshots(state.folder);
143
+ if (state.installed && state.installed.some((hash, i) => !before[i].identity || digest(before[i].bytes) !== hash || before[i].mode !== state.installedModes[i]))
144
+ throw new Error('AgyConfigChanged');
145
+ const next = [configuredManifest(before[0], !!state.installed), configured(before[1], entry, !!state.installed), configuredHooks(before[2], hook, state.installed?.length === 3)];
146
+ const transaction = { before: before.map(image), after: next.map(digest), modes: before.map(s => s.identity ? s.mode : 0o600) };
147
+ const prepared = { ...state, transaction };
148
+ saveFolder(prepared);
149
+ try {
150
+ for (let i = 0; i < next.length; i++)
151
+ replace(path.join(dir, fileNames[i]), next[i], transaction.modes[i], before[i]);
152
+ if (folderSnapshots(state.folder).some((s, i) => !s.identity || digest(s.bytes) !== transaction.after[i] || s.mode !== transaction.modes[i]))
153
+ throw new Error('AgyConfigChanged');
154
+ const active = { ...prepared, ...binding, originals: state.originals?.length === 2 ? [...state.originals, transaction.before[2]] : state.originals ?? transaction.before, installed: transaction.after, installedModes: transaction.modes, status: 'active', hintPending: true };
155
+ delete active.transaction;
156
+ delete active.pending;
157
+ saveFolder(active);
158
+ return active;
120
159
  }
121
- else
122
- replace(CONFIG(), saved.bytes, state.originalMode, current);
160
+ catch (error) {
161
+ recoverPublication(prepared);
162
+ throw error;
163
+ }
164
+ }
165
+ export function restoreFolder(state) {
166
+ if (state.originals && state.installed)
167
+ restoreImages(state.folder, state.originals, state.installed, state.installedModes);
168
+ }
169
+ export function configuredHooks(before, entry, owned = false) {
170
+ if (!isUtf8(before.bytes))
171
+ throw new Error('AgyConfigInvalid');
172
+ const text = before.identity ? before.bytes.toString('utf8') : '{}', parsed = tree(text);
173
+ if (property(parsed, 'agentmesh-wakes') && !owned)
174
+ throw new Error('AgyConfigCollision');
175
+ return Buffer.from(put(text, parsed, 'agentmesh-wakes', entry));
123
176
  }
@@ -1,12 +1,37 @@
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, configuredHooks, folderSnapshots, publishFolder, restoreFolder, recoverPublication } from './agy-config.js';
9
+ import { hookEntry } from './agy-hooks.js';
10
+ function connected(folder, id) {
11
+ process.stdout.write(`AgentMesh agent ${id} connected for agy.\nFolder: ${folder}\nStart agy here: cd '${folder.replace(/'/g, "'\\''")}' && agy\nSend your first message and approve the AgentMesh startup command to turn wakes on.\n`);
12
+ }
13
+ function verifyInstalled(state) {
14
+ const before = folderSnapshots(state.folder);
15
+ if (state.installed?.some((hash, i) => !before[i].identity || digest(before[i].bytes) !== hash || before[i].mode !== state.installedModes[i]))
16
+ throw new Error('AgyConfigChanged');
17
+ }
18
+ function installFolder(state, identity, resource, generation = state.generation) {
19
+ const node = fs.realpathSync(process.execPath), entrypoint = fs.realpathSync(fileURLToPath(import.meta.url.replace(/agy-connect\.js$/, 'index.js'))), revision = randomUUID();
20
+ const entry = { command: node, args: [entrypoint, 'agy-stdio', '--folder', state.folder], disabled: false };
21
+ return publishFolder(state, entry, { generation, agentId: identity.id, workspaceId: identity.workspace_id, resource, revision }, hookEntry(node, entrypoint, state.folder, revision));
22
+ }
23
+ async function registerHint(client, state) {
24
+ try {
25
+ const result = await client.callTool({ name: 'terminal_wake_pin', arguments: { folder_id: digest(state.folder), installed_client: 'agy' } });
26
+ const data = result.structuredContent ?? JSON.parse(result.content?.find((v) => v.type === 'text')?.text ?? '{}');
27
+ if (result.isError || data.saved !== true)
28
+ throw new Error('AgyHintPending');
29
+ saveFolder({ ...state, hintPending: false });
30
+ }
31
+ catch {
32
+ throw new Error('AgyHintPending');
33
+ }
34
+ }
10
35
  export function principal(result) {
11
36
  const r = result;
12
37
  if (r?.isError)
@@ -28,105 +53,190 @@ export async function agyConnect(args) {
28
53
  let remove = false;
29
54
  for (let i = 0; i < args.length; i++) {
30
55
  const key = args[i];
56
+ if (key === '--workspace')
57
+ throw new Error('AgyWorkspace');
31
58
  if (key === '--remove') {
32
59
  if (remove)
33
60
  throw new Error('AgyArgumentsInvalid');
34
61
  remove = true;
35
62
  continue;
36
63
  }
37
- if (!['--client', '--agent', '--workspace', '--server'].includes(key) || options.has(key) || !args[i + 1] || args[i + 1].startsWith('--'))
64
+ if (!['--client', '--agent', '--server'].includes(key) || options.has(key) || !args[i + 1] || args[i + 1].startsWith('--'))
38
65
  throw new Error('AgyArgumentsInvalid');
39
66
  options.set(key, args[++i]);
40
67
  }
41
68
  if (options.get('--client') !== 'agy')
42
69
  throw new Error('AgyArgumentsInvalid');
70
+ if (remove && options.size !== 1)
71
+ throw new Error('AgyArgumentsInvalid');
72
+ const requested = options.has('--agent') ? agentUUID(options.get('--agent')) : undefined;
73
+ const resource = options.get('--server') ?? RESOURCE;
74
+ resourceTarget(resource);
75
+ const folder = canonicalFolder();
43
76
  if (remove) {
44
- if (options.size !== 1)
45
- throw new Error('AgyArgumentsInvalid');
46
- await removeAgy();
77
+ await removeAgy(folder);
47
78
  return;
48
79
  }
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 {
80
+ // A separate Connect lock prevents two browsers creating agents for one folder.
81
+ // Remove and tools use only the lifecycle lock, so approval cannot block them.
82
+ await locked(folderRoot(folder, true), 'connect', async () => {
83
+ // An installed folder keeps its credential generation and selection. Only
84
+ // the installation revision changes; no consent/agent creation on upgrade.
85
+ const upgraded = await folderLifecycle(folder, async () => {
86
+ let state = folderState(folder);
87
+ if (state)
88
+ state = recoverPublication(state);
89
+ if (state?.status !== 'active')
90
+ return false;
91
+ if (requested && requested !== state.agentId || options.has('--server') && resource !== state.resource)
92
+ throw new Error('AgyIdentityMismatch');
93
+ const target = state.resource, dir = folderProfile(folder, state.generation);
94
+ credentials(dir, target);
95
+ await savedOAuth(dir, async (client) => {
96
+ const identity = principal(await client.callTool({ name: 'whoami', arguments: {} }));
97
+ if (identity.id !== state.agentId || state.workspaceId && identity.workspace_id !== state.workspaceId)
98
+ throw new Error('AgyRuntimeIdentity');
99
+ // A hint-only retry does not rotate the revision beneath a live monitor.
100
+ if (!state.hintPending || state.installed?.length !== 3 || !state.revision)
101
+ state = installFolder(state, identity, target);
102
+ else
103
+ verifyInstalled(state);
104
+ await registerHint(client, state);
105
+ connected(folder, identity.id);
106
+ return null;
107
+ }, target);
108
+ return true;
109
+ });
110
+ if (upgraded)
111
+ return;
112
+ const pending = await folderLifecycle(folder, async () => {
113
+ let state = folderState(folder);
114
+ if (state)
115
+ state = recoverPublication(state);
116
+ if (state?.status === 'retired')
117
+ throw new Error('AgyConfigChanged');
118
+ if (!state || state.status === 'removed')
119
+ state = { schema: 1, folder, generation: randomUUID(), status: 'pending' };
120
+ // Validate all three files before opening a browser or creating a remote agent.
121
+ const before = folderSnapshots(folder);
122
+ if (state.installed && state.installed.some((hash, i) => !before[i].identity || digest(before[i].bytes) !== hash || before[i].mode !== state.installedModes[i]))
123
+ throw new Error('AgyConfigChanged');
124
+ configuredManifest(before[0], !!state.installed);
125
+ configured(before[1], {}, !!state.installed);
126
+ configuredHooks(before[2], {}, state.installed?.length === 3);
127
+ const p = state.pending;
128
+ if (p?.phase === 'received') {
129
+ if (resource !== p.resource || requested && requested !== p.requestedAgent)
130
+ throw new Error('AgyApprovalReceived');
131
+ // A durable credential save can precede its phase checkpoint on interruption.
132
+ credentials(folderProfile(folder, p.generation), p.resource);
133
+ return p;
134
+ }
135
+ if (p?.phase === 'exchange') {
136
+ const prior = folderProfile(folder, p.generation);
137
+ if (receivedCredentials(prior, p.resource)) {
138
+ if (resource !== p.resource || requested && requested !== p.requestedAgent)
139
+ throw new Error('AgyApprovalReceived');
140
+ p.phase = 'received';
141
+ saveFolder(state);
142
+ return p;
143
+ }
144
+ if (!requested)
145
+ throw new Error('AgyApprovalUnknown');
146
+ }
147
+ const next = { generation: randomUUID(), resource, requestedAgent: requested, phase: 'approval' };
148
+ state.pending = next;
149
+ saveFolder(state);
150
+ return next;
151
+ });
152
+ const stage = folderProfile(folder, pending.generation, true), abort = new AbortController();
153
+ const cancel = () => abort.abort(new Error('ApprovalCancelled'));
154
+ process.once('SIGINT', cancel);
155
+ process.once('SIGTERM', cancel);
156
+ let oauth, committed = false;
157
+ const phase = async (value) => folderLifecycle(folder, async () => {
158
+ const state = folderState(folder);
159
+ if (!state || state.status === 'retired' || state.status === 'removed' || state.pending?.generation !== pending.generation)
160
+ throw new Error('AgyGenerationChanged');
161
+ state.pending.phase = value;
162
+ saveFolder(state);
163
+ pending.phase = value;
164
+ });
165
+ const publish = async (result, client) => {
166
+ const identity = principal(result);
167
+ if (pending.requestedAgent && identity.id !== pending.requestedAgent)
168
+ throw new Error('AgyIdentityMismatch');
169
+ await folderLifecycle(folder, async () => {
170
+ const state = folderState(folder);
171
+ if (!state || state.status === 'retired' || state.status === 'removed' || state.pending?.generation !== pending.generation)
172
+ throw new Error('AgyGenerationChanged');
173
+ credentials(stage, resource);
174
+ installFolder(state, identity, resource, pending.generation);
175
+ committed = true;
176
+ });
177
+ await folderLifecycle(folder, async () => { const state = folderState(folder); if (!state || state.status !== 'active' || state.generation !== pending.generation)
178
+ throw new Error('AgyGenerationChanged'); await registerHint(client, state); });
179
+ connected(folder, identity.id);
180
+ try {
181
+ oauth?.complete({ agentId: identity.id, workspaceId: identity.workspace_id });
182
+ }
183
+ catch {
184
+ process.stderr.write('The connection is saved. Browser completion could not be opened; use the start command above.\n');
185
+ }
186
+ };
67
187
  try {
68
- readPrivate(path.join(profile(agent, resource), 'credentials.json'));
188
+ if (pending.phase === 'received')
189
+ await savedOAuth(stage, async (client) => { await publish(await client.callTool({ name: 'whoami', arguments: {} }, undefined, { signal: abort.signal }), client); return null; }, resource);
190
+ else {
191
+ oauth = await openOAuth(stage, requested, resource, true, { signal: abort.signal, onExchange: () => phase('exchange'), onTokens: () => phase('received') });
192
+ await publish(await oauth.client.callTool({ name: 'whoami', arguments: {} }, undefined, { signal: abort.signal }), oauth.client);
193
+ }
69
194
  }
70
195
  catch (error) {
71
- if (!(error instanceof Error && error.message === 'AgyNotConnected'))
196
+ if (committed)
72
197
  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)
80
- throw new Error('AgyIdentityMismatch');
81
- await lifecycle(async () => {
82
- let state = install();
83
- if (!state || state.generation !== generation || !['active', 'pending'].includes(state.status))
84
- 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' });
104
- });
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`);
198
+ const reason = abort.signal.aborted ? 'ApprovalCancelled' : agyReason(error, 'AgyApprovalFailed');
199
+ if (reason === 'AgyIdentityMismatch')
200
+ await folderLifecycle(folder, async () => {
201
+ const state = folderState(folder);
202
+ if (state?.pending?.generation === pending.generation) {
203
+ delete state.pending;
204
+ saveFolder(state);
205
+ }
206
+ });
207
+ if (['AgyGenerationChanged', 'AgyIdentityMismatch', 'AgyConfigChanged', 'AgyConfigInvalid', 'AgyUnsafeState'].includes(reason))
208
+ throw new Error(reason);
209
+ if (pending.phase === 'exchange')
210
+ throw new Error('AgyApprovalUnknown');
211
+ if (pending.phase === 'received') {
212
+ if (error instanceof Error && (['InvalidGrantError', 'InvalidClientError'].includes(error.constructor.name) || error.message === 'ReconnectRequired'))
213
+ throw new Error('ReconnectRequired');
214
+ throw new Error('AgyApprovalReceived');
215
+ }
216
+ throw new Error(reason);
107
217
  }
108
218
  finally {
109
- await oauth.close();
219
+ process.removeListener('SIGINT', cancel);
220
+ process.removeListener('SIGTERM', cancel);
221
+ await oauth?.close().catch(() => undefined);
222
+ // Retain received or unknown approval privately for recovery. Never erase an
223
+ // active profile or the only evidence of a possibly committed redemption.
110
224
  }
111
- }
112
- finally {
113
- fs.rmSync(stage, { recursive: true, force: true });
114
- }
225
+ });
115
226
  }
116
- export async function removeAgy() {
117
- await lifecycle(async () => {
118
- const state = install();
227
+ export async function removeAgy(folder = canonicalFolder()) {
228
+ await folderLifecycle(folder, async () => {
229
+ let state = folderState(folder);
119
230
  if (!state || state.status === 'removed')
120
231
  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' });
232
+ if (state.transaction)
233
+ state = recoverPublication(state);
234
+ state = { ...state, status: 'retired' };
235
+ saveFolder(state);
236
+ restoreFolder(state);
237
+ const removed = { ...state, status: 'removed' };
238
+ delete removed.pending;
239
+ saveFolder(removed);
130
240
  });
131
- process.stdout.write('AgentMesh agy connections removed; original shared config restored.\n');
241
+ process.stdout.write('AgentMesh connection removed from this folder; original plugin files restored.\n');
132
242
  }