@agentmesh-md/mcp-server 0.2.2 → 0.3.3

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.
Files changed (45) hide show
  1. package/README.md +127 -0
  2. package/dist/client.js +16 -5
  3. package/dist/codex-hooks.js +142 -0
  4. package/dist/connect.js +77 -205
  5. package/dist/context.js +7 -0
  6. package/dist/contract.js +5 -1
  7. package/dist/errors.js +0 -55
  8. package/dist/index.js +33 -7
  9. package/dist/legacy.js +2 -66
  10. package/dist/oauth-client.js +128 -26
  11. package/dist/plugin-install.js +97 -0
  12. package/dist/plugin-monitor.js +292 -0
  13. package/dist/plugin-permissions.js +212 -0
  14. package/dist/plugin-proxy.js +75 -0
  15. package/dist/plugin-session.js +381 -0
  16. package/dist/plugin-storage.js +94 -0
  17. package/dist/plugin-target.js +16 -0
  18. package/dist/schemas.js +8 -2
  19. package/dist/server.js +31 -5
  20. package/dist/session.js +118 -14
  21. package/dist/terminal-diagnostic.js +1 -1
  22. package/dist/terminal-runtime.js +149 -151
  23. package/dist/tool-annotations.js +57 -0
  24. package/dist/tools.js +36 -55
  25. package/dist/wake-storage.js +33 -49
  26. package/package.json +5 -4
  27. package/plugin-marketplace/.claude-plugin/marketplace.json +11 -0
  28. package/plugin-marketplace/plugins/agentmesh/.claude-plugin/plugin.json +23 -0
  29. package/plugin-marketplace/plugins/agentmesh/README.md +31 -0
  30. package/plugin-marketplace/plugins/agentmesh/hooks/codex.json +44 -0
  31. package/plugin-marketplace/plugins/agentmesh/hooks/hooks.json +44 -0
  32. package/plugin-marketplace/plugins/agentmesh/mcp.json +15 -0
  33. package/plugin-marketplace/plugins/agentmesh/monitors/monitors.json +7 -0
  34. package/plugin-marketplace/plugins/agentmesh/plugin.json +6 -0
  35. package/plugin-marketplace/plugins/agentmesh/release.json +1 -0
  36. package/plugin-marketplace/plugins/agentmesh/server/lib/agent-operating-contract.txt +120 -0
  37. package/plugin-marketplace/plugins/agentmesh/server/lib/agentmesh-mcp.js +39413 -0
  38. package/plugin-marketplace/plugins/agentmesh/server/package.json +4 -0
  39. package/plugin-marketplace/plugins/agentmesh/server/schemas/defs.json +121 -0
  40. package/plugin-marketplace/plugins/agentmesh/server/schemas/tools.json +1934 -0
  41. package/schemas/tools.json +591 -1
  42. package/dist/connect-bridge.js +0 -62
  43. package/dist/mentions.cjs +0 -22
  44. package/dist/wake-monitor.js +0 -117
  45. package/dist/wake.js +0 -521
package/dist/session.js CHANGED
@@ -7,6 +7,7 @@
7
7
  */
8
8
  import { execFileSync } from "node:child_process";
9
9
  import path from "node:path";
10
+ import fs from "node:fs";
10
11
  const MAX_DEPTH = 32;
11
12
  /** The process's own executable name and its parent pid. */
12
13
  function parentOf(pid) {
@@ -19,25 +20,128 @@ function parentOf(pid) {
19
20
  return null;
20
21
  }
21
22
  }
