@agentmesh-md/mcp-server 0.3.4 → 0.3.6

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.4 is an unpublished local release candidate.** The npm package is `@agentmesh-md/mcp-server`. Alex publishes
8
+ **Version 0.3.6 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.4.tgz
19
+ npm install /ABSOLUTE/PATH/TO/agentmesh-md-mcp-server-0.3.6.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.4`. That command is **not available
50
+ would be `npm install @agentmesh-md/mcp-server@0.3.6`. 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
 
@@ -160,19 +160,21 @@ disconnect. Cleanup errors remain visible and never restore authorization.
160
160
 
161
161
  Claude uses the generated HTTPS marketplace and immutable SHA256-bound ZIP.
162
162
  The proposed production URL is not a publication claim. Atlas stages candidate
163
- assets separately. Connect does not check Claude or Codex versions. Run
164
- `/reload-plugins` once in an existing Claude session after Connect. Its monitor
165
- binds that native owner and folder without an extra prompt or a replayed
166
- SessionStart. New sessions use the same binding transition from their hooks.
163
+ assets separately. Connect does not check Claude or Codex versions. After
164
+ Connect, quit Claude Code and start it again to load AgentMesh tools and wakes.
165
+ The connection is already saved; no second Connect is needed. A new session binds
166
+ its native owner and folder through its hooks. Atlas may use `/reload-plugins`
167
+ for the separate operator-assisted same-session upgrade proof; this is not an
168
+ automatic upgrade or the customer activation instruction.
167
169
  Codex installs the same payload from npm's generated local marketplace and merges
168
170
  its lifecycle hooks into `$CODEX_HOME/hooks.json` (default `~/.codex/hooks.json`).
169
171
  Foreign hooks are preserved. The command uses a stable private launcher under
170
172
  `~/.agentmesh/plugin/`; upgrades update its private target without changing the
171
173
  hook command. Connect rereads the file and verifies the command, or exits nonzero
172
174
  naming the file and repair. This proves saved setup, not that Codex loaded a hook.
173
- In an already-open Codex session, open `/plugins`, select AgentMesh, and switch
174
- it off then on to refresh the running session. In `/hooks`, review and trust the
175
- AgentMesh hooks, then send your first message. The first eligible hook binds that
175
+ Existing trusted Codex session listeners refresh automatically after Connect.
176
+ For a first connection, review and trust AgentMesh in `/hooks`, then send your
177
+ first message. The first eligible hook binds that
176
178
  existing session and supplies its logical workspace to all AgentMesh tool calls;
177
179
  before that hook, tools load but calls ask you to trust hooks and send a message.
178
180
  An install does not replay SessionStart. Wakes turns On only
@@ -181,12 +183,13 @@ managed-only hooks stay subject to Codex policy; installation never grants trust
181
183
  changes that policy, starts app-server, or resumes a session. Plugin-bundled Codex
182
184
  hooks are not used by this shipping path.
183
185
 
184
- Each Codex prompt/Stop hook ensures one watcher for the current native owner and
185
- replaces a dead watcher. Claude's plugin monitor supervises the existing listener:
186
- an unexpected exit retries after 1s, doubling to 60s, resetting after five healthy
187
- minutes. It does no additional server polling. Revoked approval, local disconnect,
188
- or session exit ends supervision; shutdown reaps its worker, including a stuck
189
- worker. Retries preserve the same binding and existing action-receipt semantics.
186
+ Each Codex prompt/Stop hook ensures one listener for the current native owner
187
+ and replaces a dead listener. An already-running trusted listener hands off to
188
+ the installed payload without a prompt or a new session. Claude's host starts
189
+ its plugin monitor after native activation. Each monitor owns its polling loop;
190
+ there is no separate supervisor. Retries preserve the same binding and existing
191
+ action-receipt semantics. Revoked approval, local disconnect or session exit
192
+ ends that binding. A superseded monitor retires after the new catalog is admitted.
190
193
 
191
194
  Hooks record the native session UUID and exact process ancestry/start identity.
192
195
  The MCP process and Claude monitor resolve only that owner, never a latest
@@ -220,7 +223,7 @@ only after handling. Transport output alone does not claim or complete work.
220
223
  saved approval. Revoked approval requires reconnect; transient failures retry.
221
224
 
222
225
  `npm run build:plugin` generates the npm local marketplace and
223
- `web/public/plugins/{marketplace.json,agentmesh-0.3.4.zip,agentmesh-0.3.4.sha256}`.
226
+ `web/public/plugins/{marketplace.json,agentmesh-0.3.6.zip,agentmesh-0.3.6.sha256}`.
224
227
  Regenerate after server/schema integration before freezing candidate hashes.
225
228
 
226
229
  Session hooks and listeners validate the actual owner's process and executable
@@ -234,7 +237,7 @@ proxy resolves that binding.
234
237
 
235
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.
236
239
 
237
- 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.4.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.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.
238
241
 
239
242
  Connect resolves the selected CLI to one absolute executable path and prints it
240
243
  before browser approval. It does not run client version or help probes, including
@@ -244,7 +247,7 @@ Standalone installation is setup only: Wakes stay off until the native session
244
247
  binds the owner and its probe is read. A missing CLI names the client to install.
245
248
 
246
249
  Publishing npm does not update cached plugins or modules already loaded in a
247
- running session. For the coordinated 0.3.4 mesh install, Atlas enumerates every
250
+ running session. For the coordinated 0.3.6 mesh install, Atlas enumerates every
248
251
  connected seat and runs Connect in its actual workspace directory with
249
252
  `--agent EXISTING_AGENT_UUID --workspace EXISTING_WORKSPACE_UUID`, then performs
250
253
  the native activation described above. Atlas owns the complete seat pass; no
@@ -253,3 +256,46 @@ trust remain authoritative. Retained KEEP sessions require Atlas's explicit
253
256
  release before that pass. Verify the same agent/workspace with whoami and its
254
257
  probe after activation; npm publication alone does not satisfy that readback.
255
258
  The hosted backend, SPA command and npm release must update in the same install.
259
+
260
+
261
+ ## Antigravity (agy) Connect
262
+
263
+ Use the installed CLI for each seat, approving that seat's AgentMesh identity in
264
+ its browser sign-in:
265
+
266
+ ```sh
267
+ agentmesh-mcp connect --client agy --agent <agent-UUID> --workspace <workspace-UUID>
268
+ env AGENTMESH_AGENT=<agent-UUID> agy <existing-seat-arguments>
269
+ ```
270
+
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.
288
+
289
+ ```sh
290
+ agentmesh-mcp connect --client agy --remove
291
+ ```
292
+
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.
@@ -0,0 +1,123 @@
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 } 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
+ 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
+ }
@@ -0,0 +1,132 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { openOAuth, RESOURCE, credentialFile } from './oauth-client.js';
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';
10
+ export function principal(result) {
11
+ const r = result;
12
+ if (r?.isError)
13
+ throw new Error('AgyIdentityMismatch');
14
+ let data;
15
+ try {
16
+ data = (r?.structuredContent ?? JSON.parse(r?.content?.find(v => v.type === 'text')?.text ?? '{}'));
17
+ }
18
+ catch {
19
+ throw new Error('AgyIdentityMismatch');
20
+ }
21
+ const p = data?.principal;
22
+ if (p?.kind !== 'agent' || typeof p.id !== 'string' || !UUID.test(p.id) || typeof p.workspace_id !== 'string' || !UUID.test(p.workspace_id))
23
+ throw new Error('AgyIdentityMismatch');
24
+ return { id: p.id.toLowerCase(), workspace_id: p.workspace_id.toLowerCase() };
25
+ }
26
+ export async function agyConnect(args) {
27
+ const options = new Map();
28
+ let remove = false;
29
+ for (let i = 0; i < args.length; i++) {
30
+ const key = args[i];
31
+ if (key === '--remove') {
32
+ if (remove)
33
+ throw new Error('AgyArgumentsInvalid');
34
+ remove = true;
35
+ continue;
36
+ }
37
+ if (!['--client', '--agent', '--workspace', '--server'].includes(key) || options.has(key) || !args[i + 1] || args[i + 1].startsWith('--'))
38
+ throw new Error('AgyArgumentsInvalid');
39
+ options.set(key, args[++i]);
40
+ }
41
+ if (options.get('--client') !== 'agy')
42
+ throw new Error('AgyArgumentsInvalid');
43
+ if (remove) {
44
+ if (options.size !== 1)
45
+ throw new Error('AgyArgumentsInvalid');
46
+ await removeAgy();
47
+ return;
48
+ }
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)
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`);
107
+ }
108
+ finally {
109
+ await oauth.close();
110
+ }
111
+ }
112
+ finally {
113
+ fs.rmSync(stage, { recursive: true, force: true });
114
+ }
115
+ }
116
+ export async function removeAgy() {
117
+ await lifecycle(async () => {
118
+ const state = install();
119
+ if (!state || state.status === 'removed')
120
+ 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' });
130
+ });
131
+ process.stdout.write('AgentMesh agy connections removed; original shared config restored.\n');
132
+ }
@@ -0,0 +1,72 @@
1
+ import { serveStdio } from '@modelcontextprotocol/server/stdio';
2
+ import { buildServer } from './server.js';
3
+ import { MCP_INSTRUCTIONS } from './contract.js';
4
+ import { HOSTED_TOOL_NAMES } from './schemas.js';
5
+ import { savedOAuth } from './oauth-client.js';
6
+ import { agentUUID, root, lifecycle, install, enrollment, profile, credentials } from './agy-storage.js';
7
+ import { principal } from './agy-connect.js';
8
+ import { terminalDiagnostic } from './terminal-diagnostic.js';
9
+ function failure(cause, agent) {
10
+ const remedy = `Run connect --client agy --agent ${agent} again.`;
11
+ const messages = {
12
+ 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.",
13
+ 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.",
14
+ AgyNotConnected: `AgentMesh agent ${agent} is not connected. ${remedy}`,
15
+ AgyDisconnected: `AgentMesh agent ${agent} is disconnected. ${remedy}`,
16
+ AgyUnsafeState: `AgentMesh agent ${agent} has unsafe or invalid local credentials. Repair owner-only local files, then run connect --client agy --agent ${agent} again.`,
17
+ ReconnectRequired: `AgentMesh approval for agent ${agent} expired or was revoked. ${remedy}`,
18
+ AgyUnavailable: `AgentMesh is unavailable for agent ${agent}. Check the connection, then run connect --client agy --agent ${agent} again.`,
19
+ AgyIdentityMismatch: `AgentMesh identity for agent ${agent} did not match. ${remedy}`,
20
+ };
21
+ return { isError: true, content: [{ type: 'text', text: messages[cause] ?? messages.AgyUnsafeState }] };
22
+ }
23
+ export async function agyCall(name, args, signal) {
24
+ let agent, cause = 'AgyUnsafeState';
25
+ try {
26
+ const selected = process.env.AGENTMESH_AGENT;
27
+ if (!selected)
28
+ throw new Error('AgyMissingSelection');
29
+ agent = agentUUID(selected);
30
+ root();
31
+ return await lifecycle(async () => {
32
+ const state = install();
33
+ if (!state)
34
+ throw new Error('AgyNotConnected');
35
+ if (state.status === 'retired' || state.status === 'removed')
36
+ throw new Error('AgyDisconnected');
37
+ if (state.status !== 'active')
38
+ throw new Error('AgyNotConnected');
39
+ const e = enrollment(agent);
40
+ if (!e)
41
+ throw new Error('AgyNotConnected');
42
+ if (e.generation !== state.generation)
43
+ throw new Error('AgyDisconnected');
44
+ const dir = profile(agent, e.resource);
45
+ credentials(dir, e.resource);
46
+ cause = 'AgyUnavailable';
47
+ return await savedOAuth(dir, async (client) => {
48
+ const proof = await client.callTool({ name: 'whoami', arguments: {} }, undefined, { signal });
49
+ const identity = principal(proof);
50
+ if (identity.id !== agent || identity.workspace_id !== e.workspaceId)
51
+ throw new Error('AgyIdentityMismatch');
52
+ return name === 'whoami' ? proof : await client.callTool({ name, arguments: args }, undefined, { signal });
53
+ }, e.resource);
54
+ });
55
+ }
56
+ catch (error) {
57
+ const code = error instanceof Error ? error.message : '';
58
+ if (error instanceof Error && ['InvalidGrantError', 'InvalidClientError', 'UnauthorizedError'].includes(error.constructor.name))
59
+ cause = 'ReconnectRequired';
60
+ if (['AgyMissingSelection', 'AgyInvalidSelection', 'AgyNotConnected', 'AgyDisconnected', 'AgyIdentityMismatch', 'ReconnectRequired'].includes(code))
61
+ cause = code;
62
+ else if (error instanceof SyntaxError || ['AgyUnsafeState', 'OwnerCredentialsRequired', 'PrivateFileRequired', 'OwnerDirectoryRequired', 'UnapprovedResource', 'ResourceMismatch'].includes(code))
63
+ cause = 'AgyUnsafeState';
64
+ process.stderr.write(`AgentMesh ${cause}; ${terminalDiagnostic(error, 'agy-proxy.js', 'agyCall')}.\n`);
65
+ return failure(cause, agent);
66
+ }
67
+ }
68
+ export function agyProxy() {
69
+ serveStdio(() => buildServer({ instructions: MCP_INSTRUCTIONS, allowedTools: HOSTED_TOOL_NAMES.filter(name => !name.startsWith('terminal_wake_')), dispatch: agyCall }), {
70
+ onerror: error => process.stderr.write(`AgentMesh stdio unavailable; ${terminalDiagnostic(error, 'agy-proxy.js', 'agyProxy')}.\n`)
71
+ });
72
+ }
@@ -0,0 +1,92 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { createHash, randomUUID } from 'node:crypto';
5
+ import { UUID, privateRead, locked } from './plugin-storage.js';
6
+ import { writeAtomic } from './wake-storage.js';
7
+ import { resourceTarget } from './plugin-target.js';
8
+ import { credentialFile } from './oauth-client.js';
9
+ export const digest = (value) => createHash('sha256').update(value).digest('hex');
10
+ export function agentUUID(value) {
11
+ if (!UUID.test(value))
12
+ throw new Error('AgyInvalidSelection');
13
+ return value.toLowerCase();
14
+ }
15
+ export function lstat(file) {
16
+ try {
17
+ return fs.lstatSync(file);
18
+ }
19
+ catch (error) {
20
+ if (error.code === 'ENOENT')
21
+ return;
22
+ throw error;
23
+ }
24
+ }
25
+ // Walk from HOME: recursive mkdir by itself can traverse an existing symlink.
26
+ export function directory(parts, create, privateMode = true) {
27
+ let dir = os.homedir();
28
+ for (const part of parts) {
29
+ dir = path.join(dir, part);
30
+ let s = lstat(dir);
31
+ if (!s) {
32
+ if (!create)
33
+ throw new Error('AgyNotConnected');
34
+ fs.mkdirSync(dir, { mode: 0o700 });
35
+ s = fs.lstatSync(dir);
36
+ }
37
+ if (!s.isDirectory() || s.isSymbolicLink() || s.uid !== process.getuid?.() || (s.mode & (privateMode && part !== '.agentmesh' ? 0o077 : 0o022)))
38
+ throw new Error('AgyUnsafeState');
39
+ }
40
+ return dir;
41
+ }
42
+ export function root(create = false) { return directory(['.agentmesh', 'agy'], create); }
43
+ export function profile(agent, resource, create = false) {
44
+ agent = agentUUID(agent);
45
+ resourceTarget(resource);
46
+ return directory(['.agentmesh', 'agy', 'agents', agent, digest(resource).slice(0, 24)], create);
47
+ }
48
+ export function readPrivate(file) {
49
+ const s = lstat(file);
50
+ if (!s)
51
+ return;
52
+ if (s.isSymbolicLink() || !s.isFile() || s.uid !== process.getuid?.() || (s.mode & 0o077))
53
+ throw new Error('AgyUnsafeState');
54
+ return privateRead(file);
55
+ }
56
+ export function credentials(dir, resource) {
57
+ const file = path.join(dir, 'credentials.json');
58
+ readPrivate(file);
59
+ const value = credentialFile(file, resource);
60
+ if (!value?.tokens || typeof value.tokens.access_token !== 'string' || !value.tokens.access_token ||
61
+ value.tokens.refresh_token !== undefined && typeof value.tokens.refresh_token !== 'string' ||
62
+ typeof value.client?.client_id !== 'string' || !value.client.client_id || typeof value.redirect !== 'string')
63
+ throw new Error('AgyUnsafeState');
64
+ return value;
65
+ }
66
+ export function install() {
67
+ const value = readPrivate(path.join(root(), 'install.json'));
68
+ if (value && (value.schema !== 1 || !UUID.test(value.generation) || !['pending', 'active', 'retired', 'removed'].includes(value.status) ||
69
+ value.originalHash !== undefined && (!/^[a-f0-9]{64}$/.test(value.originalHash) || typeof value.originalAbsent !== 'boolean' || !Number.isInteger(value.originalMode) || value.originalMode < 0 || value.originalMode > 0o777) ||
70
+ value.configHash !== undefined && !/^[a-f0-9]{64}$/.test(value.configHash) ||
71
+ value.status === 'active' && (!value.configHash || !value.originalHash)))
72
+ throw new Error('AgyUnsafeState');
73
+ return value;
74
+ }
75
+ export function saveInstall(value) { writeAtomic(path.join(root(), 'install.json'), value); }
76
+ export function enrollment(agent) {
77
+ agent = agentUUID(agent);
78
+ const dir = directory(['.agentmesh', 'agy', 'enrollments'], false);
79
+ const value = readPrivate(path.join(dir, agent + '.json'));
80
+ if (value && (value.schema !== 1 || value.agentId !== agent || !UUID.test(value.workspaceId) || !UUID.test(value.generation)))
81
+ throw new Error('AgyUnsafeState');
82
+ if (value)
83
+ resourceTarget(value.resource);
84
+ return value;
85
+ }
86
+ export function saveEnrollment(value) {
87
+ const dir = directory(['.agentmesh', 'agy', 'enrollments'], true), file = path.join(dir, agentUUID(value.agentId) + '.json');
88
+ readPrivate(file);
89
+ writeAtomic(file, value);
90
+ }
91
+ export async function lifecycle(fn) { return locked(root(true), 'lifecycle', fn); }
92
+ export function freshInstall() { return { schema: 1, generation: randomUUID(), status: 'pending' }; }
@@ -49,6 +49,31 @@ function readDocument(file) {
49
49
  return value;
50
50
  }
