@zieglar/pi-chat-exchange 0.3.4 → 0.3.5

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 CHANGED
@@ -64,6 +64,7 @@ The wake notice carries fixed instructions and message identifiers only; the act
64
64
 
65
65
  - [Native management](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/native-management.md) and [Native SQLite](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/native-sqlite.md).
66
66
  - [Tunnel setup and troubleshooting](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/tunnel-setup.md).
67
+ - [Local HTTP MCP runtime](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/http-mcp-runtime.md): an independently managed Unix socket transport with the existing binding and authorization.
67
68
  - [Multiple Sessions](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/multi-session-usage.md), [Pi tools](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/pi-extension/README.md), [local Hooks](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/hooks.md) and [ACK contract](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/delivery-ack-contract.md).
68
69
  - [Operations / source development](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/operations.md). The prebuilt npm install needs no repository or compiler.
69
70
  - [Independent Host / tarball installation](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/independent-install.md), with current0.2.1 alternatives and a separate historical0.2.0 record.
@@ -34,6 +34,7 @@ import { CeBoundEndpoint } from "../host/bound-endpoint.js";
34
34
  import { McpBindingConfigError, MCP_BINDING_CONFIG_MAX_BYTES, parseMcpBindingConfig, } from "../host/mcp-binding-config.js";
35
35
  import { debugEvent, errorSummary } from "../control/debug-log.js";
36
36
  import { observeTransport } from "../control/mcp/debug-transport.js";
37
+ import { startLocalMcpHttp } from "../control/mcp/http-transport.js";
37
38
  import { initializeStore, openStore } from "../storage/store.js";
38
39
  import { createMcpPolicyAdmission } from "../tunnel/multi-session-admission.js";
39
40
  import { CeHookRunner } from "../hooks/runner.js";
@@ -103,9 +104,10 @@ async function main() {
103
104
  await runStdioServer();
104
105
  return;
105
106
  }