22
- /**
23
- * The pid of the nearest ancestor of `pid` whose executable is `claude`, or
24
- * null. AGENTMESH_WAKE_SESSION_PID overrides it (tests simulate separate
25
- * sessions with it; any same-user process could already read the queue files,
26
- * so the override grants nothing new).
27
- */
28
- export function findSessionPid(pid = process.pid) {
29
- const forced = process.env["AGENTMESH_WAKE_SESSION_PID"];
30
- if (forced !== undefined && /^\d+$/.test(forced))
31
- return Number(forced);
23
+ /** Native owner, never inferred from cwd or a globally recent session. */
24
+ export function nativeOwner(kind, pid = process.pid) {
32
25
  let current = pid;
33
- for (let depth = 0; depth < MAX_DEPTH; depth += 1) {
26
+ for (let depth = 0; depth < MAX_DEPTH; depth++) {
34
27
  const info = parentOf(current);
35
- if (info === null || info.ppid <= 1)
28
+ if (!info || info.ppid <= 1)
36
29
  return null;
37
30
  const parent = parentOf(info.ppid);
38
- if (parent !== null && path.basename(parent.comm) === "claude")
39
- return info.ppid;
31
+ if (parent) {
32
+ const name = path.basename(parent.comm).toLowerCase();
33
+ if (name === kind || name === kind + '.exe' || ['node', 'node.exe'].includes(name) && nodeEntry(info.ppid, kind))
34
+ return info.ppid;
35
+ }
40
36
  current = info.ppid;
41
37
  }
42
38
  return null;
43
39
  }
40
+ /** Verify Node's actual entry against the native CLI package bin, not node alone. */
41
+ function nodeEntry(pid, kind) {
42
+ try {
43
+ const args = execFileSync('ps', ['-ww', '-o', 'args=', '-p', String(pid)], { encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'] }).trim();
44
+ // Supported package launchers invoke node with their entry as argv[1].
45
+ // Do not accept eval/preload/unknown flag-based wrappers as native owners.
46
+ const entry = args.match(/^(?:"[^"]+"|'[^']+'|\S+)\s+("[^"]+"|'[^']+'|\S+)/)?.[1]?.replace(/^(["'])(.*)\1$/, '$2');
47
+ if (!entry || !path.isAbsolute(entry))
48
+ return;
49
+ const real = fs.realpathSync(entry);
50
+ let dir = path.dirname(real);
51
+ for (let depth = 0; depth < 12; depth++) {
52
+ const file = path.join(dir, 'package.json');
53
+ if (fs.existsSync(file)) {
54
+ const pkg = JSON.parse(fs.readFileSync(file, 'utf8'));
55
+ if (pkg.name === (kind === 'claude' ? '@anthropic-ai/claude-code' : '@openai/codex')) {
56
+ const bin = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin?.[kind];
57
+ if (typeof bin === 'string' && fs.realpathSync(path.resolve(dir, bin)) === real)
58
+ return real;
59
+ return;
60
+ }
61
+ }
62
+ const next = path.dirname(dir);
63
+ if (next === dir)
64
+ break;
65
+ dir = next;
66
+ }
67
+ }
68
+ catch { /* Unreadable or non-package Node processes stay unsupported. */ }
69
+ }
70
+ export function nativeExecutable(pid, kind) {
71
+ const info = parentOf(pid);
72
+ if (!info)
73
+ throw new Error('NativeOwnerEnded');
74
+ const name = path.basename(info.comm).toLowerCase();
75
+ if (['node', 'node.exe'].includes(name)) {
76
+ const entry = nodeEntry(pid, kind);
77
+ if (entry)
78
+ return entry;
79
+ throw new Error('UnsupportedNodeNativeEntry');
80
+ }
81
+ let executable = path.isAbsolute(info.comm) && fs.existsSync(info.comm) ? info.comm : '';
82
+ if (!executable) {
83
+ try {
84
+ const lines = execFileSync('lsof', ['-a', '-p', String(pid), '-d', 'txt', '-Fn'], { encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'] }).split('\n');
85
+ const candidates = [...new Set(lines.filter(line => line.startsWith('n/')).map(line => line.slice(1).replace(/ \(deleted\)$/, '')).filter(file => fs.existsSync(file) && [kind, kind + '.exe'].includes(path.basename(file).toLowerCase())))];
86
+ if (candidates.length === 1)
87
+ executable = candidates[0];
88
+ }
89
+ catch { /* An unreadable executable stays unsupported. */ }
90
+ }
91
+ if (!path.isAbsolute(executable) || ![kind, kind + '.exe'].includes(path.basename(executable).toLowerCase()))
92
+ throw new Error('UnsupportedUnreadableNativeExecutable');
93
+ return executable;
94
+ }
95
+ export function unsupportedDesktopOwner(pid, executable) {
96
+ const desktop = /\/(?:ChatGPT|Claude|Codex|Cursor|Visual Studio Code)\.app\/|\/app-server-daemon\//;
97
+ if (desktop.test(executable))
98
+ return true;
99
+ let current = pid;
100
+ for (let depth = 0; depth < MAX_DEPTH; depth++) {
101
+ const info = parentOf(current);
102
+ if (!info)
103
+ return false;
104
+ if (desktop.test(info.comm))
105
+ return true;
106
+ if (info.ppid <= 1)
107
+ return false;
108
+ current = info.ppid;
109
+ }
110
+ return false;
111
+ }
112
+ /** Identity of a command on disk, separate from the running owner's image. */
113
+ export function executableIdentity(file) {
114
+ const s = fs.statSync(file, { bigint: true });
115
+ if (!s.isFile())
116
+ throw new Error('UnsupportedUnreadableNativeExecutable');
117
+ fs.accessSync(file, fs.constants.X_OK);
118
+ return [s.dev, s.ino, s.size, s.mtimeNs].join(':');
119
+ }
120
+ /** Never validate a replacement PATH/comm image as the still-running owner. */
121
+ export function nativeImageIdentity(pid, kind, file) {
122
+ const identity = executableIdentity(file), info = parentOf(pid);
123
+ if (!info)
124
+ throw new Error('NativeOwnerEnded');
125
+ if (['node', 'node.exe'].includes(path.basename(info.comm).toLowerCase())) {
126
+ if (nodeEntry(pid, kind) !== fs.realpathSync(file))
127
+ throw new Error('UnsupportedNodeNativeEntry');
128
+ return identity;
129
+ }
130
+ const stat = fs.statSync(file, { bigint: true });
131
+ const lines = execFileSync('lsof', ['-a', '-p', String(pid), '-d', 'txt', '-FfiD'], { encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'] }).split('\n');
132
+ let dev = '', ino = '';
133
+ const matched = () => dev.toLowerCase().replace(/^0x/, '').replace(/^0+/, '') === stat.dev.toString(16).replace(/^0+/, '') && ino === String(stat.ino);
134
+ for (const line of [...lines, 'fEND']) {
135
+ if (line.startsWith('f')) {
136
+ if (matched())
137
+ return identity;
138
+ dev = '';
139
+ ino = '';
140
+ }
141
+ else if (line.startsWith('D'))
142
+ dev = line.slice(1);
143
+ else if (line.startsWith('i'))
144
+ ino = line.slice(1);
145
+ }
146
+ throw new Error('UnsupportedUnreadableNativeExecutable');
147
+ }
@@ -3,7 +3,7 @@
3
3
  export function terminalDiagnostic(error, file, fn) {
4
4
  const name = error instanceof Error ? error.constructor.name : 'Error';
5
5
  const safe = ['Error', 'TypeError', 'RangeError', 'SyntaxError', 'UnauthorizedError', 'StreamableHTTPError'];
6
- const frame = (error instanceof Error ? error.stack : '')?.match(/at (?:async )?(ownerDirectory|credentialFile|runtimeVersion|connect|bridge|brokerRequest|openOAuth|codexRuntime|queue|launch) \(.*\/(connect(?:-bridge)?|oauth-client|terminal-runtime|index)\.js:(\d+):\d+\)/);
6
+ const frame = (error instanceof Error ? error.stack : '')?.match(/at (?:async )?(ownerDirectory|credentialFile|runtimeVersion|connect|bridge|brokerRequest|openOAuth|codexRuntime|queue|launch|safePath|read|commit|recover|grantPermissions|releasePermissions|retireEnrollments|permissionPath|currentBinding|proxy|monitor|installPlugin|installCodexHooks|ensureWatcher|supervise|command) \(.*\/(connect(?:-bridge)?|oauth-client|terminal-runtime|index|plugin-permissions|plugin-proxy|plugin-session|plugin-monitor|plugin-install|plugin-supervisor|codex-hooks)\.js:(\d+):\d+\)/);
7
7
  const here = new Error().stack?.split('\n')[2]?.match(/:(\d+):\d+\)?$/)?.[1] ?? '0';
8
8
  return `${safe.includes(name) ? name : 'DependencyError'} at ${frame ? frame[2] + '.js' : file}:${frame?.[1] ?? fn}:${frame?.[3] ?? here}`;
9
9
  }
@@ -1,177 +1,175 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
- import net from 'node:net';
4
- import { spawn, execFileSync } from 'node:child_process';
5
- import WebSocket from 'ws';
6
- import { writeAtomic, readJson, pidAlive } from './wake-storage.js';
3
+ import os from 'node:os';
4
+ import { nativeExecutable, nativeImageIdentity, executableIdentity, unsupportedDesktopOwner } from './session.js';
5
+ import { execFileSync } from 'node:child_process';
7
6
  export const SUPPORTED = { claude: '2.1.322', codex: '0.166.0' };
8
- export const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
9
- export function runtimeVersion(client) {
7
+ /** Resolve once: installation must use this same absolute executable. */
8
+ export function installerRuntime(client) {
9
+ let executable;
10
+ for (const dir of (process.env.PATH ?? '').split(path.delimiter)) {
11
+ const candidate = path.resolve(dir || '.', client);
12
+ try {
13
+ if (!fs.statSync(candidate).isFile())
14
+ continue;
15
+ fs.accessSync(candidate, fs.constants.X_OK);
16
+ executable = fs.realpathSync(candidate);
17
+ break;
18
+ }
19
+ catch { /* Follow native PATH lookup for missing/nonexecutable entries. */ }
20
+ }
21
+ if (!executable) {
22
+ process.stderr.write(`AgentMesh wakes need ${client} ${SUPPORTED[client]} or newer with plugin support. Install that supported client and run Connect again.\n`);
23
+ throw new Error('RuntimeMissing');
24
+ }
25
+ return { executable, version: runtimeVersion(client, executable, true) };
26
+ }
27
+ export function runtimeVersion(client, executable = client, requireCapabilities = false) {
10
28
  let output;
11
29
  try {
12
- output = execFileSync(client, ['--version'], { encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'] });
30
+ output = execFileSync(executable, ['--version'], { encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'] });
13
31
  }
14
32
  catch {
15
33
  process.stderr.write(`AgentMesh wakes need ${client} ${SUPPORTED[client]}. Install that supported client and run Connect again.\n`);
16
34
  throw new Error('RuntimeMissing');
17
35
  }
18
36
  const version = output.match(/\b(\d+\.\d+\.\d+)\b/)?.[1];
19
- if (version !== SUPPORTED[client]) {
20
- process.stderr.write(`AgentMesh wakes need ${client} ${SUPPORTED[client]}. Install that supported version and run Connect again.\n`);
37
+ // Atlas/LUX: Claude 2.1.322 is the monitor-support floor; 2.1.323 is
38
+ // the current candidate. Newer owners must also pass native capability checks.
39
+ const supported = version && version.split('.').map(Number).reduce((r, n, i) => r || Math.sign(n - Number(SUPPORTED[client].split('.')[i])), 0) >= 0;
40
+ if (!supported) {
41
+ process.stderr.write(`AgentMesh wakes need ${client} ${SUPPORTED[client]} or newer with plugin${client === 'codex' ? ' and queue --thread' : ''} support. Install a supported ${client} and run Connect again.\n`);
21
42
  throw new Error('UnsupportedRuntime');
22
43
  }
44
+ if (requireCapabilities || version !== SUPPORTED[client]) {
45
+ try {
46
+ const help = execFileSync(executable, ['plugin', '--help'], { encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'] });
47
+ if (!/marketplace/.test(help) || !/(install|add)/.test(help))
48
+ throw new Error();
49
+ if (client === 'codex') {
50
+ const queue = execFileSync(executable, ['queue', '--help'], { encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'] });
51
+ if (!queue.includes('--thread') || !queue.includes('--message'))
52
+ throw new Error();
53
+ }
54
+ }
55
+ catch {
56
+ process.stderr.write(`AgentMesh wakes need ${client} ${SUPPORTED[client]} or newer with plugin${client === 'codex' ? ' and queue --thread' : ''} support. This executable lacks the required capability; install a supported client and run Connect again.\n`);
57
+ throw new Error('UnsupportedRuntime');
58
+ }
59
+ }
23
60
  return version;
24
61
  }
25
- function exitOf(child) {
26
- return new Promise((resolve, reject) => { child.once('error', () => reject(new Error('RuntimeStartFailed'))); child.once('exit', code => resolve(code ?? 1)); });
62
+ export const RESTART_RUNTIME = 'AgentMesh cannot verify this running client after its update. Restart this session to restore AgentMesh tools and wakes.';
63
+ export function supportedVersion(kind, version) {
64
+ return typeof version === 'string' && /^\d+\.\d+\.\d+$/.test(version) && version.split('.').map(Number).reduce((r, n, i) => r || Math.sign(n - Number(SUPPORTED[kind].split('.')[i])), 0) >= 0;
27
65
  }
28
- async function stopOwned(child) {
29
- if (child.exitCode !== null || child.signalCode !== null)
66
+ export function retainedRuntime(value, kind, owner, start, folder) {
67
+ if (value === undefined)
30
68
  return;
31
- child.kill('SIGTERM');
32
- await Promise.race([new Promise(resolve => child.once('exit', () => resolve())), delay(3000)]);
33
- if (child.exitCode === null && child.signalCode === null)
34
- child.kill('SIGKILL');
69
+ const p = value;
70
+ if (!p || p.schema !== 1 || p.client !== kind || p.owner !== owner || p.start !== start || p.folder !== folder || !supportedVersion(kind, p.version) || !['image', 'claude-session'].includes(p.source) || p.source === 'claude-session' && kind !== 'claude' || p.source === 'image' && (typeof p.executable !== 'string' || !path.isAbsolute(p.executable) || typeof p.image !== 'string'))
71
+ throw new Error('RuntimeRestartRequired');
72
+ return p;
35
73
  }
36
- // Claude's product monitor consumes the same atomic queue/session binding as
37
- // legacy key polling. Only the launcher-owned child PID is written into it.
38
- export function claudeRuntime({ runDir, entry, bindingId, cwd }) {
39
- const plugin = path.join(runDir, 'plugin');
40
- fs.mkdirSync(path.join(plugin, '.claude-plugin'), { recursive: true, mode: 0o700 });
41
- const broker = path.join(runDir, 'broker.sock');
42
- const root = path.join(runDir, 'wake');
43
- const dir = path.join(root, bindingId);
44
- fs.mkdirSync(path.join(dir, 'queue'), { recursive: true, mode: 0o700 });
45
- writeAtomic(path.join(plugin, '.claude-plugin', 'plugin.json'), {
46
- name: 'agentmesh-terminal', version: '0.2.2', description: 'AgentMesh tools and terminal wakes',
47
- mcpServers: { agentmesh: { command: process.execPath, args: [entry, 'bridge', broker] } },
48
- experimental: { monitors: [{ name: 'agentmesh-terminal', command: `${JSON.stringify(process.execPath)} ${JSON.stringify(path.join(path.dirname(entry), 'wake-monitor.js'))} ${JSON.stringify(root)}`, when: 'always', description: 'AgentMesh own-session wake notifications' }] },
49
- });
50
- let child;
51
- let exit;
52
- return { bindingId,
53
- alive: () => !!child?.pid && child.exitCode === null && child.signalCode === null && pidAlive(child.pid),
54
- deliver: async (text) => {
55
- // Backend remains pending until the model calls its receipt tool.
56
- const key = JSON.parse(text.slice(text.indexOf('{')));
57
- writeAtomic(path.join(dir, 'queue', `${key.event_id}.json`), { key: key.event_id, kind: 'notice', content: text,
58
- meta: {}, queued_at: new Date().toISOString() });
59
- },
60
- attach: async () => {
61
- child = spawn('claude', ['--plugin-dir', plugin], { cwd, stdio: 'inherit' });
62
- exit = exitOf(child);
63
- if (!child.pid)
64
- throw new Error('RuntimeStartFailed');
65
- writeAtomic(path.join(dir, 'mode.json'), { mode: 'poll', pid: process.pid, session_pid: child.pid, terminal: true });
66
- return exit;
67
- },
68
- close: async () => { if (child)
69
- await stopOwned(child); }, };
74
+ function ownerStart(pid, utc = false) {
75
+ return execFileSync('ps', ['-o', 'lstart=', '-p', String(pid)], { encoding: 'utf8', timeout: 2000, stdio: ['ignore', 'pipe', 'ignore'], ...(utc ? { env: { ...process.env, TZ: 'UTC', LC_ALL: 'C' } } : {}) }).trim();
70
76
  }
71
- class CodexRpc {
72
- ws;
73
- serial = 0;
74
- pending = new Map();
75
- constructor(ws) {
76
- this.ws = ws;
77
- ws.on('message', raw => {
78
- let message;
77
+ /** Read only Claude's non-secret per-process report; never scan or read *.key. */
78
+ function claudeProcessVersion(pid, start) {
79
+ const config = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude'), dir = path.join(config, 'sessions'), file = path.join(dir, String(pid) + '.json');
80
+ // This producer writes0644 metadata under0700 sessions, not a secret0600 file.
81
+ for (const component of [config, dir]) {
82
+ const s = fs.lstatSync(component);
83
+ if (!s.isDirectory() || s.isSymbolicLink() || s.uid !== process.getuid?.() || (s.mode & 0o022) !== 0)
84
+ throw new Error('RuntimeRestartRequired');
85
+ }
86
+ const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
87
+ try {
88
+ const s = fs.fstatSync(fd);
89
+ if (!s.isFile() || s.uid !== process.getuid?.() || (s.mode & 0o022) !== 0 || s.size > 65536)
90
+ throw new Error('RuntimeRestartRequired');
91
+ const p = JSON.parse(fs.readFileSync(fd, 'utf8'));
92
+ if (p.pid !== pid || p.entrypoint !== 'cli' || p.procStart !== ownerStart(pid, true) || ownerStart(pid) !== start || !supportedVersion('claude', p.version))
93
+ throw new Error('RuntimeRestartRequired');
94
+ return p.version;
95
+ }
96
+ finally {
97
+ fs.closeSync(fd);
98
+ }
99
+ }
100
+ /** Validate the running owner once; its path may disappear during auto-update. */
101
+ export async function ownerRuntimeProof(kind, pid, start, folder) {
102
+ if (unsupportedDesktopOwner(pid, ''))
103
+ throw new Error('UnsupportedDesktopIDEHost');
104
+ let executable, image;
105
+ try {
106
+ executable = nativeExecutable(pid, kind);
107
+ image = nativeImageIdentity(pid, kind, executable);
108
+ }
109
+ catch (error) {
110
+ // Arbitrary Node launchers must not acquire native status through metadata.
111
+ if (error instanceof Error && error.message === 'UnsupportedNodeNativeEntry')
112
+ throw error;
113
+ if (kind === 'claude')
79
114
  try {
80
- message = JSON.parse(String(raw));
115
+ return { schema: 1, client: kind, owner: pid, start, folder, version: claudeProcessVersion(pid, start), source: 'claude-session' };
81
116
  }
82
- catch {
83
- return;
84
- }
85
- if (typeof message.id !== 'number')
86
- return;
87
- const waiter = this.pending.get(message.id);
88
- if (!waiter)
89
- return;
90
- this.pending.delete(message.id);
91
- clearTimeout(waiter.timer);
92
- if (message.error)
93
- waiter.reject(new Error('CodexRpcRejected'));
94
- else
95
- waiter.resolve(message.result);
96
- });
97
- ws.on('close', () => { for (const waiter of this.pending.values()) {
98
- clearTimeout(waiter.timer);
99
- waiter.reject(new Error('CodexDisconnected'));
100
- } this.pending.clear(); });
101
- ws.on('error', () => undefined);
102
- }
103
- request(method, params) {
104
- const id = ++this.serial;
105
- return new Promise((resolve, reject) => {
106
- const timer = setTimeout(() => { this.pending.delete(id); reject(new Error('CodexRpcTimeout')); }, 15_000);
107
- this.pending.set(id, { resolve, reject, timer });
108
- this.ws.send(JSON.stringify({ id, method, params }));
109
- });
110
- }
111
- notify(method) { this.ws.send(JSON.stringify({ method })); }
112
- close() { this.ws.close(); }
113
- }
114
- export async function codexRuntime({ runDir, profile, entry, bindingId, cwd, agentId, workspaceId }) {
115
- const endpoint = `unix://${path.join(runDir, 'codex.sock')}`;
116
- const config = ['-c', `mcp_servers.agentmesh.command=${JSON.stringify(process.execPath)}`,
117
- '-c', `mcp_servers.agentmesh.args=${JSON.stringify([entry, 'bridge', path.join(runDir, 'broker.sock')])}`];
118
- const server = spawn('codex', ['app-server', '--listen', endpoint, ...config], { cwd, stdio: 'ignore' });
119
- let serverError = false;
120
- server.once('error', () => { serverError = true; });
121
- let tui;
122
- let rpc;
117
+ catch { /* A missing/mismatched producer record cannot be repaired by PATH. */ }
118
+ throw new Error('RuntimeRestartRequired');
119
+ }
120
+ if (unsupportedDesktopOwner(pid, executable))
121
+ throw new Error('UnsupportedDesktopIDEHost');
122
+ const run = (args) => execFileSync(executable, args, { encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'] });
123
+ let version;
123
124
  try {
124
- for (let i = 0; i < 100 && !fs.existsSync(path.join(runDir, 'codex.sock')); i++) {
125
- if (serverError || server.exitCode !== null)
126
- throw new Error('CodexAppServerFailed');
127
- await delay(100);
128
- }
129
- const ws = new WebSocket('ws://localhost/', { createConnection: () => net.connect(path.join(runDir, 'codex.sock')), handshakeTimeout: 5000, maxPayload: 1024 * 1024 });
130
- await new Promise((resolve, reject) => { ws.once('open', resolve); ws.once('error', () => reject(new Error('CodexSocketFailed'))); });
131
- rpc = new CodexRpc(ws);
132
- await rpc.request('initialize', { clientInfo: { name: 'agentmesh-terminal', version: '0.2.2' } });
133
- rpc.notify('initialized');
134
- const saved = readJson(path.join(profile, 'thread.json'));
135
- const resumed = saved?.agent_id === agentId && saved.workspace_id === workspaceId && saved.cwd === cwd && typeof saved.thread_id === 'string';
136
- const result = await rpc.request(resumed ? 'thread/resume' : 'thread/start', resumed ? { threadId: saved.thread_id, cwd } : { cwd, ephemeral: false });
137
- const thread = result.thread?.id;
138
- if (!/^[a-f0-9-]{36}$/.test(thread ?? ''))
139
- throw new Error('CodexThreadMissing');
140
- if (resumed && thread !== saved.thread_id)
141
- throw new Error('CodexThreadMismatch');
142
- writeAtomic(path.join(profile, 'thread.json'), { thread_id: thread, agent_id: agentId, workspace_id: workspaceId, cwd });
143
- // A fresh thread needs one persisted turn before a remote TUI can resume.
144
- // This is an explicit launcher start, never a wake starting a closed app.
145
- const firstTurn = new Promise((resolve) => { ws.on('message', raw => { try {
146
- const m = JSON.parse(String(raw));
147
- if (m.method === 'turn/completed' && m.params?.threadId === thread)
148
- resolve();
149
- }
150
- catch { } }); });
151
- const queue = async (text) => {
152
- if (!server.pid || server.exitCode !== null || server.signalCode !== null || !pidAlive(server.pid))
153
- throw new Error('CodexGenerationGone');
154
- await new Promise((resolve, reject) => {
155
- const command = spawn('codex', ['queue', '--remote', endpoint, '--thread', thread, '--message', text], { cwd, stdio: 'ignore' });
156
- const timer = setTimeout(() => { command.kill(); reject(new Error('CodexQueueTimeout')); }, 5000);
157
- command.once('error', () => { clearTimeout(timer); reject(new Error('CodexQueueFailed')); });
158
- command.once('exit', code => { clearTimeout(timer); code === 0 ? resolve() : reject(new Error('CodexQueueFailed')); });
159
- });
160
- };
161
- if (!resumed) {
162
- await queue('AgentMesh terminal tools are connected. Run whoami and get_my_instructions using the agentmesh connector. Verify your own agent identity before handling wake notifications. Wake acknowledgement means received, not completed.');
163
- await Promise.race([firstTurn, delay(30_000)]);
125
+ version = run(['--version']).match(/\b(\d+\.\d+\.\d+)\b/)?.[1];
126
+ }
127
+ catch {
128
+ throw new Error('RuntimeRestartRequired');
129
+ }
130
+ if (!supportedVersion(kind, version)) {
131
+ process.stderr.write(`AgentMesh actual ${kind} owner ${version ?? 'unknown'} is unsupported; minimum ${SUPPORTED[kind]}. This session is offline.\n`);
132
+ throw new Error('UnsupportedRuntime');
133
+ }
134
+ try {
135
+ const plugin = run(['plugin', '--help']);
136
+ if (!/marketplace/.test(plugin) || !/(install|add)/.test(plugin))
137
+ throw new Error('MissingPluginCapability');
138
+ if (kind === 'codex') {
139
+ const queue = run(['queue', '--help']);
140
+ if (!queue.includes('--thread') || !queue.includes('--message'))
141
+ throw new Error('MissingQueueCapability');
164
142
  }
165
- return { bindingId, alive: () => !!server.pid && server.exitCode === null && server.signalCode === null && pidAlive(server.pid)
166
- && (!tui || tui.exitCode === null && tui.signalCode === null), deliver: queue,
167
- attach: async () => { tui = spawn('codex', ['resume', '--remote', endpoint, thread, '--no-alt-screen'], { cwd, stdio: 'inherit' }); return exitOf(tui); },
168
- close: async () => { if (tui)
169
- await stopOwned(tui); rpc?.close(); await stopOwned(server); },
170
- };
171
143
  }
172
- catch (error) {
173
- rpc?.close();
174
- await stopOwned(server);
175
- throw error;
144
+ catch {
145
+ throw new Error('RuntimeRestartRequired');
146
+ }
147
+ // A replacement while probes ran invalidates their attribution to this owner.
148
+ if (nativeImageIdentity(pid, kind, executable) !== image || ownerStart(pid) !== start)
149
+ throw new Error('RuntimeRestartRequired');
150
+ return { schema: 1, client: kind, owner: pid, start, folder, version, source: 'image', executable, image };
151
+ }
152
+ export async function ownerRuntimeVersion(kind, pid) {
153
+ return (await ownerRuntimeProof(kind, pid, ownerStart(pid), '')).version;
154
+ }
155
+ /** Queue helper is a runnable command, never evidence of running-owner version. */
156
+ export function queueExecutable(proof) {
157
+ if (proof.client !== 'codex' || retainedRuntime(proof, 'codex', proof.owner, proof.start, proof.folder) !== proof || ownerStart(proof.owner) !== proof.start)
158
+ throw new Error('RuntimeRestartRequired');
159
+ const candidates = [proof.executable, ...(process.env.PATH ?? '').split(path.delimiter).map(dir => path.resolve(dir || '.', 'codex'))];
160
+ for (const candidate of candidates) {
161
+ if (!candidate)
162
+ continue;
163
+ try {
164
+ const real = fs.realpathSync(candidate), before = executableIdentity(real);
165
+ if (unsupportedDesktopOwner(proof.owner, real))
166
+ continue;
167
+ runtimeVersion('codex', real, true);
168
+ if (executableIdentity(real) !== before || ownerStart(proof.owner) !== proof.start)
169
+ throw new Error('RuntimeRestartRequired');
170
+ return real;
171
+ }
172
+ catch { /* Try another runnable command only after the actual owner is proven. */ }
176
173
  }
174
+ throw new Error('RuntimeRestartRequired');
177
175
  }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Accurate per-tool annotations for all tools.
3
+ *
4
+ * Semantics (MCP spec): `readOnlyHint` — the tool does not modify its
5
+ * environment; `destructiveHint` — the tool may perform DESTRUCTIVE (not
6
+ * merely additive) updates; `idempotentHint` — repeated calls with the same
7
+ * arguments have no ADDITIONAL effect on the environment; `openWorldHint` —
8
+ * the tool touches an open external world (all 9 tools operate on the closed
9
+ * AgentMesh workspace upstream, hence false everywhere).
10
+ *
11
+ * Write-tool rationale:
12
+ * - claim_card: CAS — a repeat claim either no-ops (same identity) or is a
13
+ * typed conflict that mutates nothing ⇒ idempotent, additive-only.
14
+ * - complete_card: claimant-only CAS — a repeat complete is a typed conflict
15
+ * whose CAS-miss branch is read-only ⇒ effect-idempotent, additive-only
16
+ * (the response is a conflict, but the ENVIRONMENT is unchanged — the
17
+ * hint speaks to environmental effect, per spec wording).
18
+ * - post_message / create_card: every invocation appends a NEW row by design
19
+ * (fresh Idempotency-Key per invocation) ⇒ NOT idempotent; additive-only.
20
+ *
21
+ * Serving these from ListTools is a one-line integration in server.ts
22
+ * (`annotations: TOOL_ANNOTATIONS[name]`) — server.ts is Seam B's file, so
23
+ * that wiring is FLAGGED to the integrator rather than edited here.
24
+ */
25
+ export const TOOL_ANNOTATIONS = {
26
+ terminal_wake_read: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
27
+ terminal_wake_complete: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
28
+ terminal_wake_pin: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
29
+ terminal_wake_start: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
30
+ terminal_wake_poll: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
31
+ terminal_wake_receipt: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
32
+ terminal_wake_checkin: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
33
+ read_board: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
34
+ read_channels: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
35
+ read_messages: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
36
+ list_asks: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
37
+ get_my_instructions: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
38
+ whoami: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
39
+ post_message: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
40
+ claim_card: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
41
+ complete_card: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
42
+ create_card: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
43
+ read_roster: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
44
+ list_conversations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
45
+ create_conversation: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
46
+ read_conversation_messages: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
47
+ post_conversation_message: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
48
+ edit_document: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
49
+ create_document: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
50
+ read_document: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
51
+ list_documents: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
52
+ resolve_ask: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
53
+ claim_ask: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
54
+ create_ask: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
55
+ assign_card: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
56
+ edit_card: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
57
+ };