@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/README.md CHANGED
@@ -5,8 +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.2.2 is a local release candidate, not a published npm version or
9
- registry listing.** The npm package is `@agentmesh-md/mcp-server`. Alex publishes
8
+ **Version 0.3.4 is an unpublished local release candidate.** The npm package is `@agentmesh-md/mcp-server`. Alex publishes
10
9
  this candidate after QA acceptance. `UNLICENSED` grants no public reuse
11
10
  permission. Node.js **22 or newer** is required.
12
11
 
@@ -17,7 +16,7 @@ Given the approved local artifact, install it into a directory of your choice:
17
16
  ```sh
18
17
  mkdir agentmesh-client
19
18
  cd agentmesh-client
20
- npm install /ABSOLUTE/PATH/TO/agentmesh-md-mcp-server-0.2.2.tgz
19
+ npm install /ABSOLUTE/PATH/TO/agentmesh-md-mcp-server-0.3.4.tgz
21
20
  ```
22
21
 
23
22
  For maintainers with the source checkout, `cd mcp && npm ci && npm pack` builds
@@ -48,7 +47,7 @@ when using another AgentMesh deployment. Run `whoami` after connecting to confir
48
47
  the intended agent and workspace; discovery alone does not validate a key.
49
48
 
50
49
  After a separately approved public release, the corresponding pinned install
51
- would be `npm install @agentmesh-md/mcp-server@0.2.2`. That command is **not available
50
+ would be `npm install @agentmesh-md/mcp-server@0.3.4`. That command is **not available
52
51
  as a published release yet**. `server.json` is proposed MCP Registry metadata
53
52
  for `md.agentmesh/agentmesh`, not proof of a listing.
54
53
 
@@ -114,3 +113,143 @@ stateless legacy clients are supported; legacy session GET/DELETE return 405,
114
113
  and no MCP session ID is issued. Bearer validation uses `GET /api/v1/me` per
115
114
  request with a 30-second positive cache, so revocation may take that long to
116
115
  apply in HTTP mode. This is not a remotely hosted connector or an OAuth service.
