@agentmesh-md/mcp-server 0.1.1 → 0.2.0

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/dist/schemas.js CHANGED
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * Loads the checked-in JSON Schema fixtures (../schemas/defs.json,
3
- * ../schemas/tools.json — PLAN Appendix A, DO NOT hand-edit those files)
3
+ * ../schemas/tools.json — reviewed contracts; td-63fa2f adds human whoami
4
+ * to the original Appendix A agent branch without relaxing its validation)
4
5
  * and exposes them as typed, ready-to-serve MCP tool definitions, plus
5
6
  * compiled Ajv 2020-12 validators for each tool's outputSchema.
6
7
  *
@@ -57,7 +58,7 @@ const toolsUrl = new URL("../schemas/tools.json", import.meta.url);
57
58
  /** The shared $defs object (card/message/channel/ask) injected into every outputSchema. */
58
59
  const defs = JSON.parse(readFileSync(defsUrl, "utf8"));
59
60
  const rawTools = JSON.parse(readFileSync(toolsUrl, "utf8"));
60
- /** The 14 tool names, exactly as keyed in ../schemas/tools.json. */
61
+ /** The tool names, exactly as keyed in ../schemas/tools.json. */
61
62
  export const TOOL_NAMES = [
62
63
  "read_board",
63
64
  "read_channels",
@@ -74,6 +75,23 @@ export const TOOL_NAMES = [
74
75
  "read_conversation_messages",
75
76
  "post_conversation_message",
76
77
  ];
78
+ /** Additional tools are exposed only by the private hosted entry. */
79
+ export const HOSTED_TOOL_NAMES = [...TOOL_NAMES,
80
+ "terminal_wake_start",
81
+ "terminal_wake_poll",
82
+ "terminal_wake_receipt",
83
+ "terminal_wake_checkin",
84
+ "get_my_instructions",
85
+ "edit_card",
86
+ "assign_card",
87
+ "create_ask",
88
+ "claim_ask",
89
+ "resolve_ask",
90
+ "list_documents",
91
+ "read_document",
92
+ "create_document",
93
+ "edit_document",
94
+ ];
77
95
  export class SchemaGuardError extends Error {
78
96
  code;
79
97
  constructor(code, detail) {
@@ -251,13 +269,13 @@ export function guardSchemaDocuments(defsDoc, toolsDoc, options) {
251
269
  throw new SchemaGuardError("DEFS_KEY_MISMATCH", `defs.json must define exactly [${EXPECTED_DEF_KEYS.join(", ")}]; found [${defKeys.join(", ")}]`);
252
270
  }
253
271
  const toolKeys = Object.keys(toolsDoc).sort();
254
- const expectedToolKeys = [...TOOL_NAMES].sort();
272
+ const expectedToolKeys = [...HOSTED_TOOL_NAMES].sort();
255
273
  if (toolKeys.length !== expectedToolKeys.length || toolKeys.some((k, i) => k !== expectedToolKeys[i])) {
256
- throw new SchemaGuardError("TOOLS_KEY_MISMATCH", `tools.json must define exactly the ${TOOL_NAMES.length} served tools; found [${toolKeys.join(", ")}]`);
274
+ throw new SchemaGuardError("TOOLS_KEY_MISMATCH", `tools.json must define exactly the ${HOSTED_TOOL_NAMES.length} served tools; found [${toolKeys.join(", ")}]`);
257
275
  }
258
276
  // Surface shape + object-root enforcement (2026-07-28) per tool, before any
259
277
  // deep walk so a malformed entry is named precisely.
260
- for (const name of TOOL_NAMES) {
278
+ for (const name of HOSTED_TOOL_NAMES) {
261
279
  const entry = toolsDoc[name];
262
280
  if (!isPlainObject(entry)) {
263
281
  throw new SchemaGuardError("MALFORMED_TOOL_ENTRY", `tools.json entry "${name}" is not an object`);
@@ -290,7 +308,7 @@ export function guardSchemaDocuments(defsDoc, toolsDoc, options) {
290
308
  // Per-served-unit resolution: inputSchema is served VERBATIM (no injection),
291
309
  // so its refs must resolve within itself alone; outputSchema is served with
292
310
  // defs.json injected at $defs, so its refs resolve against that composite.
293
- for (const name of TOOL_NAMES) {
311
+ for (const name of HOSTED_TOOL_NAMES) {
294
312
  const entry = toolsDoc[name];
295
313
  const input = entry["inputSchema"];
296
314
  const output = entry["outputSchema"];
@@ -330,10 +348,15 @@ function buildToolDef(name, description) {
330
348
  }
331
349
  /** Name -> {description, inputSchema, outputSchema-with-$defs}, ready to serve from ListTools. */
332
350
  export const TOOL_DEFS = {
351
+ terminal_wake_start: buildToolDef("terminal_wake_start", "Start an own-agent terminal wake generation; launcher only."),
352
+ terminal_wake_poll: buildToolDef("terminal_wake_poll", "Lease pending own-agent wake references; no message content or recipient selectors."),
353
+ terminal_wake_receipt: buildToolDef("terminal_wake_receipt", "Acknowledge receipt of this event in this exact terminal connection. Stage agent means the model received it; transport alone is not acknowledgement."),
354
+ terminal_wake_checkin: buildToolDef("terminal_wake_checkin", "Record bound terminal process heartbeat or closure; launcher only."),
333
355
  read_board: buildToolDef("read_board", "Read the AgentMesh board: its columns and the cards in each column."),
334
356
  read_channels: buildToolDef("read_channels", "List every AgentMesh channel."),
335
357
  read_messages: buildToolDef("read_messages", "Read messages from an AgentMesh channel, newest first, with cursor pagination via before_id."),
336
358
  list_asks: buildToolDef("list_asks", "List AgentMesh asks (help requests), optionally filtered by state."),
359
+ get_my_instructions: buildToolDef("get_my_instructions", "Read your current owner-provided instructions; native agent connections only."),
337
360
  whoami: buildToolDef("whoami", "Return the identity, workspace, and scopes of the authenticated AgentMesh agent."),
338
361
  post_message: buildToolDef("post_message", 'Post a message to an AgentMesh channel (defaults to "general").'),
339
362
  claim_card: buildToolDef("claim_card", "Claim an open AgentMesh board card so this agent owns it."),
@@ -344,12 +367,21 @@ export const TOOL_DEFS = {
344
367
  create_conversation: buildToolDef("create_conversation", "Create a private conversation with existing workspace participants."),
345
368
  read_conversation_messages: buildToolDef("read_conversation_messages", "Read a private conversation's messages with cursor pagination."),
346
369
  post_conversation_message: buildToolDef("post_conversation_message", "Post a message to a private conversation."),
370
+ edit_card: buildToolDef("edit_card", "Replace a card title and markdown description (including acceptance criteria). Read the existing card before editing; body_md replaces the whole description."),
371
+ assign_card: buildToolDef("assign_card", "Assign an open, unclaimed card to an eligible workspace human or agent. Existing assignment conflicts and eligibility rules remain authoritative."),
372
+ create_ask: buildToolDef("create_ask", "Create a Needs You help request in the connected workspace."),
373
+ claim_ask: buildToolDef("claim_ask", "Claim an open Needs You request for the current identity. Required before a member can resolve their own request."),
374
+ resolve_ask: buildToolDef("resolve_ask", "Resolve an already claimed Needs You request. Only its claimant or an existing human approver/owner can resolve it."),
375
+ list_documents: buildToolDef("list_documents", "List document metadata in the connected workspace; bodies are returned by read_document."),
376
+ read_document: buildToolDef("read_document", "Read a connected-workspace document and its current version before editing."),
377
+ create_document: buildToolDef("create_document", "Create a document using the existing API; server derives the author and first version."),
378
+ edit_document: buildToolDef("edit_document", "Append a document version using expected_version from read_document. A stale version, trashed document or destructive clear is rejected by the existing API."),
347
379
  };
348
380
  // ---- Ajv 2020-12 output validation ----
349
381
  const ajv = new Ajv2020({ strict: true, allErrors: true });
350
382
  addFormats(ajv);
351
383
  const compiledValidators = new Map();
352
- for (const name of TOOL_NAMES) {
384
+ for (const name of HOSTED_TOOL_NAMES) {
353
385
  compiledValidators.set(name, ajv.compile(TOOL_DEFS[name].outputSchema));
354
386
  }
355
387
  /** Look up the compiled Ajv validator for a tool's outputSchema. */
@@ -357,7 +389,7 @@ export function validateOutput(name) {
357
389
  const fn = compiledValidators.get(name);
358
390
  if (fn === undefined) {
359
391
  // Unreachable in practice: compiledValidators is populated above for
360
- // every member of TOOL_NAMES, and `name` is typed as ToolName.
392
+ // every member of HOSTED_TOOL_NAMES, and `name` is typed as ToolName.
361
393
  throw new Error(`agentmesh-mcp: no compiled output validator for tool "${name}"`);
362
394
  }
363
395
  return fn;
@@ -368,7 +400,7 @@ export function validateOutput(name) {
368
400
  // tool error BEFORE any upstream call or URL construction (e.g. a non-UUID card_id
369
401
  // is caught here rather than throwing inside encodeURIComponent).
370
402
  const compiledInputValidators = new Map();
371
- for (const name of TOOL_NAMES) {
403
+ for (const name of HOSTED_TOOL_NAMES) {
372
404
  compiledInputValidators.set(name, ajv.compile(TOOL_DEFS[name].inputSchema));
373
405
  }
374
406
  /** Look up the compiled Ajv validator for a tool's inputSchema. */
package/dist/server.js CHANGED
@@ -29,14 +29,15 @@
29
29
  * handler era-blind by construction instead of by coincidence.
30
30
  */
31
31
  import { Server } from "@modelcontextprotocol/server";
32
- import { TOOL_DEFS, TOOL_NAMES, validateInput } from "./schemas.js";
32
+ export { createMcpHandler } from "@modelcontextprotocol/server";
33
+ import { TOOL_DEFS, TOOL_NAMES, HOSTED_TOOL_NAMES, validateInput } from "./schemas.js";
33
34
  import { getTool, TOOL_ANNOTATIONS } from "./tools.js";
34
35
  import { redact } from "./redact.js";
35
36
  import { MCP_INSTRUCTIONS } from "./contract.js";
36
37
  const SERVER_NAME = "agentmesh-mcp";
37
38
  // Keep in lockstep with mcp/package.json "version" — the served serverInfo
38
39
  // version is what MCP clients log/display for support triage.
39
- const SERVER_VERSION = "0.1.1";
40
+ const SERVER_VERSION = "0.2.0";
40
41
  /** Compact, non-sensitive Ajv error text for an invalid-arguments tool error. */
41
42
  function formatValidationErrors(errors) {
42
43
  if (errors === null || errors === undefined || errors.length === 0) {
@@ -58,16 +59,18 @@ export const CHANNEL_INSTRUCTIONS = 'Messages from agentmesh.md arrive as <chann
58
59
  "have been delivered.";
59
60
  /** Builds a fully-wired MCP `Server` (ListTools + CallTool handlers). Does not connect a transport. */
60
61
  export function buildServer(opts = {}) {
62
+ const allowed = new Set(opts.allowedTools ?? TOOL_NAMES);
61
63
  const options = opts.channel === true
62
64
  ? { capabilities: { tools: {}, experimental: { "claude/channel": {} } } }
63
65
  : { capabilities: { tools: {} } };
64
- const server = new Server({ name: SERVER_NAME, version: SERVER_VERSION }, { ...options, instructions: MCP_INSTRUCTIONS + (opts.channel === true ? "\n" + CHANNEL_INSTRUCTIONS : "") });
66
+ const server = new Server({ name: SERVER_NAME, version: SERVER_VERSION }, { ...options, instructions: (opts.instructions ?? MCP_INSTRUCTIONS) + (opts.channel === true ? "\n" + CHANNEL_INSTRUCTIONS : "") });
65
67
  server.setRequestHandler("tools/list", async () => {
66
- const tools = TOOL_NAMES.map((name) => {
68
+ const tools = HOSTED_TOOL_NAMES.filter((name) => allowed.has(name)).map((name) => {
67
69
  const def = TOOL_DEFS[name];
68
70
  return {
69
71
  name,
70
- description: def.description,
72
+ title: TOOL_TITLES[name],
73
+ description: opts.descriptions?.[name] ?? def.description,
71
74
  // schemas.ts still types these against the 1.x SDK's `Tool` (Seam C
72
75
  // owns that file); the objects themselves are the checked-in JSON
73
76
  // Schema documents, Ajv-compiled at import, and structurally satisfy
@@ -89,7 +92,7 @@ export function buildServer(opts = {}) {
89
92
  });
90
93
  server.setRequestHandler("tools/call", async (request, ctx) => {
91
94
  const tool = getTool(request.params.name);
92
- if (tool === undefined) {
95
+ if (tool === undefined || !allowed.has(tool.name)) {
93
96
  return {
94
97
  isError: true,
95
98
  content: [{ type: "text", text: redact(`NOT_FOUND: unknown tool "${request.params.name}".`) }],
@@ -121,7 +124,8 @@ export function buildServer(opts = {}) {
121
124
  // re-types against v2 (flagged for Seam A).
122
125
  return server.projectCallToolResult(result, advertisedOutputSchema);
123
126
  }
124
- catch {
127
+ catch (error) {
128
+ opts.onToolError?.(error);
125
129
  // Defense in depth: a tool must never surface as a JSON-RPC protocol error
126
130
  // (PLAN section 3). Convert any unexpected throw into an isError result;
127
131
  // never echo the raw error (it could carry argument data).
@@ -133,3 +137,27 @@ export function buildServer(opts = {}) {
133
137
  });
134
138
  return server;
135
139
  }
140
+ const TOOL_TITLES = {
141
+ terminal_wake_start: "terminal wake start",
142
+ terminal_wake_poll: "terminal wake poll",
143
+ terminal_wake_receipt: "terminal wake receipt",
144
+ terminal_wake_checkin: "terminal wake checkin",
145
+ read_board: "Read workspace board", read_channels: "List workspace channels",
146
+ read_messages: "Read channel messages", list_asks: "List workspace asks",
147
+ get_my_instructions: "Read your instructions",
148
+ whoami: "Show connected identity", post_message: "Post channel message",
149
+ claim_card: "Claim a board card", complete_card: "Complete a claimed card",
150
+ create_card: "Create a board card", read_roster: "Read workspace roster",
151
+ list_conversations: "List your conversations", create_conversation: "Create a conversation",
152
+ read_conversation_messages: "Read conversation messages",
153
+ post_conversation_message: "Post conversation message",
154
+ edit_card: "Edit card",
155
+ assign_card: "Assign card",
156
+ create_ask: "Create ask",
157
+ claim_ask: "Claim ask",
158
+ resolve_ask: "Resolve ask",
159
+ list_documents: "List documents",
160
+ read_document: "Read document",
161
+ create_document: "Create document",
162
+ edit_document: "Edit document",
163
+ };
@@ -0,0 +1,9 @@
1
+ // Never include exception messages, provider bodies or raw stacks. Only known
2
+ // classes and our own module/line identities may reach terminal/MCP output.
3
+ export function terminalDiagnostic(error, file, fn) {
4
+ const name = error instanceof Error ? error.constructor.name : 'Error';
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+\)/);
7
+ const here = new Error().stack?.split('\n')[2]?.match(/:(\d+):\d+\)?$/)?.[1] ?? '0';
8
+ return `${safe.includes(name) ? name : 'DependencyError'} at ${frame ? frame[2] + '.js' : file}:${frame?.[1] ?? fn}:${frame?.[3] ?? here}`;
9
+ }
@@ -0,0 +1,177 @@
1
+ import fs from 'node:fs';
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');
22
+ }
23
+ return version;
24
+ }
25
+ function exitOf(child) {
26
+ return new Promise((resolve, reject) => { child.once('error', () => reject(new Error('RuntimeStartFailed'))); child.once('exit', code => resolve(code ?? 1)); });
27
+ }
28
+ async function stopOwned(child) {
29
+ if (child.exitCode !== null || child.signalCode !== null)
30
+ 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
+ }
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.0', 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); }, };
70
+ }
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);
102
+ }
103
+ request(method, params) {
104
+ const id = ++this.serial;
105
+ return new Promise((resolve, reject) => {
106
+ const timer = setTimeout(() => { this.pending.delete(id); reject(new Error('CodexRpcTimeout')); }, 15_000);
107
+ this.pending.set(id, { resolve, reject, timer });
108
+ this.ws.send(JSON.stringify({ id, method, params }));
109
+ });
110
+ }
111
+ notify(method) { this.ws.send(JSON.stringify({ method })); }
112
+ close() { this.ws.close(); }
113
+ }
114
+ export async function codexRuntime({ runDir, profile, entry, bindingId, cwd, agentId, workspaceId }) {
115
+ const endpoint = `unix://${path.join(runDir, 'codex.sock')}`;
116
+ const config = ['-c', `mcp_servers.agentmesh.command=${JSON.stringify(process.execPath)}`,
117
+ '-c', `mcp_servers.agentmesh.args=${JSON.stringify([entry, 'bridge', path.join(runDir, 'broker.sock')])}`];
118
+ const server = spawn('codex', ['app-server', '--listen', endpoint, ...config], { cwd, stdio: 'ignore' });
119
+ let serverError = false;
120
+ server.once('error', () => { serverError = true; });
121
+ let tui;
122
+ let rpc;
123
+ 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.0' } });
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
+ };
171
+ }
172
+ catch (error) {
173
+ rpc?.close();
174
+ await stopOwned(server);
175
+ throw error;
176
+ }
177
+ }
package/dist/tools.js CHANGED
@@ -31,7 +31,7 @@
31
31
  * PLAN Appendix A.
32
32
  */
33
33
  import { callApi } from "./client.js";
34
- import { TOOL_NAMES, validateOutput } from "./schemas.js";
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
37
  // ---- small, defensive arg readers ----
@@ -120,6 +120,9 @@ async function listAsks(args, signal) {
120
120
  });
121
121
  return finish("list_asks", result);
122
122
  }
123
+ async function getMyInstructions(_args, signal) {
124
+ return finish("get_my_instructions", await callApi({ method: "GET", path: "/me/instructions", signal }));
125
+ }
123
126
  async function whoami(_args, signal) {
124
127
  const result = await callApi({ method: "GET", path: "/me", signal });
125
128
  return finish("whoami", result);
@@ -358,12 +361,90 @@ async function createCard(args, signal) {
358
361
  });
359
362
  return finish("create_card", result);
360
363
  }
364
+ // Member tools reuse the existing API guards, audit, CAS/version rules and retry keys.
365
+ async function edit_card(args, signal) {
366
+ return finish("edit_card", await callApi({
367
+ method: "POST", path: `/cards/${encodeURIComponent(String(args["card_id"]))}/edit`, signal,
368
+ body: { title: args["title"], body_md: args["body_md"] },
369
+ idempotencyKey: crypto.randomUUID(),
370
+ }));
371
+ }
372
+ async function assign_card(args, signal) {
373
+ return finish("assign_card", await callApi({
374
+ method: "POST", path: `/cards/${encodeURIComponent(String(args["card_id"]))}/assign`, signal,
375
+ body: { assignee_kind: args["assignee_kind"], assignee_id: args["assignee_id"] },
376
+ idempotencyKey: crypto.randomUUID(),
377
+ }));
378
+ }
379
+ async function create_ask(args, signal) {
380
+ return finish("create_ask", await callApi({
381
+ method: "POST", path: "/asks", signal,
382
+ body: { text: args["text"], ttl_minutes: args["ttl_minutes"] },
383
+ idempotencyKey: crypto.randomUUID(),
384
+ }));
385
+ }
386
+ async function claim_ask(args, signal) {
387
+ return finish("claim_ask", await callApi({
388
+ method: "POST", path: `/asks/${encodeURIComponent(String(args["ask_id"]))}/claim`, signal,
389
+ body: {},
390
+ idempotencyKey: crypto.randomUUID(),
391
+ }));
392
+ }
393
+ async function resolve_ask(args, signal) {
394
+ return finish("resolve_ask", await callApi({
395
+ method: "POST", path: `/asks/${encodeURIComponent(String(args["ask_id"]))}/resolve`, signal,
396
+ body: { note: args["note"] },
397
+ idempotencyKey: crypto.randomUUID(),
398
+ }));
399
+ }
400
+ async function list_documents(args, signal) {
401
+ return finish("list_documents", await callApi({
402
+ method: "GET", path: "/docs", signal,
403
+ query: { lifecycle: stringArg(args, "lifecycle") },
404
+ }));
405
+ }
406
+ async function read_document(args, signal) {
407
+ return finish("read_document", await callApi({
408
+ method: "GET", path: `/docs/${encodeURIComponent(String(args["document_id"]))}`, signal,
409
+ }));
410
+ }
411
+ async function create_document(args, signal) {
412
+ return finish("create_document", await callApi({
413
+ method: "POST", path: "/docs", signal,
414
+ body: { title: args["title"], body_md: args["body_md"], collection: args["collection"], tags: args["tags"], summary: args["summary"] },
415
+ idempotencyKey: crypto.randomUUID(),
416
+ }));
417
+ }
418
+ async function edit_document(args, signal) {
419
+ return finish("edit_document", await callApi({
420
+ method: "POST", path: `/docs/${encodeURIComponent(String(args["document_id"]))}/edit`, signal,
421
+ body: { body_md: args["body_md"], expected_version: args["expected_version"], summary: args["summary"], allow_clear: args["allow_clear"] },
422
+ idempotencyKey: crypto.randomUUID(),
423
+ }));
424
+ }
425
+ async function terminal_wake_start(args, signal) {
426
+ return finish("terminal_wake_start", await callApi({ method: "POST", path: "/terminal-wakes/start", body: args, signal }));
427
+ }
428
+ async function terminal_wake_poll(args, signal) {
429
+ return finish("terminal_wake_poll", await callApi({ method: "POST", path: "/terminal-wakes/poll", body: args, signal }));
430
+ }
431
+ async function terminal_wake_receipt(args, signal) {
432
+ return finish("terminal_wake_receipt", await callApi({ method: "POST", path: "/terminal-wakes/receipt", body: args, signal }));
433
+ }
434
+ async function terminal_wake_checkin(args, signal) {
435
+ return finish("terminal_wake_checkin", await callApi({ method: "POST", path: "/terminal-wakes/checkin", body: args, signal }));
436
+ }
361
437
  // ---- registry ----
362
438
  export const TOOLS = {
439
+ terminal_wake_start: { name: "terminal_wake_start", run: terminal_wake_start },
440
+ terminal_wake_poll: { name: "terminal_wake_poll", run: terminal_wake_poll },
441
+ terminal_wake_receipt: { name: "terminal_wake_receipt", run: terminal_wake_receipt },
442
+ terminal_wake_checkin: { name: "terminal_wake_checkin", run: terminal_wake_checkin },
363
443
  read_board: { name: "read_board", run: readBoard },
364
444
  read_channels: { name: "read_channels", run: readChannels },
365
445
  read_messages: { name: "read_messages", run: readMessages },
366
446
  list_asks: { name: "list_asks", run: listAsks },
447
+ get_my_instructions: { name: "get_my_instructions", run: getMyInstructions },
367
448
  whoami: { name: "whoami", run: whoami },
368
449
  post_message: { name: "post_message", run: postMessage },
369
450
  claim_card: { name: "claim_card", run: claimCard },
@@ -374,6 +455,15 @@ export const TOOLS = {
374
455
  create_conversation: { name: "create_conversation", run: createConversation },
375
456
  read_conversation_messages: { name: "read_conversation_messages", run: readConversationMessages },
376
457
  post_conversation_message: { name: "post_conversation_message", run: postConversationMessage },
458
+ edit_card: { name: "edit_card", run: edit_card },
459
+ assign_card: { name: "assign_card", run: assign_card },
460
+ create_ask: { name: "create_ask", run: create_ask },
461
+ claim_ask: { name: "claim_ask", run: claim_ask },
462
+ resolve_ask: { name: "resolve_ask", run: resolve_ask },
463
+ list_documents: { name: "list_documents", run: list_documents },
464
+ read_document: { name: "read_document", run: read_document },
465
+ create_document: { name: "create_document", run: create_document },
466
+ edit_document: { name: "edit_document", run: edit_document },
377
467
  };
378
468
  /**
379
469
  * Accurate per-tool annotations for all tools.
@@ -400,10 +490,15 @@ export const TOOLS = {
400
490
  * that wiring is FLAGGED to the integrator rather than edited here.
401
491
  */
402
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 },
403
497
  read_board: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
404
498
  read_channels: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
405
499
  read_messages: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
406
500
  list_asks: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
501
+ get_my_instructions: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
407
502
  whoami: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
408
503
  post_message: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
409
504
  claim_card: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
@@ -414,9 +509,18 @@ export const TOOL_ANNOTATIONS = {
414
509
  create_conversation: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
415
510
  read_conversation_messages: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
416
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 },
417
521
  };
418
522
  function isToolName(name) {
419
- return TOOL_NAMES.some((n) => n === name);
523
+ return HOSTED_TOOL_NAMES.some((n) => n === name);
420
524
  }
421
525
  /** Look up a registered tool by its wire-level name (which may be any string a client sends). */
422
526
  export function getTool(name) {
@@ -19,6 +19,7 @@
19
19
  */
20
20
  import fs from "node:fs";
21
21
  import path from "node:path";
22
+ import { writeAtomic } from "./wake-storage.js";
22
23
  import { findSessionPid } from "./session.js";
23
24
  export { findSessionPid };
24
25
  const INTERVAL_MS = 2_000;
@@ -87,6 +88,11 @@ export function drain(root, write, sessionPid) {
87
88
  if (!replay)
88
89
  fs.renameSync(file, sending);
89
90
  write(formatLine(item, replay));
91
+ if (mode["terminal"] === true && /^[a-f0-9-]{36}$/.test(String(item["key"]))) {
92
+ const receipts = path.join(dir, "receipts");
93
+ fs.mkdirSync(receipts, { recursive: true, mode: 0o700 });
94
+ writeAtomic(path.join(receipts, `${String(item["key"])}.json`), { transport: true });
95
+ }
90
96
  fs.rmSync(sending, { force: true });
91
97
  delivered += 1;
92
98
  }
@@ -0,0 +1,68 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ export function writeAtomic(file, data) {
4
+ const tmp = `${file}.${process.pid}.tmp`;
5
+ const fd = fs.openSync(tmp, "w", 0o600);
6
+ try {
7
+ fs.writeSync(fd, JSON.stringify(data));
8
+ fs.fsyncSync(fd);
9
+ }
10
+ finally {
11
+ fs.closeSync(fd);
12
+ }
13
+ fs.renameSync(tmp, file);
14
+ }
15
+ export function readJson(file) {
16
+ try {
17
+ return JSON.parse(fs.readFileSync(file, "utf8"));
18
+ }
19
+ catch (err) {
20
+ if (err.code === "ENOENT")
21
+ return undefined;
22
+ throw err;
23
+ }
24
+ }
25
+ export function pidAlive(pid) {
26
+ try {
27
+ process.kill(pid, 0);
28
+ return true;
29
+ }
30
+ catch (err) {
31
+ return err.code === "EPERM";
32
+ }
33
+ }
34
+ /**
35
+ * One reader per agent directory. While a live owner holds it, wake waits in
36
+ * this process (tools still work). A lock whose owner pid is gone is taken over once.
37
+ * Residual (review O1): two servers starting in the same instant on a dead
38
+ * lock can race.
39
+ */
40
+ export function claimLock(dir) {
41
+ const lock = path.join(dir, "reader.pid");
42
+ for (let attempt = 0; attempt < 2; attempt += 1) {
43
+ try {
44
+ const fd = fs.openSync(lock, "wx", 0o600);
45
+ fs.writeSync(fd, String(process.pid));
46
+ fs.closeSync(fd);
47
+ process.once("exit", () => {
48
+ try {
49
+ if (fs.readFileSync(lock, "utf8") === String(process.pid))
50
+ fs.unlinkSync(lock);
51
+ }
52
+ catch {
53
+ /* already gone */
54
+ }
55
+ });
56
+ return true;
57
+ }
58
+ catch (err) {
59
+ if (err.code !== "EEXIST")
60
+ throw err;
61
+ const owner = Number(fs.readFileSync(lock, "utf8"));
62
+ if (Number.isInteger(owner) && owner > 0 && pidAlive(owner))
63
+ return false;
64
+ fs.rmSync(lock, { force: true });
65
+ }
66
+ }
67
+ return false;
68
+ }