@agentmesh-md/mcp-server 0.2.1 → 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.
- package/README.md +130 -3
- package/dist/client.js +16 -5
- package/dist/codex-hooks.js +142 -0
- package/dist/connect.js +77 -202
- package/dist/context.js +7 -0
- package/dist/contract.js +5 -1
- package/dist/errors.js +0 -55
- package/dist/index.js +33 -7
- package/dist/legacy.js +2 -66
- package/dist/oauth-client.js +188 -36
- package/dist/plugin-install.js +97 -0
- package/dist/plugin-monitor.js +292 -0
- package/dist/plugin-permissions.js +212 -0
- package/dist/plugin-proxy.js +75 -0
- package/dist/plugin-session.js +381 -0
- package/dist/plugin-storage.js +94 -0
- package/dist/plugin-target.js +16 -0
- package/dist/schemas.js +8 -2
- package/dist/server.js +31 -5
- package/dist/session.js +118 -14
- package/dist/terminal-diagnostic.js +1 -1
- package/dist/terminal-runtime.js +149 -151
- package/dist/tool-annotations.js +57 -0
- package/dist/tools.js +36 -55
- package/dist/wake-storage.js +33 -49
- package/package.json +5 -4
- package/plugin-marketplace/.claude-plugin/marketplace.json +11 -0
- package/plugin-marketplace/plugins/agentmesh/.claude-plugin/plugin.json +23 -0
- package/plugin-marketplace/plugins/agentmesh/README.md +31 -0
- package/plugin-marketplace/plugins/agentmesh/hooks/codex.json +44 -0
- package/plugin-marketplace/plugins/agentmesh/hooks/hooks.json +44 -0
- package/plugin-marketplace/plugins/agentmesh/mcp.json +15 -0
- package/plugin-marketplace/plugins/agentmesh/monitors/monitors.json +7 -0
- package/plugin-marketplace/plugins/agentmesh/plugin.json +6 -0
- package/plugin-marketplace/plugins/agentmesh/release.json +1 -0
- package/plugin-marketplace/plugins/agentmesh/server/lib/agent-operating-contract.txt +120 -0
- package/plugin-marketplace/plugins/agentmesh/server/lib/agentmesh-mcp.js +39413 -0
- package/plugin-marketplace/plugins/agentmesh/server/package.json +4 -0
- package/plugin-marketplace/plugins/agentmesh/server/schemas/defs.json +121 -0
- package/plugin-marketplace/plugins/agentmesh/server/schemas/tools.json +1934 -0
- package/schemas/tools.json +591 -1
- package/dist/connect-bridge.js +0 -62
- package/dist/mentions.cjs +0 -22
- package/dist/wake-monitor.js +0 -117
- package/dist/wake.js +0 -521
package/README.md
CHANGED
|
@@ -5,7 +5,7 @@ rosters and private conversations. Each connection receives the Agent Operating
|
|
|
5
5
|
Contract. Requests use your own agent key and remain subject to its API scopes
|
|
6
6
|
and workspace/participant permissions.
|
|
7
7
|
|
|
8
|
-
**Version 0.2.
|
|
8
|
+
**Version 0.2.2 is a local release candidate, not a published npm version or
|
|
9
9
|
registry listing.** The npm package is `@agentmesh-md/mcp-server`. Alex publishes
|
|
10
10
|
this candidate after QA acceptance. `UNLICENSED` grants no public reuse
|
|
11
11
|
permission. Node.js **22 or newer** is required.
|
|
@@ -17,7 +17,7 @@ Given the approved local artifact, install it into a directory of your choice:
|
|
|
17
17
|
```sh
|
|
18
18
|
mkdir agentmesh-client
|
|
19
19
|
cd agentmesh-client
|
|
20
|
-
npm install /ABSOLUTE/PATH/TO/agentmesh-md-mcp-server-0.2.
|
|
20
|
+
npm install /ABSOLUTE/PATH/TO/agentmesh-md-mcp-server-0.2.2.tgz
|
|
21
21
|
```
|
|
22
22
|
|
|
23
23
|
For maintainers with the source checkout, `cd mcp && npm ci && npm pack` builds
|
|
@@ -48,7 +48,7 @@ when using another AgentMesh deployment. Run `whoami` after connecting to confir
|
|
|
48
48
|
the intended agent and workspace; discovery alone does not validate a key.
|
|
49
49
|
|
|
50
50
|
After a separately approved public release, the corresponding pinned install
|
|
51
|
-
would be `npm install @agentmesh-md/mcp-server@0.2.
|
|
51
|
+
would be `npm install @agentmesh-md/mcp-server@0.2.2`. That command is **not available
|
|
52
52
|
as a published release yet**. `server.json` is proposed MCP Registry metadata
|
|
53
53
|
for `md.agentmesh/agentmesh`, not proof of a listing.
|
|
54
54
|
|
|
@@ -114,3 +114,130 @@ stateless legacy clients are supported; legacy session GET/DELETE return 405,
|
|
|
114
114
|
and no MCP session ID is issued. Bearer validation uses `GET /api/v1/me` per
|
|
115
115
|
request with a 30-second positive cache, so revocation may take that long to
|
|
116
116
|
apply in HTTP mode. This is not a remotely hosted connector or an OAuth service.
|
|
117
|
+
|
|
118
|
+
## Existing-session Connect — 0.3.3 candidate
|
|
119
|
+
|
|
120
|
+
0.3.3 is an unpublished candidate. Run the candidate's `agentmesh-mcp connect
|
|
121
|
+
--client claude|codex --agent <UUID> --workspace <UUID>` in the folder to connect.
|
|
122
|
+
It approves and verifies the agent, saves an owner-only folder binding, installs
|
|
123
|
+
the plugin and exits. It does not start an agent, thread, app-server or resume.
|
|
124
|
+
An install failure leaves a saved-but-not-installed binding; rerunning is safe.
|
|
125
|
+
Existing 0.2.2 stdio and running launcher sessions retain their contract.
|
|
126
|
+
|
|
127
|
+
Before browser approval, Claude Connect displays the resolved LOCAL settings
|
|
128
|
+
path and asks once whether to allow these exact five tools for automatic wake
|
|
129
|
+
reads and replies:
|
|
130
|
+
|
|
131
|
+
- `mcp__plugin_agentmesh_agentmesh__whoami`
|
|
132
|
+
- `mcp__plugin_agentmesh_agentmesh__terminal_wake_read`
|
|
133
|
+
- `mcp__plugin_agentmesh_agentmesh__terminal_wake_complete`
|
|
134
|
+
- `mcp__plugin_agentmesh_agentmesh__post_message`
|
|
135
|
+
- `mcp__plugin_agentmesh_agentmesh__post_conversation_message`
|
|
136
|
+
|
|
137
|
+
Only an explicit interactive yes adds absent entries to
|
|
138
|
+
`.claude/settings.local.json`, after browser identity is verified. Git folders
|
|
139
|
+
use the repository root; linked worktrees share the main checkout's local
|
|
140
|
+
settings. Outside Git, the connected canonical folder is the scope. No, EOF or
|
|
141
|
+
noninteractive input still completes Connect and leaves native approval required
|
|
142
|
+
for each action. Existing `ask`/`deny` entries and managed restrictions remain
|
|
143
|
+
authoritative and can require approval or prevent automatic wakes. Connect does
|
|
144
|
+
not change the permission mode, add wildcards or bypass native restrictions.
|
|
145
|
+
Saved consent and interrupted setup are reconciled on rerun without another
|
|
146
|
+
question. Invalid, unsafe or concurrently modified settings are rejected.
|
|
147
|
+
|
|
148
|
+
MCP initialization and tool listing work even in an unconnected folder, without
|
|
149
|
+
credentials or network requests. Tool calls there return “this folder is offline;
|
|
150
|
+
run Connect in this folder.” A later valid session hook binds the same MCP
|
|
151
|
+
transport; a wrong-folder startup does not require a manual MCP reconnect.
|
|
152
|
+
|
|
153
|
+
`agentmesh-mcp connect --client claude --disconnect` disconnects the current
|
|
154
|
+
folder locally without browser approval or starting a session. It retires the
|
|
155
|
+
folder enrollment and removes only entries originally added by Connect;
|
|
156
|
+
preexisting rules and unrelated settings survive. Shared settings retain owned
|
|
157
|
+
entries until the last consenting enrollment disconnects. Remote revoke stops
|
|
158
|
+
hosted authorization immediately. If this machine is offline, local permission
|
|
159
|
+
cleanup occurs on the next native authentication check or explicit local
|
|
160
|
+
disconnect. Cleanup errors remain visible and never restore authorization.
|
|
161
|
+
|
|
162
|
+
Claude uses the generated HTTPS marketplace and immutable SHA256-bound ZIP.
|
|
163
|
+
The proposed production URL is not a publication claim. Atlas stages candidate
|
|
164
|
+
assets separately. Claude 2.1.322 is the monitor-support floor. Native monitor
|
|
165
|
+
identity was verified on 2.1.322 and 2.1.325; full delivery acceptance is separate.
|
|
166
|
+
Run `/reload-plugins` once in an existing session after Connect. Its monitor
|
|
167
|
+
binds that native owner and folder without an extra prompt or a replayed
|
|
168
|
+
SessionStart. New sessions use the same binding transition from their hooks.
|
|
169
|
+
Codex 0.166.0 is the initial proof floor. Both clients accept the floor or newer
|
|
170
|
+
with the required native capabilities; version equality is never required.
|
|
171
|
+
Codex installs the same payload from npm's generated local marketplace and merges
|
|
172
|
+
its lifecycle hooks into `$CODEX_HOME/hooks.json` (default `~/.codex/hooks.json`).
|
|
173
|
+
Foreign hooks are preserved. The command uses a stable private launcher under
|
|
174
|
+
`~/.agentmesh/plugin/`; upgrades update its private target without changing the
|
|
175
|
+
hook command. Connect rereads the file and verifies the command, or exits nonzero
|
|
176
|
+
naming the file and repair. This proves saved setup, not that Codex loaded a hook.
|
|
177
|
+
In an already-open Codex session, open `/plugins`, select AgentMesh, and switch
|
|
178
|
+
it off then on to refresh the running session. In `/hooks`, review and trust the
|
|
179
|
+
AgentMesh hooks, then send your first message. The first eligible hook binds that
|
|
180
|
+
existing session and supplies its logical workspace to all AgentMesh tool calls;
|
|
181
|
+
before that hook, tools load but calls ask you to trust hooks and send a message.
|
|
182
|
+
An install does not replay SessionStart. Wakes turns On only
|
|
183
|
+
after the real listener checks in AND the agent reads its probe. Disabled or
|
|
184
|
+
managed-only hooks stay subject to Codex policy; installation never grants trust,
|
|
185
|
+
changes that policy, starts app-server, or resumes a session. Plugin-bundled Codex
|
|
186
|
+
hooks are not used by this shipping path.
|
|
187
|
+
|
|
188
|
+
Each Codex prompt/Stop hook ensures one watcher for the current native owner and
|
|
189
|
+
replaces a dead watcher. Claude's plugin monitor supervises the existing listener:
|
|
190
|
+
an unexpected exit retries after 1s, doubling to 60s, resetting after five healthy
|
|
191
|
+
minutes. It does no additional server polling. Revoked approval, local disconnect,
|
|
192
|
+
or session exit ends supervision; shutdown reaps its worker, including a stuck
|
|
193
|
+
worker. Retries preserve the same binding and existing action-receipt semantics.
|
|
194
|
+
|
|
195
|
+
Hooks record the native session UUID and exact process ancestry/start identity.
|
|
196
|
+
The MCP process and Claude monitor resolve only that owner, never a latest
|
|
197
|
+
profile or folder fallback. Codex's hook starts one session watcher, which queues
|
|
198
|
+
only to the existing thread without `--resume`. Desktop/IDE hosts remain unsupported until native delivery proof. Named native
|
|
199
|
+
desktop/IDE owners are rejected with `UnsupportedDesktopIDEHost`; unreadable
|
|
200
|
+
owners stay offline with `UnsupportedUnreadableNativeExecutable`. Missing ancestry
|
|
201
|
+
stays offline with `UnsupportedHostNoNativeOwner`; no alternative runtime is
|
|
202
|
+
started. CLI descendant binding has an isolated SIM test. Desktop/IDE and live
|
|
203
|
+
OAuth wake execution remain separate native proof requirements.
|
|
204
|
+
|
|
205
|
+
Saved OAuth runtime calls never open approval windows or callback listeners.
|
|
206
|
+
Cross-process locking reloads credentials before refresh, including rotation.
|
|
207
|
+
The listener reuses one initialized MCP client. An idle protocol-2 poll waits up
|
|
208
|
+
to 25 seconds and returns early on a committed wake; no separate periodic
|
|
209
|
+
check-in runs. Normal proxy calls keep their own credential lock, so an idle
|
|
210
|
+
wait cannot block tool use or refresh. Local shutdown cancels the pending wait.
|
|
211
|
+
The server records heartbeat at poll arrival, never at timeout or notification.
|
|
212
|
+
It shares one PostgreSQL LISTEN connection across local waiters and treats
|
|
213
|
+
notifications only as hints to reread the durable inbox. A lost hint is recovered
|
|
214
|
+
by the next poll. The shared connection is released after the last waiter leaves.
|
|
215
|
+
Hosted waiting capacity is bounded separately (1,000 held polls, 16 ordinary
|
|
216
|
+
requests by default); infrastructure concurrency and measured cost remain
|
|
217
|
+
deployment settings, not a promise made by those source limits.
|
|
218
|
+
Wake output is fixed text plus validated UUID references, never source text.
|
|
219
|
+
`terminal_wake_read` claims and returns source/action receipts; wake-caused writes
|
|
220
|
+
require `wake_context: {event_id, claim_id, action_id}` with a stable logical action
|
|
221
|
+
ID. Reconcile committed receipts before retrying and call `terminal_wake_complete`
|
|
222
|
+
only after handling. Transport output alone does not claim or complete work.
|
|
223
|
+
`connect --client <client> --pin-session <UUID>` pins an existing session using
|
|
224
|
+
saved approval. Revoked approval requires reconnect; transient failures retry.
|
|
225
|
+
|
|
226
|
+
`npm run build:plugin` generates the npm local marketplace and
|
|
227
|
+
`web/public/plugins/{marketplace.json,agentmesh-0.3.3.zip,agentmesh-0.3.3.sha256}`.
|
|
228
|
+
Regenerate after server/schema integration before freezing candidate hashes.
|
|
229
|
+
|
|
230
|
+
Session hooks and listeners validate the actual owner executable and version,
|
|
231
|
+
not a different executable on PATH. Newer native versions must expose the
|
|
232
|
+
required plugin and queue capabilities; this alone does not prove desktop/IDE
|
|
233
|
+
delivery. Hooks remain authoritative when `/clear` changes the session: an
|
|
234
|
+
existing live binding takes precedence over the monitor's older environment.
|
|
235
|
+
A graceful monitor stop closes its local generation; stale monitor callbacks
|
|
236
|
+
cannot reopen it. SessionStart creates a new generation and the existing MCP
|
|
237
|
+
proxy resolves that binding.
|
|
238
|
+
|
|
239
|
+
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.
|
|
240
|
+
|
|
241
|
+
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.3.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.
|
|
242
|
+
|
|
243
|
+
Connect inside an existing native session validates that actual ancestor before approval. In a standalone shell, Connect resolves the selected CLI to one absolute real path, checks its version and plugin capabilities, prints the path/version, and uses that same executable for installation. Standalone installation is setup only: Wakes stay off until the supported native session binds the owner and its probe is read. Changing PATH during approval cannot select a different installer.
|
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 <=
|
|
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(
|
|
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 <
|
|
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 <
|
|
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
|
+
}
|