51
51
  const quote = (s) => "'" + s.replaceAll("'", "'\\''") + "'";
52
+ /** Resolve the installed content destination, never a caller's cached bundle. */
53
+ export function installedCodexTarget() {
54
+ const root = privateRoot(), target = privateRead(path.join(root, 'codex-hook-target.json'));
55
+ if (!target || typeof target.node !== 'string' || !path.isAbsolute(target.node) || typeof target.entry !== 'string')
56
+ throw new Error('CodexInstalledTargetUnavailable');
57
+ const relative = path.relative(root, target.entry);
58
+ if (!/^release-[a-f0-9]{64}\/plugins\/agentmesh\/server\/lib\/agentmesh-mcp\.js$/.test(relative))
59
+ throw new Error('CodexInstalledTargetUnsafe');
60
+ // Every installed component is private, owner-held, and free of symlinks.
61
+ let component = root;
62
+ for (const name of relative.split(path.sep)) {
63
+ component = path.join(component, name);
64
+ const st = fs.lstatSync(component);
65
+ if (st.isSymbolicLink() || st.uid !== process.getuid?.() || (st.mode & 0o077) !== 0 || !(component === target.entry ? st.isFile() : st.isDirectory()))
66
+ throw new Error('CodexInstalledTargetUnsafe');
67
+ }
68
+ const release = privateRead(path.resolve(path.dirname(target.entry), '../../release.json'))?.digest;
69
+ if (typeof release !== 'string' || !/^[a-f0-9]{64}$/.test(release))
70
+ throw new Error('CodexInstalledReleaseInvalid');
71
+ const node = fs.realpathSync(target.node), st = fs.statSync(node);
72
+ if (!st.isFile() || (st.mode & 0o022) !== 0 || ![0, process.getuid?.()].includes(st.uid))
73
+ throw new Error('CodexInstalledTargetUnsafe');
74
+ fs.accessSync(node, fs.constants.X_OK);
75
+ return { node, entry: target.entry, release };
76
+ }
52
77
  export async function installCodexHooks(entry) {
53
78
  const home = path.resolve(process.env.CODEX_HOME || path.join(os.homedir(), '.codex')), file = path.join(home, 'hooks.json');
54
79
  try {