@agentmesh-md/mcp-server 0.2.2 → 0.3.4

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 +143 -4
  2. package/dist/client.js +16 -5
  3. package/dist/codex-hooks.js +142 -0
  4. package/dist/connect.js +75 -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 +41 -8
  9. package/dist/legacy.js +2 -66
  10. package/dist/oauth-client.js +131 -26
  11. package/dist/plugin-install.js +154 -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 +30 -5
  20. package/dist/session.js +118 -14
  21. package/dist/terminal-diagnostic.js +1 -1
  22. package/dist/terminal-runtime.js +96 -161
  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 +36 -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 +39419 -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 +1933 -0
  41. package/schemas/tools.json +592 -3
  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|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,112 @@
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';
7
- 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) {
10
- let output;
11
- try {
12
- output = execFileSync(client, ['--version'], { encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'] });
13
- }
14
- catch {
15
- process.stderr.write(`AgentMesh wakes need ${client} ${SUPPORTED[client]}. Install that supported client and run Connect again.\n`);
16
- throw new Error('RuntimeMissing');
17
- }
18
- 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`);
21
- throw new Error('UnsupportedRuntime');
3
+ import os from 'node:os';
4
+ import { nativeExecutable, nativeImageIdentity, executableIdentity, unsupportedDesktopOwner } from './session.js';
5
+ import { execFileSync } from 'node:child_process';
6
+ export class ClientExecutableMissing extends Error {
7
+ client;
8
+ constructor(client) {
9
+ super('ClientExecutableMissing');
10
+ this.client = client;
22
11
  }
23
- return version;
24
12
  }
25
- function exitOf(child) {
26
- return new Promise((resolve, reject) => { child.once('error', () => reject(new Error('RuntimeStartFailed'))); child.once('exit', code => resolve(code ?? 1)); });
13
+ /** Resolve once: installation must use this same absolute executable. */
14
+ export function installerRuntime(client) {
15
+ let executable;
16
+ for (const dir of (process.env.PATH ?? '').split(path.delimiter)) {
17
+ const candidate = path.resolve(dir || '.', client);
18
+ try {
19
+ if (!fs.statSync(candidate).isFile())
20
+ continue;
21
+ fs.accessSync(candidate, fs.constants.X_OK);
22
+ executable = fs.realpathSync(candidate);
23
+ break;
24
+ }
25
+ catch { /* Follow native PATH lookup for missing/nonexecutable entries. */ }
26
+ }
27
+ if (!executable)
28
+ throw new ClientExecutableMissing(client);
29
+ return { executable };
27
30
  }
28
- async function stopOwned(child) {
29
- if (child.exitCode !== null || child.signalCode !== null)
31
+ export const RESTART_RUNTIME = 'AgentMesh cannot verify this running client after its update. Restart this session to restore AgentMesh tools and wakes.';
32
+ export function retainedRuntime(value, kind, owner, start, folder) {
33
+ if (value === undefined)
30
34
  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');
35
+ const p = value;
36
+ if (!p || p.schema !== 1 || p.client !== kind || p.owner !== owner || p.start !== start || p.folder !== folder || !['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'))
37
+ throw new Error('RuntimeRestartRequired');
38
+ return typeof p.version === 'string' ? p : { ...p, version: 'unknown' };
35
39
  }
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); }, };
40
+ function ownerStart(pid, utc = false) {
41
+ 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
42
  }
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;
79
- try {
80
- message = JSON.parse(String(raw));
81
- }
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);
43
+ /** Read only Claude's non-secret per-process report; never scan or read *.key. */
44
+ function claudeProcessVersion(pid, start) {
45
+ const config = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude'), dir = path.join(config, 'sessions'), file = path.join(dir, String(pid) + '.json');
46
+ // This producer writes0644 metadata under0700 sessions, not a secret0600 file.
47
+ for (const component of [config, dir]) {
48
+ const s = fs.lstatSync(component);
49
+ if (!s.isDirectory() || s.isSymbolicLink() || s.uid !== process.getuid?.() || (s.mode & 0o022) !== 0)
50
+ throw new Error('RuntimeRestartRequired');
51
+ }
52
+ const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
53
+ try {
54
+ const s = fs.fstatSync(fd);
55
+ if (!s.isFile() || s.uid !== process.getuid?.() || (s.mode & 0o022) !== 0 || s.size > 65536)
56
+ throw new Error('RuntimeRestartRequired');
57
+ const p = JSON.parse(fs.readFileSync(fd, 'utf8'));
58
+ if (p.pid !== pid || p.entrypoint !== 'cli' || p.procStart !== ownerStart(pid, true) || ownerStart(pid) !== start)
59
+ throw new Error('RuntimeRestartRequired');
60
+ return typeof p.version === 'string' ? p.version : 'unknown';
102
61
  }
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
- });
62
+ finally {
63
+ fs.closeSync(fd);
110
64
  }
111
- notify(method) { this.ws.send(JSON.stringify({ method })); }
112
- close() { this.ws.close(); }
113
65
  }
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;
66
+ /** Validate the running owner once; its path may disappear during auto-update. */
67
+ export async function ownerRuntimeProof(kind, pid, start, folder) {
68
+ if (unsupportedDesktopOwner(pid, ''))
69
+ throw new Error('UnsupportedDesktopIDEHost');
70
+ let executable, image;
123
71
  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)]);
164
- }
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
- };
72
+ executable = nativeExecutable(pid, kind);
73
+ image = nativeImageIdentity(pid, kind, executable);
171
74
  }
172
75
  catch (error) {
173
- rpc?.close();
174
- await stopOwned(server);
175
- throw error;
76
+ // Arbitrary Node launchers must not acquire native status through metadata.
77
+ if (error instanceof Error && error.message === 'UnsupportedNodeNativeEntry')
78
+ throw error;
79
+ if (kind === 'claude')
80
+ try {
81
+ return { schema: 1, client: kind, owner: pid, start, folder, version: claudeProcessVersion(pid, start), source: 'claude-session' };
82
+ }
83
+ catch { /* A missing/mismatched producer record cannot be repaired by PATH. */ }
84
+ throw new Error('RuntimeRestartRequired');
85
+ }
86
+ if (unsupportedDesktopOwner(pid, executable))
87
+ throw new Error('UnsupportedDesktopIDEHost');
88
+ // File and running-process identity establish ownership; version is descriptive.
89
+ if (nativeImageIdentity(pid, kind, executable) !== image || ownerStart(pid) !== start)
90
+ throw new Error('RuntimeRestartRequired');
91
+ return { schema: 1, client: kind, owner: pid, start, folder, version: 'unknown', source: 'image', executable, image };
92
+ }
93
+ /** Resolve a runnable queue command for the already verified owner. */
94
+ export function queueExecutable(proof) {
95
+ if (proof.client !== 'codex' || !retainedRuntime(proof, 'codex', proof.owner, proof.start, proof.folder) || ownerStart(proof.owner) !== proof.start)
96
+ throw new Error('RuntimeRestartRequired');
97
+ const candidates = [proof.executable, ...(process.env.PATH ?? '').split(path.delimiter).map(dir => path.resolve(dir || '.', 'codex'))];
98
+ for (const candidate of candidates) {
99
+ if (!candidate)
100
+ continue;
101
+ try {
102
+ const real = fs.realpathSync(candidate), before = executableIdentity(real);
103
+ if (unsupportedDesktopOwner(proof.owner, real))
104
+ continue;
105
+ if (executableIdentity(real) !== before || ownerStart(proof.owner) !== proof.start)
106
+ throw new Error('RuntimeRestartRequired');
107
+ return real;
108
+ }
109
+ catch { /* Try another runnable command only after the actual owner is proven. */ }
176
110
  }
111
+ throw new Error('RuntimeRestartRequired');
177
112
  }
@@ -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
+ };
package/dist/tools.js CHANGED
@@ -34,6 +34,7 @@ import { callApi } from "./client.js";
34
34
  import { HOSTED_TOOL_NAMES, validateOutput } from "./schemas.js";
35
35
  import { formatToolErrorText } from "./errors.js";
36
36
  import { redact, redactDeep } from "./redact.js";
37
+ import { runWithWakeAction } from "./context.js";
37
38
  // ---- small, defensive arg readers ----
38
39
  function stringArg(args, key) {
39
40
  const value = args[key];
@@ -434,8 +435,20 @@ async function terminal_wake_receipt(args, signal) {
434
435
  async function terminal_wake_checkin(args, signal) {
435
436
  return finish("terminal_wake_checkin", await callApi({ method: "POST", path: "/terminal-wakes/checkin", body: args, signal }));
436
437
  }
438
+ async function terminal_wake_read(args, signal) {
439
+ return finish("terminal_wake_read", await callApi({ method: "POST", path: "/terminal-wakes/read", body: args, signal }));
440
+ }
441
+ async function terminal_wake_complete(args, signal) {
442
+ return finish("terminal_wake_complete", await callApi({ method: "POST", path: "/terminal-wakes/complete", body: args, signal }));
443
+ }
444
+ async function terminal_wake_pin(args, signal) {
445
+ return finish("terminal_wake_pin", await callApi({ method: "POST", path: "/terminal-wakes/pin", body: args, signal }));
446
+ }
437
447
  // ---- registry ----
438
- export const TOOLS = {
448
+ const REGISTRY = {
449
+ terminal_wake_read: { name: "terminal_wake_read", run: terminal_wake_read },
450
+ terminal_wake_complete: { name: "terminal_wake_complete", run: terminal_wake_complete },
451
+ terminal_wake_pin: { name: "terminal_wake_pin", run: terminal_wake_pin },
439
452
  terminal_wake_start: { name: "terminal_wake_start", run: terminal_wake_start },
440
453
  terminal_wake_poll: { name: "terminal_wake_poll", run: terminal_wake_poll },
441
454
  terminal_wake_receipt: { name: "terminal_wake_receipt", run: terminal_wake_receipt },
@@ -465,60 +478,28 @@ export const TOOLS = {
465
478
  create_document: { name: "create_document", run: create_document },
466
479
  edit_document: { name: "edit_document", run: edit_document },
467
480
  };
468
- /**
469
- * Accurate per-tool annotations for all tools.
470
- *
471
- * Semantics (MCP spec): `readOnlyHint` — the tool does not modify its
472
- * environment; `destructiveHint` — the tool may perform DESTRUCTIVE (not
473
- * merely additive) updates; `idempotentHint` — repeated calls with the same
474
- * arguments have no ADDITIONAL effect on the environment; `openWorldHint` —
475
- * the tool touches an open external world (all 9 tools operate on the closed
476
- * AgentMesh workspace upstream, hence false everywhere).
477
- *
478
- * Write-tool rationale:
479
- * - claim_card: CAS — a repeat claim either no-ops (same identity) or is a
480
- * typed conflict that mutates nothing ⇒ idempotent, additive-only.
481
- * - complete_card: claimant-only CAS — a repeat complete is a typed conflict
482
- * whose CAS-miss branch is read-only ⇒ effect-idempotent, additive-only
483
- * (the response is a conflict, but the ENVIRONMENT is unchanged — the
484
- * hint speaks to environmental effect, per spec wording).
485
- * - post_message / create_card: every invocation appends a NEW row by design
486
- * (fresh Idempotency-Key per invocation) ⇒ NOT idempotent; additive-only.
487
- *
488
- * Serving these from ListTools is a one-line integration in server.ts
489
- * (`annotations: TOOL_ANNOTATIONS[name]`) — server.ts is Seam B's file, so
490
- * that wiring is FLAGGED to the integrator rather than edited here.
491
- */
492
- export const TOOL_ANNOTATIONS = {
493
- terminal_wake_start: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
494
- terminal_wake_poll: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
495
- terminal_wake_receipt: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
496
- terminal_wake_checkin: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
497
- read_board: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
498
- read_channels: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
499
- read_messages: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
500
- list_asks: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
501
- get_my_instructions: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
502
- whoami: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
503
- post_message: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
504
- claim_card: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
505
- complete_card: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
506
- create_card: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
507
- read_roster: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
508
- list_conversations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
509
- create_conversation: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
510
- read_conversation_messages: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
511
- post_conversation_message: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
512
- edit_document: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
513
- create_document: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
514
- read_document: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
515
- list_documents: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
516
- resolve_ask: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
517
- claim_ask: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
518
- create_ask: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
519
- assign_card: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
520
- edit_card: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
521
- };
481
+ // ---- tool annotations (Phase-1 adoption AC-4) ----
482
+ import { TOOL_ANNOTATIONS } from './tool-annotations.js';
483
+ export { TOOL_ANNOTATIONS } from './tool-annotations.js';
484
+ export const TOOLS = Object.fromEntries(Object.entries(REGISTRY).map(([name, tool]) => [name, {
485
+ ...tool,
486
+ async run(args, signal) {
487
+ const { wake_context: value, ...body } = args;
488
+ if (value === undefined)
489
+ return tool.run(body, signal);
490
+ const context = value;
491
+ const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
492
+ if (!context || typeof context !== "object" || Array.isArray(context)
493
+ || Object.keys(context).some(k => !["event_id", "claim_id", "action_id"].includes(k))
494
+ || typeof context.event_id !== "string" || !uuid.test(context.event_id)
495
+ || typeof context.claim_id !== "string" || !uuid.test(context.claim_id)
496
+ || typeof context.action_id !== "string" || !/^[A-Za-z0-9_.:-]{1,128}$/.test(context.action_id)
497
+ || TOOL_ANNOTATIONS[tool.name].readOnlyHint || name.startsWith("terminal_wake_")) {
498
+ return errorResult({ ok: false, code: "VALIDATION", message: "wake_context requires valid event, claim and stable action IDs on a business write", status: 400 });
499
+ }
500
+ return runWithWakeAction(context, () => tool.run(body, signal));
501
+ },
502
+ }]));
522
503
  function isToolName(name) {
523
504
  return HOSTED_TOOL_NAMES.some((n) => n === name);
524
505
  }