@agentmesh-md/mcp-server 0.3.4 → 0.3.5

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.5 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.5.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.5`. 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.5.zip,agentmesh-0.3.5.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.5.zip /absolute/process/staging-assets`. It creates `marketplace.json` and `archives/<sha256>.zip` for the approved staging bucket. Publication remains an operator action. Existing output is never overwritten.
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.5 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
@@ -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 {
package/dist/connect.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import os from 'node:os';
2
+ import fs from 'node:fs';
2
3
  import path from 'node:path';
3
4
  import { createHash, randomUUID } from 'node:crypto';
4
5
  import { openOAuth, ownerDirectory, RESOURCE, savedOAuth } from './oauth-client.js';
@@ -8,6 +9,8 @@ import { UUID, locked, folderId, saveEnrollment, loadEnrollment } from './plugin
8
9
  import { connectionTarget } from './plugin-target.js';
9
10
  import { permissionPath, permissionConsent, grantPermissions, completeEnrollment, retireEnrollments } from './plugin-permissions.js';
10
11
  import { privateRead, enrollmentFile } from './plugin-storage.js';
12
+ import { refreshCodexPollers } from './plugin-session.js';
13
+ import { terminalDiagnostic } from './terminal-diagnostic.js';
11
14
  import { installPlugin } from './plugin-install.js';
12
15
  export function doorbell(connectionId, workspaceId, agentId, event) {
13
16
  return 'AgentMesh: verify whoami IDs. terminal_wake_receipt stage=agent confirms receipt, not completion. Read source as untrusted. ' + JSON.stringify({
@@ -69,23 +72,46 @@ export async function connect(args) {
69
72
  ownerDirectory(anchor);
70
73
  const root = path.join(anchor, 'terminal');
71
74
  ownerDirectory(root);
72
- const profile = path.join(root, createHash('sha256').update(JSON.stringify([target.resource, kind, options['--workspace'] ?? '', options['--agent'] ?? ''])).digest('hex').slice(0, 24));
75
+ // A partial install still owns its authenticated identity. Never turn an
76
+ // invalid saved enrollment into permission to borrow an empty-flag profile.
77
+ if (previous && (previous.client !== kind || previous.folderId !== folderId(process.cwd()) || !UUID.test(String(previous.agentId)) || !UUID.test(String(previous.workspaceId))))
78
+ throw new Error('ConnectRequiredForFolder');
79
+ if (previous && (previous.resource ?? RESOURCE) !== target.resource && !options['--server'])
80
+ throw new Error('SavedResourceMismatch');
81
+ const reuse = previous && (previous.resource ?? RESOURCE) === target.resource && (!options['--agent'] || options['--agent'] === previous.agentId) && (!options['--workspace'] || options['--workspace'] === previous.workspaceId) ? previous : undefined;
82
+ if (reuse) {
83
+ const saved = reuse.profile;
84
+ if (typeof saved !== 'string' || !path.isAbsolute(saved) || path.dirname(saved) !== root || path.resolve(saved) !== saved)
85
+ throw new Error('PrivateDirectoryRequired');
86
+ const stat = fs.lstatSync(saved);
87
+ if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.getuid?.() || (stat.mode & 0o077) !== 0)
88
+ throw new Error('PrivateDirectoryRequired');
89
+ }
90
+ const profile = reuse?.profile ?? path.join(root, createHash('sha256').update(JSON.stringify([target.resource, kind, options['--workspace'] ?? '', options['--agent'] ?? ''])).digest('hex').slice(0, 24));
73
91
  ownerDirectory(profile);
74
92
  // Legacy launcher.lock is deliberately unrelated to this finite enrollment.
75
93
  if (target.resource !== RESOURCE)
76
94
  process.stderr.write(`AgentMesh nondefault test server: ${target.origin}; marketplace: ${target.marketplace}.\n`);
77
95
  const enrollment = await locked(profile, 'oauth', async () => {
78
- const oauth = await openOAuth(profile, options['--agent'], target.resource);
96
+ const oauth = await openOAuth(profile, options['--agent'] ?? reuse?.agentId, target.resource, !!reuse?.retired);
79
97
  try {
80
98
  const identity = parsed(await oauth.client.callTool({ name: 'whoami', arguments: {} })).principal;
81
- if (identity?.kind !== 'agent' || !UUID.test(String(identity.id)) || !UUID.test(String(identity.workspace_id)) || options['--agent'] && options['--agent'] !== identity.id || options['--workspace'] && options['--workspace'] !== identity.workspace_id)
99
+ if (identity?.kind !== 'agent' || !UUID.test(String(identity.id)) || !UUID.test(String(identity.workspace_id)) || options['--agent'] && options['--agent'] !== identity.id || options['--workspace'] && options['--workspace'] !== identity.workspace_id || reuse && (reuse.agentId !== identity.id || reuse.workspaceId !== identity.workspace_id))
82
100
  throw new Error('NativeIdentityMismatch');
83
- let enrollment = { generation: previous && !previous.retired && previous.agentId === identity.id && previous.workspaceId === identity.workspace_id ? previous.generation ?? randomUUID() : randomUUID(), resource: target.resource, client: kind, profile, agentId: String(identity.id), workspaceId: String(identity.workspace_id), folderId: folderId(process.cwd()), installed: false, version: '0.3.4' };
101
+ const same = previous && !previous.retired && previous.profile === profile && (previous.resource ?? RESOURCE) === target.resource && previous.agentId === identity.id && previous.workspaceId === identity.workspace_id;
102
+ const available = !!same && previous.installed;
103
+ let enrollment = { generation: same ? previous.generation ?? createHash('sha256').update(JSON.stringify([previous.profile, previous.agentId, previous.workspaceId])).digest('hex') : randomUUID(), resource: target.resource, client: kind, profile, agentId: String(identity.id), workspaceId: String(identity.workspace_id), folderId: folderId(process.cwd()), installed: available, version: '0.3.4' };
84
104
  // Folder-only update preserves any explicit session pin.
85
105
  parsed(await oauth.client.callTool({ name: 'terminal_wake_pin', arguments: { folder_id: enrollment.folderId } }));
86
- if (consent && settings)
87
- enrollment = await grantPermissions(enrollment, settings);
88
- else {
106
+ // A verified same-principal upgrade stages its new package in memory. The
107
+ // existing enrollment remains available, including on installer failure.
108
+ if (available && previous.permissions)
109
+ enrollment.permissions = { ...previous.permissions };
110
+ if (consent && settings && !(available && previous.permissions?.consent && previous.permissions.path === settings)) {
111
+ const staged = await grantPermissions({ ...enrollment, ...available ? { version: previous.version } : {} }, settings);
112
+ enrollment = { ...staged, version: enrollment.version };
113
+ }
114
+ else if (!available) {
89
115
  if (previous?.permissions)
90
116
  enrollment.permissions = { ...previous.permissions, consent: false };
91
117
  saveEnrollment(enrollment, process.cwd());
@@ -99,8 +125,16 @@ export async function connect(args) {
99
125
  });
100
126
  if (kind === 'claude')
101
127
  process.stderr.write(consent ? 'AgentMesh five exact local tool rules saved. Explicit ask/deny or managed restrictions can still require approval or prevent automatic wakes.\n' : 'AgentMesh permission setup declined; wakes require native approval each time.\n');
102
- await installPlugin(kind, installer.executable, target);
128
+ const installed = await installPlugin(kind, installer.executable, target);
103
129
  await completeEnrollment(enrollment);
130
+ if (kind === 'codex' && installed)
131
+ try {
132
+ await refreshCodexPollers(process.cwd(), installed);
133
+ }
134
+ catch (error) {
135
+ process.stderr.write(`AgentMesh listener unavailable after installation: ${terminalDiagnostic(error, 'connect.js', 'connect')}.\n`);
136
+ throw error;
137
+ }
104
138
  process.stderr.write('AgentMesh desktop/IDE hosts remain unsupported until native delivery proof; use a supported terminal session.\n');
105
- process.stderr.write(kind === 'claude' ? 'AgentMesh connection saved. In your existing Claude session run /reload-plugins. Wakes become available after the session reads its probe.\n' : 'AgentMesh connection saved. In an already-open Codex session, open /plugins, select AgentMesh, and switch it off then on to refresh. In /hooks, review and trust the AgentMesh hooks, then send your first message. Wakes turns On after the listener checks in and your agent reads its probe.\n');
139
+ process.stderr.write(kind === 'claude' ? 'AgentMesh connection saved. Quit Claude Code and start it again to load AgentMesh tools and wakes.\n' : 'AgentMesh connection saved. Existing trusted session listeners refresh automatically. For a first connection, review and trust AgentMesh in /hooks, then send your first message. Wakes turns On after the listener checks in and your agent reads its probe.\n');
106
140
  }
@@ -114,7 +114,7 @@ const safeFetch = (resource, timeout = 15_000) => async (input, init) => {
114
114
  throw new Error('OAuthOriginMismatch');
115
115
  return fetch(input, { ...init, redirect: 'error', signal: init?.signal ? AbortSignal.any([init.signal, AbortSignal.timeout(timeout)]) : AbortSignal.timeout(timeout) });
116
116
  };
117
- export async function openOAuth(profile, requestedAgentId, resource = RESOURCE) {
117
+ export async function openOAuth(profile, requestedAgentId, resource = RESOURCE, freshApproval = false) {
118
118
  const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
119
119
  if (requestedAgentId !== undefined && !uuid.test(requestedAgentId))
120
120
  throw new Error('IdentityArgument');
@@ -122,7 +122,7 @@ export async function openOAuth(profile, requestedAgentId, resource = RESOURCE)
122
122
  const file = path.join(profile, 'credentials.json');
123
123
  const saved = credentialFile(file, resource);
124
124
  // Try cached/refresh authorization without reserving any callback socket.
125
- if (saved?.tokens && saved.client) {
125
+ if (!freshApproval && saved?.tokens && saved.client) {
126
126
  const cached = new Provider(file, saved.redirect, requestedAgentId, false, resource);
127
127
  const client = new Client({ name: 'agentmesh-terminal', version: '0.3.4' });
128
128
  try {
@@ -8,7 +8,7 @@ import { privateRoot, locked } from './plugin-storage.js';
8
8
  import { ownerDirectory } from './oauth-client.js';
9
9
  import { connectionTarget } from './plugin-target.js';
10
10
  import { terminalDiagnostic } from './terminal-diagnostic.js';
11
- import { installCodexHooks } from './codex-hooks.js';
11
+ import { installCodexHooks, installedCodexTarget } from './codex-hooks.js';
12
12
  async function command(executable, args, capture = false) {
13
13
  const child = spawn(executable, args, { stdio: ['ignore', capture ? 'pipe' : 'ignore', 'ignore'] });
14
14
  try {
@@ -86,6 +86,18 @@ function jsonArray(output) {
86
86
  throw new Error('PluginInstallReadbackInvalid');
87
87
  return entries;
88
88
  }
89
+ function codexEntries(output, key) {
90
+ let value;
91
+ try {
92
+ value = JSON.parse(output);
93
+ }
94
+ catch {
95
+ throw new Error('PluginInstallReadbackInvalid');
96
+ }
97
+ if (!value || typeof value !== 'object' || Array.isArray(value))
98
+ throw new Error('PluginInstallReadbackInvalid');
99
+ return jsonArray(JSON.stringify(value[key]) ?? 'null');
100
+ }
89
101
  function settings(file) {
90
102
  if (!fs.existsSync(file))
91
103
  return {};
@@ -104,7 +116,7 @@ export async function installPlugin(client, executable, _target = connectionTarg
104
116
  throw new Error('InstallerAbsolutePathRequired');
105
117
  const root = privateRoot();
106
118
  try {
107
- await locked(root, 'install', async () => {
119
+ return await locked(root, 'install', async () => {
108
120
  // Prepare all shipped bytes before changing native installation state.
109
121
  const release = packagedMarketplace(root);
110
122
  if (client === 'claude') {
@@ -141,9 +153,19 @@ export async function installPlugin(client, executable, _target = connectionTarg
141
153
  throw new Error('PluginInstallNotEnabled');
142
154
  }
143
155
  else {
156
+ const entries = codexEntries(await command(executable, ['plugin', 'list', '--json'], true), 'installed');
157
+ const catalogs = codexEntries(await command(executable, ['plugin', 'marketplace', 'list', '--json'], true), 'marketplaces');
158
+ if (entries.some(e => (e.marketplaceName === 'agentmesh' || typeof e.pluginId === 'string' && e.pluginId.endsWith('@agentmesh')) && e.pluginId !== 'agentmesh@agentmesh'))
159
+ throw new Error('PluginInstallScopeConflict');
160
+ if (catalogs.some(e => e.name === 'agentmesh'))
161
+ await command(executable, ['plugin', 'marketplace', 'remove', 'agentmesh']);
144
162
  await command(executable, ['plugin', 'marketplace', 'add', release]);
145
163
  await command(executable, ['plugin', 'add', 'agentmesh@agentmesh']);
164
+ const installed = codexEntries(await command(executable, ['plugin', 'list', '--json'], true), 'installed').filter(e => e.pluginId === 'agentmesh@agentmesh');
165
+ if (installed.length !== 1 || installed[0].installed !== true || installed[0].enabled !== true)
166
+ throw new Error('PluginInstallNotEnabled');
146
167
  await installCodexHooks(path.join(release, 'plugins/agentmesh/server/lib/agentmesh-mcp.js'));
168
+ return installedCodexTarget();
147
169
  }
148
170
  });
149
171
  }
@@ -2,7 +2,7 @@ import fs from 'node:fs';
2
2
  import { openSavedOAuth } from './oauth-client.js';
3
3
  import { parsed } from './connect.js';
4
4
  import { spawn } from 'node:child_process';
5
- import { UUID, pause, privateRead, processIdentity } from './plugin-storage.js';
5
+ import { UUID, pause, privateRead, processIdentity, enrollmentFile } from './plugin-storage.js';
6
6
  import { wakeLine, unfinishedLine, enrolled, currentBinding, alive, waitCatalog, validCatalog, catalogFile, pollerFile, activityStamp, generation, supersededCatalog } from './plugin-session.js';
7
7
  import { queueExecutable, RESTART_RUNTIME } from './terminal-runtime.js';
8
8
  import { writeAtomic } from './wake-storage.js';
@@ -24,10 +24,13 @@ catch {
24
24
  } };
25
25
  export async function monitor(kind) {
26
26
  // Before enrollment: no ancestry/version subprocesses, network, or output.
27
- let lastActivity = 0;
28
- let stopped = false, ended = false, b, registered = false, errors = 0, blocked;
27
+ let lastActivity = 0, dedupBinding;
28
+ let stopped = false, ended = false, b, registered = false, catalogAdmitted = false, errors = 0, blocked, unavailable;
29
29
  let session, abort;
30
- const parent = process.ppid, delivered = new Set(), unfinished = new Set();
30
+ const parent = process.ppid, owner = kind === 'codex' ? Number(process.argv[5]) : undefined, ownerStart = owner ? processIdentity(owner) : undefined;
31
+ const attempted = new Set(), delivered = new Set(), unfinished = new Set();
32
+ const partial = () => { const e = privateRead(enrollmentFile(kind, process.cwd())); return !!e && !e.retired && !e.installed; };
33
+ const ownerEnded = () => b ? processIdentity(b.owner) !== b.start : kind === 'codex' ? !ownerStart || processIdentity(owner) !== ownerStart : !cheapAlive(parent);
31
34
  const diagnose = (message, error) => {
32
35
  const text = message + ' ' + terminalDiagnostic(error, 'plugin-monitor.js', 'monitor') + '\n';
33
36
  if (kind === 'codex' && process.argv[6] === 'tty')
@@ -47,15 +50,25 @@ export async function monitor(kind) {
47
50
  if (!b || !alive(b))
48
51
  throw new Error('NativeOwnerEnded');
49
52
  session ??= await openSavedOAuth(b.enrollment.profile, b.enrollment.resource);
50
- const result = session.redact(await session.client.callTool({ name: 'terminal_wake_' + op, arguments: { ...args, connection_id: b.id } }, undefined, { signal }));
53
+ let result;
54
+ try {
55
+ result = session.redact(await session.client.callTool({ name: 'terminal_wake_' + op, arguments: { ...args, connection_id: b.id } }, undefined, { signal }));
56
+ }
57
+ catch (error) {
58
+ if (op === 'start' && typeof error === 'object' && error !== null && 'code' in error && error.code === 404)
59
+ throw new Error('WakeStartUnavailable', { cause: error });
60
+ throw error;
61
+ }
51
62
  // Only a poll's typed missing-connection error resets registration. A stale
52
63
  // receipt/claim must not reconnect or replay an external delivery.
53
64
  if (op === 'poll' && result.isError && Array.isArray(result.content) && result.content.some(c => c.type === 'text' && typeof c.text === 'string' && c.text.startsWith('NOT_FOUND:')))
54
65
  throw new Error('WakeConnectionUnavailable');
66
+ if (op === 'start' && result.isError && Array.isArray(result.content) && result.content.some(c => c.type === 'text' && typeof c.text === 'string' && c.text.startsWith('NOT_FOUND:')))
67
+ throw new Error('WakeStartUnavailable');
55
68
  return parsed(result);
56
69
  };
57
70
  const superseded = () => {
58
- if (kind !== 'claude' || !b)
71
+ if (kind !== 'claude' || !b || !catalogAdmitted)
59
72
  return false;
60
73
  try {
61
74
  return supersededCatalog(b, privateRead(catalogFile(kind, b.owner)));
@@ -75,15 +88,20 @@ export async function monitor(kind) {
75
88
  while (!stopped) {
76
89
  if (superseded())
77
90
  break;
78
- if (b ? processIdentity(b.owner) !== b.start : kind === 'claude' && !cheapAlive(parent)) {
91
+ if (ownerEnded()) {
79
92
  ended = true;
80
93
  break;
81
94
  }
82
95
  let bindingReady = false, activityChanged = false;
83
96
  try {
84
97
  if (!enrolled(kind)) {
98
+ if (partial()) {
99
+ await pause(2000);
100
+ continue;
101
+ }
85
102
  await drop(true);
86
103
  b = undefined;
104
+ catalogAdmitted = false;
87
105
  if (kind === 'codex')
88
106
  break;
89
107
  await pause(2000);
@@ -93,12 +111,20 @@ export async function monitor(kind) {
93
111
  if (b?.id !== next.id) {
94
112
  await drop(true);
95
113
  b = next;
114
+ catalogAdmitted = false;
96
115
  lastActivity = activityStamp(b);
97
116
  errors = 0;
98
117
  }
99
118
  else
100
119
  b = next;
101
- if (blocked === generation(b.enrollment)) {
120
+ if (dedupBinding !== b.id) {
121
+ dedupBinding = b.id;
122
+ attempted.clear();
123
+ delivered.clear();
124
+ unfinished.clear();
125
+ unavailable = undefined;
126
+ }
127
+ if (blocked === generation(b.enrollment) || unavailable === b.id) {
102
128
  await pause(2000);
103
129
  continue;
104
130
  }
@@ -106,8 +132,12 @@ export async function monitor(kind) {
106
132
  if (superseded())
107
133
  break;
108
134
  if (kind === 'claude') {
109
- if (!registered)
135
+ // A foreign digest has no temporal order until this binding admitted ours.
136
+ // Admission survives remote registration loss, but never a binding change.
137
+ if (!registered) {
110
138
  await waitCatalog(b);
139
+ catalogAdmitted = true;
140
+ }
111
141
  else if (!validCatalog(b, privateRead(catalogFile(kind, b.owner))))
112
142
  throw new Error('NativeCatalogNotReady');
113
143
  }
@@ -146,11 +176,17 @@ export async function monitor(kind) {
146
176
  continue;
147
177
  if (pending.connection_id !== b.id || pending.agent_id !== b.enrollment.agentId || pending.workspace_id !== b.enrollment.workspaceId || !Array.isArray(pending.events))
148
178
  throw new Error('WakeIdentityMismatch');
149
- for (const item of pending.unhandled ?? []) {
179
+ // Validate the whole poll before any attempt; a rotated offer is the same
180
+ // logical event, not permission to add another native turn.
181
+ const unfinishedItems = (pending.unhandled ?? []).map((item) => ({ item, line: unfinishedLine(item) }));
182
+ const events = new Map();
183
+ for (const event of pending.events)
184
+ events.set(event.event_id, { event, line: wakeLine(event) });
185
+ for (const { item, line } of unfinishedItems) {
150
186
  const key = [item.event_id, item.claim_id, item.owned].join(':');
151
187
  if (unfinished.has(key))
152
188
  continue;
153
- const line = unfinishedLine(item), executable = kind === 'codex' ? queueExecutable(b.runtime) : '';
189
+ const executable = kind === 'codex' ? queueExecutable(b.runtime) : '';
154
190
  unfinished.add(key);
155
191
  try {
156
192
  if (kind === 'codex')
@@ -161,32 +197,39 @@ export async function monitor(kind) {
161
197
  catch (error) {
162
198
  if (error instanceof Error && error.message === 'QueueNotStarted')
163
199
  unfinished.delete(key);
200
+ else
201
+ await call('checkin', { state: 'delivery_failed' }).catch(() => undefined);
164
202
  throw error;
165
203
  }
166
204
  }
167
- for (const event of pending.events) {
168
- if (stopped || !alive(b))
169
- break;
170
- const line = wakeLine(event);
171
- if (!delivered.has(event.offer_id)) {
172
- const executable = kind === 'codex' ? queueExecutable(b.runtime) : '';
173
- // Validation failures are not delivery attempts. Ambiguous queue failures
174
- // are never replayed for this offer.
175
- delivered.add(event.offer_id);
176
- try {
177
- if (kind === 'codex')
178
- await queueThread(b.session, line, executable);
179
- else
205
+ const fresh = [...events.values()].filter(({ event }) => !attempted.has(event.event_id));
206
+ if (fresh.length && !stopped && alive(b)) {
207
+ const executable = kind === 'codex' ? queueExecutable(b.runtime) : '';
208
+ for (const { event } of fresh)
209
+ attempted.add(event.event_id);
210
+ try {
211
+ if (kind === 'codex')
212
+ await queueThread(b.session, fresh.map(({ line }) => line).join('\n'), executable);
213
+ else
214
+ for (const { event, line } of fresh) {
180
215
  process.stdout.write(line + '\n');
181
- }
182
- catch (error) {
183
- if (error instanceof Error && error.message === 'QueueNotStarted')
184
- delivered.delete(event.offer_id);
185
- throw error;
186
- }
216
+ delivered.add(event.event_id);
217
+ }
218
+ for (const { event } of fresh)
219
+ delivered.add(event.event_id);
220
+ }
221
+ catch (error) {
222
+ if (error instanceof Error && error.message === 'QueueNotStarted')
223
+ for (const { event } of fresh)
224
+ attempted.delete(event.event_id);
225
+ else
226
+ await call('checkin', { state: 'delivery_failed' }).catch(() => undefined);
227
+ throw error;
187
228
  }
188
- await call('receipt', { event_id: event.event_id, offer_id: event.offer_id, stage: 'transport' });
189
229
  }
230
+ for (const { event } of events.values())
231
+ if (delivered.has(event.event_id))
232
+ await call('receipt', { event_id: event.event_id, offer_id: event.offer_id, stage: 'transport' });
190
233
  errors = 0;
191
234
  // Bound immediate results (including legacy-wait/unhandled-only servers).
192
235
  await pause(1000);
@@ -198,7 +241,7 @@ export async function monitor(kind) {
198
241
  continue;
199
242
  if (activityChanged)
200
243
  continue;
201
- if (b ? processIdentity(b.owner) !== b.start : kind === 'claude' && !cheapAlive(parent)) {
244
+ if (ownerEnded()) {
202
245
  ended = true;
203
246
  break;
204
247
  }
@@ -217,8 +260,13 @@ export async function monitor(kind) {
217
260
  invalid = true;
218
261
  }
219
262
  if (!invalid && !available) {
263
+ if (partial()) {
264
+ await pause(2000);
265
+ continue;
266
+ }
220
267
  await drop(true);
221
268
  b = undefined;
269
+ catalogAdmitted = false;
222
270
  errors = 0;
223
271
  if (kind === 'codex')
224
272
  break;
@@ -228,6 +276,7 @@ export async function monitor(kind) {
228
276
  if (invalid || !bindingReady || !bindingLive) {
229
277
  await drop(false);
230
278
  b = undefined;
279
+ catalogAdmitted = false;
231
280
  if (errors === 0)
232
281
  diagnose(error instanceof Error && error.message === 'RuntimeRestartRequired' ? RESTART_RUNTIME : 'AgentMesh local listener state unavailable; retrying.', error);
233
282
  errors++;
@@ -237,6 +286,12 @@ export async function monitor(kind) {
237
286
  const reason = error instanceof Error ? error.message : '';
238
287
  if (!b)
239
288
  continue;
289
+ if (reason === 'WakeStartUnavailable') {
290
+ unavailable = b.id;
291
+ diagnose('AgentMesh listener unavailable: this binding was closed or rejected; waiting for a new trusted session or enrollment.', error);
292
+ await drop(false);
293
+ continue;
294
+ }
240
295
  if (reason === 'ReconnectRequired') {
241
296
  blocked = generation(b.enrollment);
242
297
  process.stderr.write('AgentMesh approval expired or was revoked. Re-run Connect; this folder is offline. ' + terminalDiagnostic(error, 'plugin-monitor.js', 'monitor') + '\n');
@@ -271,17 +326,14 @@ export async function monitor(kind) {
271
326
  abort?.abort();
272
327
  let close = ended;
273
328
  try {
274
- close = close || !!b && !alive(b);
329
+ close = close || !!b && !partial() && !alive(b);
275
330
  }
276
331
  catch { /* Invalid local state is recoverable, not an explicit close. */ }
277
332
  await drop(close);
278
- if (kind === 'codex' && b) {
279
- const file = pollerFile(b.owner), r = privateRead(file);
333
+ if (kind === 'codex' && owner) {
334
+ const file = pollerFile(owner), r = privateRead(file);
280
335
  if (r?.pid === process.pid && r.start === processIdentity(process.pid)) {
281
- if (r.runtime)
282
- writeAtomic(file, { ...r, pid: 0, start: '', session: ended ? '' : r.session });
283
- else
284
- fs.rmSync(file, { force: true });
336
+ writeAtomic(file, { ...r, starting: false, pid: 0, start: '', session: ended ? '' : r.session });
285
337
  }
286
338
  }
287
339
  for (const sig of ['SIGINT', 'SIGTERM', 'SIGHUP'])
@@ -5,6 +5,7 @@ import { execFileSync } from 'node:child_process';
5
5
  import { createInterface } from 'node:readline';
6
6
  import { privateRoot, privateRead, locked } from './plugin-storage.js';
7
7
  import { writeAtomic } from './wake-storage.js';
8
+ import { RESOURCE } from './oauth-client.js';
8
9
  export const CONNECT_RULES = ['whoami', 'terminal_wake_read', 'terminal_wake_complete', 'post_message', 'post_conversation_message'].map(name => 'mcp__plugin_agentmesh_agentmesh__' + name);
9
10
  const hash = (bytes) => createHash('sha256').update(bytes).digest('hex');
10
11
  const recordFile = (e) => { if (!['claude', 'codex'].includes(e.client) || !/^[a-f0-9]{64}$/.test(e.folderId))
@@ -135,6 +136,8 @@ function recover(e) {
135
136
  export async function grantPermissions(e, file) {
136
137
  return locked(privateRoot(), 'permissions-' + hash(file), async () => {
137
138
  const previous = privateRead(recordFile(e));
139
+ if (e.installed && (!previous || previous.retired || previous.profile !== e.profile || previous.agentId !== e.agentId || previous.workspaceId !== e.workspaceId || (previous.generation ?? hash(JSON.stringify([previous.profile, previous.agentId, previous.workspaceId]))) !== (e.generation ?? hash(JSON.stringify([e.profile, e.agentId, e.workspaceId]))) || (previous.resource ?? RESOURCE) !== (e.resource ?? RESOURCE)))
140
+ throw new Error('EnrollmentChanged');
138
141
  if (previous?.permissions && previous.permissions.path !== file)
139
142
  throw new Error('PermissionScopeChanged');
140
143
  const current = { ...e, permissions: previous?.permissions ? { ...previous.permissions, consent: true } : { path: file, consent: true, added: [] } };
@@ -155,8 +158,9 @@ export async function grantPermissions(e, file) {
155
158
  });
156
159
  }
157
160
  export async function completeEnrollment(e) {
158
- const update = async () => { const current = privateRead(recordFile(e)); if (!current || current.retired || current.profile !== e.profile || current.agentId !== e.agentId)
159
- throw new Error('EnrollmentChanged'); save({ ...current, installed: true }); };
161
+ const generation = (value) => value.generation ?? hash(JSON.stringify([value.profile, value.agentId, value.workspaceId]));
162
+ const update = async () => { const current = privateRead(recordFile(e)); if (!current || current.retired || current.profile !== e.profile || current.agentId !== e.agentId || current.workspaceId !== e.workspaceId || generation(current) !== generation(e) || (current.resource ?? RESOURCE) !== (e.resource ?? RESOURCE))
163
+ throw new Error('EnrollmentChanged'); save({ ...current, ...e, permissions: current.permissions, installed: true }); };
160
164
  if (e.permissions)
161
165
  await locked(privateRoot(), 'permissions-' + hash(e.permissions.path), update);
162
166
  else
@@ -2,7 +2,7 @@ import { serveStdio, StdioServerTransport } from '@modelcontextprotocol/server/s
2
2
  import { buildServer } from './server.js';
3
3
  import { MCP_INSTRUCTIONS } from './contract.js';
4
4
  import { HOSTED_TOOL_NAMES } from './schemas.js';
5
- import { currentBinding, currentHost, alive, nativeIdentity, catalogServed } from './plugin-session.js';
5
+ import { currentBinding, currentHost, alive, nativeIdentity, catalogServed, bootstrapCodex } from './plugin-session.js';
6
6
  import { savedOAuth } from './oauth-client.js';
7
7
  import { RESTART_RUNTIME } from './terminal-runtime.js';
8
8
  import { retireProfile } from './plugin-permissions.js';
@@ -60,12 +60,15 @@ export async function proxy(kind) {
60
60
  });
61
61
  const transport = new StdioServerTransport(), send = transport.send.bind(transport);
62
62
  let cleanup;
63
- transport.send = async (message) => { await send(message); if (kind === 'claude' && 'result' in message && message.result && typeof message.result === 'object' && 'tools' in message.result) {
63
+ transport.send = async (message) => { await send(message); if ('result' in message && message.result && typeof message.result === 'object' && 'tools' in message.result) {
64
64
  try {
65
- cleanup = catalogServed(await nativeIdentity(kind));
65
+ if (kind === 'claude')
66
+ cleanup = catalogServed(await nativeIdentity(kind));
67
+ else
68
+ await bootstrapCodex();
66
69
  }
67
70
  catch (error) {
68
- process.stderr.write(RESTART_RUNTIME + ' ' + terminalDiagnostic(error, 'plugin-proxy.js', 'catalogServed') + '\n');
71
+ process.stderr.write((kind === 'claude' ? RESTART_RUNTIME : 'AgentMesh native root identity unavailable; trust hooks and send a message to establish this session.') + ' ' + terminalDiagnostic(error, 'plugin-proxy.js', 'catalogServed') + '\n');
69
72
  }
70
73
  } };
71
74
  const close = () => cleanup?.();