@agentmesh-md/mcp-server 0.3.3 → 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.
@@ -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?.();