116
+
117
+ ## Existing-session Connect — 0.3.3 candidate
118
+
119
+ 0.3.3 is an unpublished candidate. Run the candidate's `agentmesh-mcp connect
120
+ --client claude|codex --agent <UUID> --workspace <UUID>` in the folder to connect.
121
+ It approves and verifies the agent, saves an owner-only folder binding, installs
122
+ the plugin and exits. It does not start an agent, thread, app-server or resume.
123
+ An install failure leaves a saved-but-not-installed binding; rerunning is safe.
124
+ Existing 0.2.2 stdio and running launcher sessions retain their contract.
125
+
126
+ Before browser approval, Claude Connect displays the resolved LOCAL settings
127
+ path and asks once whether to allow these exact five tools for automatic wake
128
+ reads and replies:
129
+
130
+ - `mcp__plugin_agentmesh_agentmesh__whoami`
131
+ - `mcp__plugin_agentmesh_agentmesh__terminal_wake_read`
132
+ - `mcp__plugin_agentmesh_agentmesh__terminal_wake_complete`
133
+ - `mcp__plugin_agentmesh_agentmesh__post_message`
134
+ - `mcp__plugin_agentmesh_agentmesh__post_conversation_message`
135
+
136
+ Only an explicit interactive yes adds absent entries to
137
+ `.claude/settings.local.json`, after browser identity is verified. Git folders
138
+ use the repository root; linked worktrees share the main checkout's local
139
+ settings. Outside Git, the connected canonical folder is the scope. No, EOF or
140
+ noninteractive input still completes Connect and leaves native approval required
141
+ for each action. Existing `ask`/`deny` entries and managed restrictions remain
142
+ authoritative and can require approval or prevent automatic wakes. Connect does
143
+ not change the permission mode, add wildcards or bypass native restrictions.
144
+ Saved consent and interrupted setup are reconciled on rerun without another
145
+ question. Invalid, unsafe or concurrently modified settings are rejected.
146
+
147
+ MCP initialization and tool listing work even in an unconnected folder, without
148
+ credentials or network requests. Tool calls there return “this folder is offline;
149
+ run Connect in this folder.” A later valid session hook binds the same MCP
150
+ transport; a wrong-folder startup does not require a manual MCP reconnect.
151
+
152
+ `agentmesh-mcp connect --client claude --disconnect` disconnects the current
153
+ folder locally without browser approval or starting a session. It retires the
154
+ folder enrollment and removes only entries originally added by Connect;
155
+ preexisting rules and unrelated settings survive. Shared settings retain owned
156
+ entries until the last consenting enrollment disconnects. Remote revoke stops
157
+ hosted authorization immediately. If this machine is offline, local permission
158
+ cleanup occurs on the next native authentication check or explicit local
159
+ disconnect. Cleanup errors remain visible and never restore authorization.
160
+
161
+ Claude uses the generated HTTPS marketplace and immutable SHA256-bound ZIP.
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.
167
+ Codex installs the same payload from npm's generated local marketplace and merges
168
+ its lifecycle hooks into `$CODEX_HOME/hooks.json` (default `~/.codex/hooks.json`).
169
+ Foreign hooks are preserved. The command uses a stable private launcher under
170
+ `~/.agentmesh/plugin/`; upgrades update its private target without changing the
171
+ hook command. Connect rereads the file and verifies the command, or exits nonzero
172
+ 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
176
+ existing session and supplies its logical workspace to all AgentMesh tool calls;
177
+ before that hook, tools load but calls ask you to trust hooks and send a message.
178
+ An install does not replay SessionStart. Wakes turns On only
179
+ after the real listener checks in AND the agent reads its probe. Disabled or
180
+ managed-only hooks stay subject to Codex policy; installation never grants trust,
181
+ changes that policy, starts app-server, or resumes a session. Plugin-bundled Codex
182
+ hooks are not used by this shipping path.
183
+
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.
190
+
191
+ Hooks record the native session UUID and exact process ancestry/start identity.
192
+ The MCP process and Claude monitor resolve only that owner, never a latest
193
+ profile or folder fallback. Codex's hook starts one session watcher, which queues
194
+ only to the existing thread without `--resume`. Desktop/IDE hosts remain unsupported until native delivery proof. Named native
195
+ desktop/IDE owners are rejected with `UnsupportedDesktopIDEHost`; unreadable
196
+ owners stay offline with `UnsupportedUnreadableNativeExecutable`. Missing ancestry
197
+ stays offline with `UnsupportedHostNoNativeOwner`; no alternative runtime is
198
+ started. CLI descendant binding has an isolated SIM test. Desktop/IDE and live
199
+ OAuth wake execution remain separate native proof requirements.
200
+
201
+ Saved OAuth runtime calls never open approval windows or callback listeners.
202
+ Cross-process locking reloads credentials before refresh, including rotation.
203
+ The listener reuses one initialized MCP client. An idle protocol-2 poll waits up
204
+ to 25 seconds and returns early on a committed wake; no separate periodic
205
+ check-in runs. Normal proxy calls keep their own credential lock, so an idle
206
+ wait cannot block tool use or refresh. Local shutdown cancels the pending wait.
207
+ The server records heartbeat at poll arrival, never at timeout or notification.
208
+ It shares one PostgreSQL LISTEN connection across local waiters and treats
209
+ notifications only as hints to reread the durable inbox. A lost hint is recovered
210
+ by the next poll. The shared connection is released after the last waiter leaves.
211
+ Hosted waiting capacity is bounded separately (1,000 held polls, 16 ordinary
212
+ requests by default); infrastructure concurrency and measured cost remain
213
+ deployment settings, not a promise made by those source limits.
214
+ Wake output is fixed text plus validated UUID references, never source text.
215
+ `terminal_wake_read` claims and returns source/action receipts; wake-caused writes
216
+ require `wake_context: {event_id, claim_id, action_id}` with a stable logical action
217
+ ID. Reconcile committed receipts before retrying and call `terminal_wake_complete`
218
+ only after handling. Transport output alone does not claim or complete work.
219
+ `connect --client <client> --pin-session <UUID>` pins an existing session using
220
+ saved approval. Revoked approval requires reconnect; transient failures retry.
221
+
222
+ `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}`.
224
+ Regenerate after server/schema integration before freezing candidate hashes.
225
+
226
+ Session hooks and listeners validate the actual owner's process and executable
227
+ identity. Version metadata is descriptive and never controls admission. Actual
228
+ plugin installation and queue operation errors remain visible; this does not
229
+ prove desktop/IDE delivery. Hooks remain authoritative when `/clear` changes the session: an
230
+ existing live binding takes precedence over the monitor's older environment.
231
+ A graceful monitor stop closes its local generation; stale monitor callbacks
232
+ cannot reopen it. SessionStart creates a new generation and the existing MCP
233
+ proxy resolves that binding.
234
+
235
+ 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
+
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.
238
+
239
+ Connect resolves the selected CLI to one absolute executable path and prints it
240
+ before browser approval. It does not run client version or help probes, including
241
+ inside an existing native session. Installation uses that same executable after
242
+ approval; changing PATH during approval cannot select a different installer.
243
+ Standalone installation is setup only: Wakes stay off until the native session
244
+ binds the owner and its probe is read. A missing CLI names the client to install.
245
+
246
+ 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
248
+ connected seat and runs Connect in its actual workspace directory with
249
+ `--agent EXISTING_AGENT_UUID --workspace EXISTING_WORKSPACE_UUID`, then performs
250
+ the native activation described above. Atlas owns the complete seat pass; no
251
+ follow-up is left to Alex or individual agents. Existing permissions and native
252
+ trust remain authoritative. Retained KEEP sessions require Atlas's explicit
253
+ release before that pass. Verify the same agent/workspace with whoami and its
254
+ probe after activation; npm publication alone does not satisfy that readback.
255
+ The hosted backend, SPA command and npm release must update in the same install.
package/dist/client.js CHANGED
@@ -18,7 +18,7 @@
18
18
  * never included in a returned error, and this module performs no logging
19
19
  * of its own.
20
20
  */
21
- import { currentRequestApiKey, currentRequestContext } from "./context.js";
21
+ import { currentRequestApiKey, currentRequestContext, currentWakeAction } from "./context.js";
22
22
  // The private hosted process supplies its own fixed request context. Loading
23
23
  // local CLI configuration there would require a process API key or exit the
24
24
  // existing app. CLI entries still validate their configuration at startup.
@@ -50,9 +50,20 @@ export async function callApi(params) {
50
50
  }
51
51
  const url = buildUrl(params.path, params.query);
52
52
  const headers = buildHeaders(params);
53
+ const wake = currentWakeAction();
54
+ if (wake && params.method !== "GET" && !params.path.startsWith("/terminal-wakes/")) {
55
+ headers["X-AgentMesh-Wake-Event"] = wake.event_id;
56
+ headers["X-AgentMesh-Wake-Claim"] = wake.claim_id;
57
+ headers["X-AgentMesh-Wake-Action"] = wake.action_id;
58
+ headers["Idempotency-Key"] = `wake:${wake.event_id}:${wake.action_id}`;
59
+ }
53
60
  const bodyText = params.body === undefined ? undefined : JSON.stringify(params.body);
61
+ const pollBody = params.body;
62
+ const held = params.method === 'POST' && params.path === '/terminal-wakes/poll' && pollBody && Number.isInteger(pollBody.wait_seconds) && Number(pollBody.wait_seconds) > 0 && Number(pollBody.wait_seconds) <= 25;
63
+ const maxAttempts = held ? 1 : MAX_ATTEMPTS;
64
+ const attemptTimeout = held ? 28_000 : PER_ATTEMPT_TIMEOUT_MS;
54
65
  const deadlineAt = Date.now() + TOTAL_DEADLINE_MS;
55
- for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
66
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
56
67
  if (callerAborted(params.signal)) {
57
68
  return callerAbortedResult(params.signal);
58
69
  }
@@ -67,7 +78,7 @@ export async function callApi(params) {
67
78
  }
68
79
  // Per-attempt timeout, capped so a late attempt can never push past the
69
80
  // total 30s deadline.
70
- const timeoutMs = Math.min(PER_ATTEMPT_TIMEOUT_MS, remainingMs);
81
+ const timeoutMs = Math.min(attemptTimeout, remainingMs);
71
82
  const timeoutController = new AbortController();
72
83
  const timer = setTimeout(() => timeoutController.abort(), timeoutMs);
73
84
  const onCallerAbort = () => timeoutController.abort();
@@ -98,7 +109,7 @@ export async function callApi(params) {
98
109
  }
99
110
  // Network failure OR our per-attempt timeout firing during connect or the
100
111
  // body read. This is the ONE non-5xx case allowed to consume attempt 2.
101
- if (attempt < MAX_ATTEMPTS) {
112
+ if (attempt < maxAttempts) {
102
113
  continue;
103
114
  }
104
115
  return networkErrorResult(err);
@@ -113,7 +124,7 @@ export async function callApi(params) {
113
124
  // Every 4xx (incl. 409, 429) is terminal after one request. Only a 5xx
114
125
  // may consume attempt 2, reusing the identical url/headers/body above (in
115
126
  // particular the same Idempotency-Key, unchanged across the loop).
116
- if (status >= 500 && attempt < MAX_ATTEMPTS) {
127
+ if (status >= 500 && attempt < maxAttempts) {
117
128
  continue;
118
129
  }
119
130
  // PLAN section 4: report Retry-After on a 429 so the caller can back off
@@ -0,0 +1,142 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import os from 'node:os';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { ownerDirectory } from './oauth-client.js';
6
+ import { privateRoot, privateRead, locked } from './plugin-storage.js';
7
+ import { writeAtomic } from './wake-storage.js';
8
+ import { terminalDiagnostic } from './terminal-diagnostic.js';
9
+ const events = ['SessionStart', 'UserPromptSubmit', 'Stop', 'SessionEnd'];
10
+ // Constant command AND launcher bytes: upgrading the private target does not
11
+ // change the hook definition or write Codex's user-owned trust decision.
12
+ const launcher = `#!/usr/bin/env node
13
+ const fs=require('node:fs'),path=require('node:path'),cp=require('node:child_process');
14
+ (async()=>{try {
15
+ let input='';for await(const chunk of process.stdin){input+=chunk;if(input.length>65536)throw Error();}
16
+ const hook=JSON.parse(input),folder=require('node:crypto').createHash('sha256').update(fs.realpathSync(hook.cwd)).digest('hex');
17
+ const enrollment=path.join(__dirname,'enrollment-codex-'+folder+'.json');
18
+ if(!fs.existsSync(enrollment))process.exit(0);
19
+ const es=fs.lstatSync(enrollment);if(!es.isFile()||es.isSymbolicLink()||es.uid!==process.getuid()||(es.mode&0o077))throw Error();
20
+ const e=JSON.parse(fs.readFileSync(enrollment,'utf8'));if(e.retired||!e.installed)process.exit(0);
21
+ const file=path.join(__dirname,'codex-hook-target.json'),stat=fs.lstatSync(file);
22
+ if(!stat.isFile()||stat.isSymbolicLink()||stat.uid!==process.getuid()||(stat.mode&0o077))throw Error();
23
+ const target=JSON.parse(fs.readFileSync(file,'utf8'));
24
+ if(!path.isAbsolute(target.node)||!path.isAbsolute(target.entry))throw Error();
25
+ const result=cp.spawnSync(target.node,[target.entry,'plugin-hook','codex'],{input,stdio:['pipe','inherit','inherit'],env:{...process.env,AGENTMESH_HOOK_OWNER_PID:String(process.ppid)}});
26
+ process.exit(result.status??1);
27
+ }catch{process.stderr.write('AgentMesh Codex hook unavailable; run Connect in this folder again.\\n');process.exit(1);}})();
28
+ `;
29
+ const object = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
30
+ function readDocument(file) {
31
+ try {
32
+ const stat = fs.lstatSync(file);
33
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.uid !== process.getuid?.())
34
+ throw new Error('CodexHookFileUnsafe');
35
+ }
36
+ catch (error) {
37
+ if (error.code === 'ENOENT')
38
+ return {};
39
+ throw error;
40
+ }
41
+ const value = JSON.parse(fs.readFileSync(file, 'utf8'));
42
+ if (!object(value) || value.hooks !== undefined && !object(value.hooks))
43
+ throw new Error('CodexHookFileInvalid');
44
+ for (const event of events) {
45
+ const groups = value.hooks?.[event];
46
+ if (groups !== undefined && (!Array.isArray(groups) || groups.some((g) => !object(g) || !Array.isArray(g.hooks))))
47
+ throw new Error('CodexHookFileInvalid');
48
+ }
49
+ return value;
50
+ }
51
+ const quote = (s) => "'" + s.replaceAll("'", "'\\''") + "'";
52
+ export async function installCodexHooks(entry) {
53
+ const home = path.resolve(process.env.CODEX_HOME || path.join(os.homedir(), '.codex')), file = path.join(home, 'hooks.json');
54
+ try {
55
+ ownerDirectory(home);
56
+ await locked(home, 'agentmesh-hooks', async () => {
57
+ const before = readDocument(file), root = privateRoot(), executable = path.join(root, 'codex-hook.cjs'), targetFile = path.join(root, 'codex-hook-target.json');
58
+ const command = quote(executable), after = structuredClone(before);
59
+ after.hooks ??= {};
60
+ for (const event of events) {
61
+ const groups = after.hooks[event] ?? [];
62
+ // Own only the exact stable command; foreign matcher groups and handlers
63
+ // survive byte-for-byte as JSON values, including mixed groups.
64
+ const own = (h) => object(h) && h.type === 'command' && h.command === command;
65
+ after.hooks[event] = groups.filter((group) => !(Object.keys(group).length === 1 && group.hooks.length > 0 && group.hooks.every(own))).map((group) => ({ ...group, hooks: group.hooks.filter((h) => !own(h)) }));
66
+ after.hooks[event].push({ hooks: [{ type: 'command', command }] });
67
+ }
68
+ for (const name of [executable, targetFile])
69
+ try {
70
+ const stat = fs.lstatSync(name);
71
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.uid !== process.getuid?.())
72
+ throw new Error('CodexHookFileUnsafe');
73
+ }
74
+ catch (error) {
75
+ if (error.code !== 'ENOENT')
76
+ throw error;
77
+ }
78
+ const tmp = executable + '.' + randomUUID();
79
+ try {
80
+ fs.writeFileSync(tmp, launcher, { mode: 0o700, flag: 'wx' });
81
+ fs.renameSync(tmp, executable);
82
+ }
83
+ finally {
84
+ fs.rmSync(tmp, { force: true });
85
+ }
86
+ writeAtomic(targetFile, { node: process.execPath, entry });
87
+ // Avoid replacing a concurrently edited document with our earlier snapshot.
88
+ if (JSON.stringify(readDocument(file)) !== JSON.stringify(before))
89
+ throw new Error('CodexHookFileChanged');
90
+ writeAtomic(file, after, true);
91
+ const actual = readDocument(file);
92
+ if (JSON.stringify(actual) !== JSON.stringify(after))
93
+ throw new Error('CodexHookReadbackFailed');
94
+ const target = privateRead(targetFile);
95
+ if (!target || target.node !== process.execPath || target.entry !== entry || fs.readFileSync(executable, 'utf8') !== launcher)
96
+ throw new Error('CodexHookReadbackFailed');
97
+ fs.accessSync(executable, fs.constants.X_OK);
98
+ fs.accessSync(target.node, fs.constants.X_OK);
99
+ fs.accessSync(target.entry, fs.constants.R_OK);
100
+ });
101
+ process.stderr.write(`AgentMesh hooks file saved and verified: ${file}. This verifies setup, not live delivery.\n`);
102
+ }
103
+ catch (error) {
104
+ process.stderr.write(`AgentMesh Codex hooks could not be verified at ${file}: ${terminalDiagnostic(error, 'codex-hooks.js', 'installCodexHooks')}. Check that this owner-writable file contains valid hooks JSON, then rerun Connect. Wakes require a live listener and your agent's probe read.\n`);
105
+ throw new Error('CodexHookSetupFailed', { cause: error });
106
+ }
107
+ }
108
+ /** Shared hooks survive until the last folder has retired its enrollment. */
109
+ export async function removeCodexHooksIfUnused() {
110
+ const root = privateRoot();
111
+ const inUse = () => fs.readdirSync(root).filter(n => /^enrollment-codex-.*\.json$/.test(n)).some(n => { const e = privateRead(path.join(root, n)); return e && !e.retired; });
112
+ if (inUse())
113
+ return;
114
+ const home = path.resolve(process.env.CODEX_HOME || path.join(os.homedir(), '.codex')), file = path.join(home, 'hooks.json');
115
+ await locked(home, 'agentmesh-hooks', async () => {
116
+ if (inUse())
117
+ return;
118
+ const before = readDocument(file), after = structuredClone(before), command = quote(path.join(root, 'codex-hook.cjs'));
119
+ for (const event of events) {
120
+ if (!after.hooks?.[event])
121
+ continue;
122
+ after.hooks[event] = after.hooks[event].map((group) => ({ ...group, hooks: group.hooks.filter((h) => !(object(h) && h.type === 'command' && h.command === command)) })).filter((group) => group.hooks.length || Object.keys(group).length > 1);
123
+ }
124
+ if (JSON.stringify(readDocument(file)) !== JSON.stringify(before))
125
+ throw new Error('CodexHookFileChanged');
126
+ if (JSON.stringify(before) !== JSON.stringify(after))
127
+ writeAtomic(file, after, true);
128
+ for (const name of ['codex-hook.cjs', 'codex-hook-target.json']) {
129
+ const target = path.join(root, name);
130
+ try {
131
+ const st = fs.lstatSync(target);
132
+ if (!st.isFile() || st.isSymbolicLink() || st.uid !== process.getuid?.())
133
+ throw new Error('CodexHookFileUnsafe');
134
+ fs.unlinkSync(target);
135
+ }
136
+ catch (e) {
137
+ if (e.code !== 'ENOENT')
138
+ throw e;
139
+ }
140
+ }
141
+ });
142
+ }