106
- const [flag, configPath] = argv;
107
- if (argv.length !== 2 || flag !== "--config" || configPath === undefined || !configPath.startsWith("/")) {
108
- fail("CE_MCP_LAUNCH_INVALID", "usage: mcp-stdio.js [--config /absolute/path.json]");
107
+ const [flag, configPath, socketFlag, socketPath] = argv;
108
+ if ((argv.length !== 2 && argv.length !== 4) || flag !== "--config" || configPath === undefined || !configPath.startsWith("/") ||
109
+ (argv.length === 4 && (socketFlag !== "--http-socket" || socketPath === undefined || !socketPath.startsWith("/")))) {
110
+ fail("CE_MCP_LAUNCH_INVALID", "usage: mcp-stdio.js --config /absolute/path.json [--http-socket /absolute/path.sock]");
109
111
  }
110
112
  const { config, launchDigest } = loadBindingConfig(configPath);
111
113
  // Verify actual launch bytes before Store creation; managed provenance grants nothing.
@@ -182,18 +184,18 @@ async function main() {
182
184
  }
183
185
  // HANDOFF-CE-E2B-01: advertise `ce_ack` only when the validated binding
184
186
  // declares the ack opt-in; the default surface stays exactly four tools.
185
- const server = createExchangeMcpServer(undefined, {
187
+ const createServer = () => createExchangeMcpServer(undefined, {
186
188
  port: activeBound, ackEnabled: config.ack.enabled, executionGuard: config.debugExecutionGuard,
187
189
  ...(taskOwner ?? {}),
188
190
  ...(live === undefined
189
191
  ? admission === undefined ? {} : { admission: () => admission({ kind: "inbox" }) }
190
- : { discovery: { discover: (previousEndpointId, runtimeId, useRuntimeBinding, group) => discoverLiveEndpoints(live, activeBound, previousEndpointId, runtimeId, useRuntimeBinding, group) } }),
192
+ : { discovery: { discover: (previousEndpointId, runtimeId, useRuntimeBinding, group) => discoverLiveEndpoints(live, activeBound, previousEndpointId, runtimeId, useRuntimeBinding, group) }, selectedTarget: live.selectedTarget }),
191
193
  }, sourceMetadataProbe);
194
+ const server = socketPath === undefined ? createServer() : undefined;
195
+ let http;
192
196
  if (config.debugExecutionGuard.enabled) {
193
197
  debugEvent("server", "EXECUTION_GUARD_ARMED", { scope: "tools/call", stage: "unified-dispatch-entry" });
194
198
  }
195
- const transport = observeTransport(new StdioServerTransport());
196
- debugEvent("server", "TRANSPORT_CREATED");
197
199
  let initiated = false;
198
200
  const initiateShutdown = async () => {
199
201
  if (initiated)
@@ -201,7 +203,8 @@ async function main() {
201
203
  initiated = true;
202
204
  await probe?.close();
203
205
  try {
204
- await server.close();
206
+ await http?.close();
207
+ await server?.close();
205
208
  }
206
209
  catch {
207
210
  // Transport already gone; the lease release below is what matters.
@@ -224,10 +227,16 @@ async function main() {
224
227
  // disposition and killing the process before the lease is released.
225
228
  process.on("SIGTERM", () => { debugEvent("process", "PROCESS_SIGNAL", { signal: "SIGTERM" }); requestShutdown(); });
226
229
  process.on("SIGINT", () => { debugEvent("process", "PROCESS_SIGNAL", { signal: "SIGINT" }); requestShutdown(); });
227
- process.stdin.once("end", requestShutdown);
228
- process.stdin.once("close", requestShutdown);
229
- server.onclose = requestShutdown;
230
- await server.connect(transport);
230
+ if (server !== undefined) {
231
+ debugEvent("server", "TRANSPORT_CREATED");
232
+ process.stdin.once("end", requestShutdown);
233
+ process.stdin.once("close", requestShutdown);
234
+ server.onclose = requestShutdown;
235
+ await server.connect(observeTransport(new StdioServerTransport()));
236
+ }
237
+ else {
238
+ http = await startLocalMcpHttp(socketPath, createServer);
239
+ }
231
240
  debugEvent("server", "TRANSPORT_CONNECTED");
232
241
  debugEvent("server", "SERVER_READY", { mode: "bound" });
233
242
  // HANDOFF-CE-E2B-01: the diagnostic mirrors exactly what the server above
@@ -48,6 +48,7 @@ export const EndpointDiscoveryResultSchema = Type.Object({
48
48
  ]),
49
49
  }, closed), { maxItems: 128 }),
50
50
  sessionSwitch: Type.Optional(SessionSwitchResultSchema),
51
+ selectedTarget: Type.Optional(Type.Object({ endpointId: previousEndpoint, generation: Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER }), scope: Type.Literal("shared-mcp-endpoint") }, closed)),
51
52
  runtimes: Type.Optional(Type.Array(Type.Object({ runtimeId }, closed), { maxItems: 128 })),
52
53
  currentBinding: Type.Optional(CurrentBindingResultSchema),
53
54
  runtimeSelection: Type.Optional(RuntimeSelectionSchema),
@@ -60,7 +61,7 @@ const groupArgs = Type.Object({ group: Type.String({ minLength: 1, maxLength: 25
60
61
  const argsSchema = Type.Union([legacyArgs, boundArgs, groupArgs]);
61
62
  export const CE_ENDPOINTS_TOOL = {
62
63
  name: CE_ENDPOINTS_TOOL_NAME,
63
- description: "Read this caller's authorized targets. Use group:<name> to explicitly resolve a local operator's named Runtime group to its independently authorized current Session. Alternatively use runtimeId or useRuntimeBinding:true; do not combine selectors. Groups and unnamed bindings are CE Endpoint scoped. No permissions, receipt or task ownership are inferred; ce_send still requires an exact Endpoint and rechecks authority.",
64
+ description: "Read this caller's authorized targets. Use group:<name> to explicitly resolve a local operator's named Runtime group to its independently authorized current Session. Alternatively use runtimeId or useRuntimeBinding:true; do not combine selectors. Groups and unnamed bindings are CE Endpoint scoped. A selectedTarget, when present, is shared across conversations; refresh its generation before selected sends. No permissions, receipt or task ownership are inferred; ce_send rechecks authority.",
64
65
  inputSchema: { ...Type.Object({ ...legacyArgs.properties, useRuntimeBinding: Type.Optional(Type.Literal(true)), group: Type.Optional(groupArgs.properties.group) }, closed),
65
66
  oneOf: [legacyArgs, boundArgs, groupArgs] },
66
67
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
@@ -0,0 +1,48 @@
1
+ import { chmodSync } from "node:fs";
2
+ import { createServer } from "node:http";
3
+ import { assertPrivateSocketDirectory } from "../../runtime/private-unix-socket.js";
4
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
5
+ /** The socket directory is the access boundary: only its owner may reach the MCP endpoint. */
6
+ export async function startLocalMcpHttp(socketPath, createMcpServer) {
7
+ assertPrivateSocketDirectory(socketPath);
8
+ const http = createServer((req, res) => {
9
+ if (req.headers.origin !== undefined || req.headers.host !== "localhost") {
10
+ res.writeHead(403).end();
11
+ return;
12
+ }
13
+ if (req.method !== "POST" || req.url !== "/mcp") {
14
+ res.writeHead(404).end();
15
+ return;
16
+ }
17
+ const server = createMcpServer();
18
+ const transport = new StreamableHTTPServerTransport({ enableJsonResponse: true });
19
+ res.once("close", () => { void server.close(); });
20
+ void (async () => {
21
+ // SAFETY: SDK HTTP transport implements Transport at runtime; accessor optionality differs under exactOptionalPropertyTypes.
22
+ await server.connect(transport);
23
+ await transport.handleRequest(req, res);
24
+ })().catch(() => {
25
+ if (!res.headersSent)
26
+ res.writeHead(500).end();
27
+ else
28
+ res.destroy();
29
+ void server.close();
30
+ });
31
+ });
32
+ await new Promise((resolve, reject) => {
33
+ http.once("error", reject);
34
+ http.listen(socketPath, () => {
35
+ http.removeListener("error", reject);
36
+ resolve();
37
+ });
38
+ });
39
+ try {
40
+ chmodSync(socketPath, 0o600);
41
+ }
42
+ catch (error) {
43
+ await new Promise(resolve => http.close(() => resolve()));
44
+ throw error;
45
+ }
46
+ return { close: () => new Promise((resolve, reject) => http.close(error => error ? reject(error) : resolve())) };
47
+ }
48
+ //# sourceMappingURL=http-transport.js.map
@@ -26,7 +26,9 @@ export const MESSAGING_TOOL_NAMES = [CE_SEND_TOOL_NAME, CE_INBOX_LIST_TOOL_NAME,
26
26
  export const CE_ACK_TOOL_NAME = "ce_ack";
27
27
  const closed = { additionalProperties: false };
28
28
  export const SendArgsSchema = Type.Object({
29
- to: Type.String({ minLength: 1, maxLength: 256, description: "Exact recipient label selected from a fresh ce_endpoints result in live mode; do not infer the latest Session" }),
29
+ to: Type.Optional(Type.String({ minLength: 1, maxLength: 256, description: "Explicit recipient; never overridden by a selected target" })),
30
+ selectionVersion: Type.Optional(Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER, description: "Version returned by ce_endpoints for the shared selected target" })),
31
+ replyTo: Type.Optional(Type.String({ pattern: "^msg_[0-9A-HJKMNP-TV-Z]{26}$", description: "Request Message ID for a reply; use an explicit recipient" })),
30
32
  text: Type.String({ minLength: 1, description: "Text to deliver; stored as the private payload" }),
31
33
  idempotencyKey: Type.String({ minLength: 1, maxLength: 256, description: "Stable key; a replay returns the original record" }),
32
34
  }, closed);
@@ -57,7 +59,9 @@ export const MESSAGING_TOOLS = [
57
59
  name: CE_SEND_TOOL_NAME,
58
60
  description: "Send one durable chat-exchange item from this server's fixed, operator-configured endpoint to an " +
59
61
  "operator-authorized recipient label. Idempotent by idempotencyKey. The sender is never a parameter. " +
60
- "In live mode, call ce_endpoints before choosing a recipient. Do not reuse a recipient label from an " +
62
+ "Use an explicit to, or obtain the current shared MCP Endpoint selection from ce_endpoints and provide its selectionVersion. " +
63
+ "This selection is shared across ChatGPT conversations; if it changes or the target is offline, sending is refused. " +
64
+ "Never provide both to and selectionVersion. Do not reuse a recipient label from an " +
61
65
  "earlier conversation; ambiguous targets require explicit user selection. CREATED/REPLAYED does not prove " +
62
66
  "receiver reading or task completion. If the result is CE_HOST_UNCERTAIN the outcome is unknown: do not " +
63
67
  "retry; ask the operator to inspect.",
@@ -159,14 +163,14 @@ export function isAckToolName(name) {
159
163
  /** Validate the closed schema, then call the bound port. Schema failures throw
160
164
  * `MessagingArgsError` (mapped to JSON-RPC invalid params by the server);
161
165
  * port refusals become sanitized `isError` tool results. */
162
- export function callMessagingTool(port, name, args) {
166
+ export function callMessagingTool(port, name, args, selection) {
163
167
  const input = args ?? {};
164
168
  switch (name) {
165
169
  case CE_SEND_TOOL_NAME: {
166
- if (!Value.Check(SendArgsSchema, input))
170
+ if (!Value.Check(SendArgsSchema, input) || input.to === undefined || input.selectionVersion !== undefined)
167
171
  throw new MessagingArgsError(name);
168
172
  try {
169
- const sent = port.send({ to: input.to, text: input.text, idempotencyKey: input.idempotencyKey });
173
+ const sent = port.send({ to: input.to, text: input.text, idempotencyKey: input.idempotencyKey, ...(input.replyTo === undefined ? {} : { replyTo: input.replyTo }) }, selection);
170
174
  const evidence = {
171
175
  disposition: sent.disposition,
172
176
  messageId: sent.messageId,
@@ -17,15 +17,16 @@
17
17
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
18
18
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
19
19
  import { CallToolRequestSchema, ErrorCode, ListToolsRequestSchema, McpError, } from "@modelcontextprotocol/sdk/types.js";
20
+ import { Type } from "@sinclair/typebox";
20
21
  import { Value } from "@sinclair/typebox/value";
21
22
  import { argumentShape, debugEvent, errorSummary } from "../debug-log.js";
22
23
  import { observeTransport } from "./debug-transport.js";
23
24
  import { PING_TOOL_NAME, PingArgsSchema, PingResultSchema, defaultHostLabel, ping } from "./ping.js";
24
- import { callMessagingTool, CE_ACK_TOOL, isAckToolName, isMessagingToolName, MESSAGING_TOOLS, } from "./messaging-tools.js";
25
+ import { callMessagingTool, CE_ACK_TOOL, CE_SEND_TOOL_NAME, SendArgsSchema, isAckToolName, isMessagingToolName, MESSAGING_TOOLS, } from "./messaging-tools.js";
25
26
  import { callEndpointDiscovery, CE_ENDPOINTS_TOOL, CE_ENDPOINTS_TOOL_NAME } from "./endpoint-discovery.js";
26
27
  import { callTaskOwner, CE_TASK_OWNER_TOOL, CE_TASK_OWNER_TOOL_NAME } from "./task-owner.js";
27
28
  export const SERVER_NAME = "pi-chat-exchange";
28
- export const SERVER_VERSION = "0.3.4";
29
+ export const SERVER_VERSION = "0.3.5";
29
30
  const PING_TOOL = {
30
31
  name: PING_TOOL_NAME,
31
32
  description: "Read-only liveness probe for the pi-chat-exchange service. " +
@@ -39,6 +40,8 @@ const PING_TOOL = {
39
40
  openWorldHint: false,
40
41
  },
41
42
  };
43
+ const FIND_REPLIES_SCHEMA = Type.Object({ requestMessageId: Type.String({ pattern: "^msg_[0-9A-HJKMNP-TV-Z]{26}$" }), afterMessageId: Type.Optional(Type.String({ pattern: "^msg_[0-9A-HJKMNP-TV-Z]{26}$" })) }, { additionalProperties: false });
44
+ const FIND_REPLIES_TOOL = { name: "ce_find_replies", description: "Find authorized reply message IDs for an original request. Reads metadata only; no ACK or consumption.", inputSchema: { ...FIND_REPLIES_SCHEMA }, annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false } };
42
45
  export function createExchangeMcpServer(hostLabel = defaultHostLabel(), messaging = undefined, sourceMetadataProbe) {
43
46
  const server = new Server({ name: SERVER_NAME, version: SERVER_VERSION }, { capabilities: { tools: {} } });
44
47
  debugEvent("server", "SERVER_CREATED");
@@ -50,7 +53,8 @@ export function createExchangeMcpServer(hostLabel = defaultHostLabel(), messagin
50
53
  // operator ack opt-in carried by the binding.
51
54
  const withAck = messaging?.ackEnabled === true ? [...tools, CE_ACK_TOOL] : tools;
52
55
  const withDiscovery = messaging?.discovery === undefined ? withAck : [...withAck, CE_ENDPOINTS_TOOL];
53
- const advertised = messaging?.taskOwner === undefined ? withDiscovery : [...withDiscovery, CE_TASK_OWNER_TOOL];
56
+ const withTaskOwner = messaging?.taskOwner === undefined ? withDiscovery : [...withDiscovery, CE_TASK_OWNER_TOOL];
57
+ const advertised = messaging?.port.findReplies === undefined ? withTaskOwner : [...withTaskOwner, FIND_REPLIES_TOOL];
54
58
  for (const tool of advertised)
55
59
  debugEvent("tool", "TOOL_REGISTERED", { tool: tool.name });
56
60
  const admit = () => {
@@ -89,6 +93,19 @@ export function createExchangeMcpServer(hostLabel = defaultHostLabel(), messagin
89
93
  admit();
90
94
  debugEvent("tool", "TOOL_CALL_STARTED", { tool, args: argumentShape(args) });
91
95
  try {
96
+ if (name === "ce_find_replies") {
97
+ if (!messaging?.port.findReplies)
98
+ throw new McpError(ErrorCode.MethodNotFound, "unknown tool");
99
+ if (!Value.Check(FIND_REPLIES_SCHEMA, args ?? {}))
100
+ throw new McpError(ErrorCode.InvalidParams, "invalid request Message ID");
101
+ try {
102
+ const result = messaging.port.findReplies(args);
103
+ return { content: [{ type: "text", text: JSON.stringify(result) }], structuredContent: result, isError: false };
104
+ }
105
+ catch {
106
+ return { content: [{ type: "text", text: "Reply lookup rejected or unavailable." }], isError: true };
107
+ }
108
+ }
92
109
  if (name === CE_TASK_OWNER_TOOL_NAME) {
93
110
  if (messaging?.taskOwner === undefined) {
94
111
  throw new McpError(ErrorCode.MethodNotFound, "unknown tool: ce_task_owner");
@@ -122,7 +139,22 @@ export function createExchangeMcpServer(hostLabel = defaultHostLabel(), messagin
122
139
  }
123
140
  try {
124
141
  debugEvent("tool", "TOOL_DISPATCH", { tool, stage: "bound-port" });
125
- const result = callMessagingTool(messaging.port, name, args ?? {});
142
+ let input = args ?? {};
143
+ let selectionMetadata;
144
+ if (name === CE_SEND_TOOL_NAME && Value.Check(SendArgsSchema, input) && input.selectionVersion !== undefined) {
145
+ if (input.to !== undefined)
146
+ return { content: [{ type: "text", text: "Choose either an explicit recipient or the shared selected target." }], isError: true };
147
+ const selection = messaging.selectedTarget?.();
148
+ const discovery = messaging.discovery?.discover();
149
+ const verified = messaging.selectedTarget?.();
150
+ if (!selection || selection.generation !== input.selectionVersion || verified?.generation !== selection.generation || verified.endpointId !== selection.endpointId ||
151
+ !discovery?.targets.some(t => t.endpointId === selection.endpointId && t.active === "true")) {
152
+ return { content: [{ type: "text", text: "Selected target unavailable or changed; refresh the shared selection." }], isError: true };
153
+ }
154
+ selectionMetadata = { policyId: selection.policyId, selectionVersion: selection.generation, targetRuntimeSessionId: selection.runtimeSessionId, bindingEpoch: selection.epoch };
155
+ input = { to: selection.endpointId, text: input.text, idempotencyKey: input.idempotencyKey, ...(input.replyTo === undefined ? {} : { replyTo: input.replyTo }) };
156
+ }
157
+ const result = callMessagingTool(messaging.port, name, input, selectionMetadata);
126
158
  debugEvent("tool", "TOOL_CALL_COMPLETED", { tool, isError: result.isError, durationMs: Date.now() - started });
127
159
  return result;
128
160
  }
@@ -130,8 +130,11 @@ export class CeBoundEndpoint {
130
130
  this.#inFlight -= 1;
131
131
  }
132
132
  }
133
- send(input) {
134
- return this.#run(true, { kind: "send", to: input.to }, () => this.#host.send(this.#endpointId, { to: input.to, text: input.text, idempotencyKey: input.idempotencyKey }));
133
+ send(input, selection) {
134
+ return this.#run(true, { kind: "send", to: input.to }, () => this.#host.send(this.#endpointId, input, selection));
135
+ }
136
+ findReplies(input) {
137
+ return this.#run(false, { kind: "inbox" }, () => this.#host.findReplies(this.#endpointId, input));
135
138
  }
136
139
  listInbox(input) {
137
140
  const request = {};
@@ -42,7 +42,7 @@ import { CreationDomainError } from "../storage/creation.js";
42
42
  import { createExchange } from "../storage/creation.js";
43
43
  import { CreationRequestError } from "../storage/creation-request.js";
44
44
  import { StoreLifecycleError } from "../storage/errors.js";
45
- import { readMessageMetadata, readMessagePayload, sendMessage, } from "../storage/messaging.js";
45
+ import { readMessageMetadata, readMessagePayload, sendMessage, findMessageReplies, bindNativeSession, bindSelectedSession, verifyTaskTarget, } from "../storage/messaging.js";
46
46
  import { discoverInboxMessages } from "../storage/inbox-discovery.js";
47
47
  import { captureFields, isParticipantId, isSessionId, ParticipantRequestError, } from "../storage/participant-identity.js";
48
48
  import { createParticipant, ParticipantDomainError, issueCapability, joinExchange, readParticipantByEndpoint, } from "../storage/participant.js";
@@ -591,11 +591,47 @@ export class CeEndpointHost {
591
591
  /** Session-authorized durable send. All authority comes from host memory;
592
592
  * the model supplies only the recipient label, the text, and an idempotency
593
593
  * key. */
594
- send(endpointId, input) {
594
+ /** Trusted Pi composition only: capture the active runtime's own binding. */
595
+ bindNativeSession(endpointId, runtimeSessionId, bindingEpoch) {
596
+ const authority = this.#authority(endpointId);
597
+ try {
598
+ bindNativeSession(this.#store, { participantId: authority.participantId, sessionId: authority.sessionId,
599
+ fencingToken: this.#currentFencing(authority), capability: authority.sendCapability, runtimeSessionId, bindingEpoch }, this.#seams);
600
+ }
601
+ catch (error) {
602
+ throw toRefusal(error);
603
+ }
604
+ }
605
+ bindSelectedSession(endpointId, target) {
606
+ const authority = this.#authority(endpointId);
607
+ try {
608
+ bindSelectedSession(this.#store, { ...target, participantId: authority.participantId, sessionId: authority.sessionId,
609
+ exchangeId: authority.exchangeId, fencingToken: this.#currentFencing(authority), capability: authority.sendCapability }, this.#seams);
610
+ }
611
+ catch (error) {
612
+ throw toRefusal(error);
613
+ }
614
+ }
615
+ verifyTaskTarget(endpointId, messageId) {
616
+ const authority = this.#authority(endpointId);
617
+ try {
618
+ return verifyTaskTarget(this.#store, { participantId: authority.participantId, sessionId: authority.sessionId, exchangeId: authority.exchangeId,
619
+ fencingToken: this.#currentFencing(authority), capability: authority.readCapability, messageId }, this.#seams);
620
+ }
621
+ catch (error) {
622
+ throw toRefusal(error);
623
+ }
624
+ }
625
+ send(endpointId, input, selection) {
595
626
  const authority = this.#authority(endpointId);
596
627
  if (!isPlainObject(input))
597
628
  throw new CeHostRefusal("CE_HOST_INVALID_REQUEST");
598
- const { to, text, idempotencyKey } = input;
629
+ if (Reflect.ownKeys(input).some(key => typeof key !== "string" || !["to", "text", "idempotencyKey", "replyTo"].includes(key))) {
630
+ throw new CeHostRefusal("CE_HOST_INVALID_REQUEST");
631
+ }
632
+ const { to, text, idempotencyKey, replyTo } = input;
633
+ if (replyTo !== undefined && (typeof replyTo !== "string" || selection !== undefined))
634
+ throw new CeHostRefusal("CE_HOST_INVALID_REQUEST");
599
635
  if (typeof to !== "string" || to.length === 0 || to.length > 256) {
600
636
  throw new CeHostRefusal("CE_HOST_INVALID_REQUEST");
601
637
  }
@@ -623,6 +659,7 @@ export class CeEndpointHost {
623
659
  sessionId: authority.sessionId,
624
660
  fencingToken,
625
661
  capability: authority.sendCapability,
662
+ ...(replyTo !== undefined ? { association: { requestMessageId: replyTo } } : selection !== undefined ? { association: selection } : {}),
626
663
  message: {
627
664
  exchangeId: authority.exchangeId,
628
665
  from: { adapter, endpointId },
@@ -826,6 +863,17 @@ export class CeEndpointHost {
826
863
  receiptAuditSequence: recorded.receiptAuditSequence,
827
864
  });
828
865
  }
866
+ findReplies(endpointId, input) {
867
+ const authority = this.#authority(endpointId);
868
+ try {
869
+ const request = captureFields(input, ["requestMessageId", "afterMessageId"], ["requestMessageId"], "request");
870
+ return findMessageReplies(this.#store, { ...request, participantId: authority.participantId, sessionId: authority.sessionId,
871
+ exchangeId: authority.exchangeId, capability: authority.readCapability, fencingToken: this.#currentFencing(authority) }, this.#seams);
872
+ }
873
+ catch (error) {
874
+ throw toRefusal(error);
875
+ }
876
+ }
829
877
  /** Explicit, bounded metadata discovery. Pagination grants no authority and
830
878
  * never advances ACK or delivery state. All CE authorization remains in Storage. */
831
879
  listInbox(endpointId, input) {
@@ -0,0 +1,51 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { lstatSync, realpathSync } from "node:fs";
3
+ import { dirname, isAbsolute, normalize } from "node:path";
4
+ /** Protect the path against replacement by a different OS user; same-UID processes are trusted. */
5
+ export function assertPrivateSocketDirectory(socketPath) {
6
+ if (!isAbsolute(socketPath) || normalize(socketPath) !== socketPath)
7
+ throw new Error("MCP socket path must be absolute and canonical");
8
+ const socketDirectory = dirname(socketPath);
9
+ if (realpathSync(socketDirectory) !== socketDirectory)
10
+ throw new Error("MCP socket directory must be canonical");
11
+ for (let path = socketDirectory;; path = dirname(path)) {
12
+ const stat = lstatSync(path);
13
+ const uid = process.geteuid?.();
14
+ const stickyRoot = stat.uid === 0 && (stat.mode & 0o1000) !== 0;
15
+ if (!stat.isDirectory() || (stat.uid !== uid && stat.uid !== 0) ||
16
+ (!stickyRoot && (stat.mode & 0o022) !== 0) ||
17
+ (path === socketDirectory && (stat.uid !== uid || (stat.mode & 0o077) !== 0))) {
18
+ throw new Error("MCP socket directory or ancestor is not private and trusted");
19
+ }
20
+ // A Darwin ACL can grant access independently of POSIX mode.
21
+ if (process.platform === "darwin") {
22
+ let acl;
23
+ try {
24
+ acl = execFileSync("/bin/ls", ["-lde", path], {
25
+ encoding: "utf8", timeout: 5_000, maxBuffer: 16_384,
26
+ env: { PATH: "/usr/bin:/bin", LC_ALL: "C" }, stdio: ["ignore", "pipe", "pipe"],
27
+ });
28
+ }
29
+ catch {
30
+ throw new Error("MCP socket directory ACL could not be verified");
31
+ }
32
+ const [header = "", ...entries] = acl.trimEnd().split("\n");
33
+ if (!/^[bcdlps-][rwxStTs-]{9}[+@ ]/.test(header) ||
34
+ entries.some(entry => !/^\s*\d+: \S+ deny [a-z_,]+$/.test(entry)) ||
35
+ (header[10] === "+" && entries.length === 0)) {
36
+ throw new Error("MCP socket directory ACL must not grant access");
37
+ }
38
+ }
39
+ if (dirname(path) === path)
40
+ break;
41
+ }
42
+ }
43
+ /** Revalidate before Tunnel spawn; a restarted Runtime may create a new inode. */
44
+ export function assertPrivateUnixSocket(socketPath) {
45
+ assertPrivateSocketDirectory(socketPath);
46
+ const socket = lstatSync(socketPath);
47
+ if (!socket.isSocket() || socket.uid !== process.geteuid?.() || (socket.mode & 0o7777) !== 0o600) {
48
+ throw new Error("MCP socket must be private and owned by the current user");
49
+ }
50
+ }
51
+ //# sourceMappingURL=private-unix-socket.js.map
@@ -439,10 +439,21 @@ function persistCapturedMessageSnapshot(tx, request, trusted) {
439
439
  }
440
440
  /** Package-private transaction-scoped B2 persistence. The caller owns the
441
441
  * IMMEDIATE transaction and all authorization ordering. */
442
- export function createMessageInTransaction(tx, request, trusted, hooks = {}) {
442
+ export function createMessageInTransaction(tx, request, trusted, hooks = {}, association) {
443
443
  const existing = replayMessage(tx, request);
444
- if (existing !== undefined)
444
+ if (existing !== undefined) {
445
+ const link = tx.prepare("SELECT request_message_id, policy_id, selection_version, target_runtime_session_id, binding_epoch FROM message_association WHERE message_id=? AND exchange_id=?").get(existing.message.messageId, request.exchangeId);
446
+ if (link === undefined) {
447
+ // A v7 message can be replayed without inventing historical association data.
448
+ if (association?.requestMessageId !== undefined || association?.selectionVersion !== undefined)
449
+ throw new CreationDomainError("IDEMPOTENCY_KEY_CONFLICT");
450
+ }
451
+ else if (link.request_message_id !== (association?.requestMessageId ?? existing.message.messageId) ||
452
+ link.policy_id !== (association?.policyId ?? null) || link.selection_version !== (association?.selectionVersion ?? null) ||
453
+ (association?.selectionVersion !== undefined && (link.target_runtime_session_id !== association.targetRuntimeSessionId || link.binding_epoch !== association.bindingEpoch)))
454
+ throw new CreationDomainError("IDEMPOTENCY_KEY_CONFLICT");
445
455
  return Object.freeze({ creation: existing });
456
+ }
446
457
  admitExchange(tx, request.exchangeId);
447
458
  if (tx
448
459
  .prepare("SELECT message_id FROM message WHERE exchange_id=? AND idempotency_key=?")
@@ -462,6 +473,7 @@ export function createMessageInTransaction(tx, request, trusted, hooks = {}) {
462
473
  });
463
474
  if (!Value.Check(MessageSchema, message))
464
475
  throw new Error("creation candidate failed frozen schema validation");
476
+ requireSingleRowChange(tx.prepare("INSERT INTO message_association(message_id, exchange_id, request_message_id, from_endpoint_json, to_endpoint_json, policy_id, selection_version, target_runtime_session_id, binding_epoch, target_owner_session_id, target_owner_fencing_token, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(message.messageId, message.exchangeId, association?.requestMessageId ?? message.messageId, request.fromEndpointJson, request.toEndpointJson, association?.policyId ?? null, association?.selectionVersion ?? null, association?.targetRuntimeSessionId ?? null, association?.bindingEpoch ?? null, association?.targetOwnerSessionId ?? null, association?.targetOwnerFencingToken ?? null, message.createdAt), "message association insert");
465
477
  persistCapturedMessageSnapshot(tx, request, trusted);
466
478
  hook(hooks.afterMessageInsert);
467
479
  requireSingleRowChange(tx