@zieglar/pi-chat-exchange 0.3.2 → 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.
@@ -0,0 +1,33 @@
1
+ #!/usr/bin/env node
2
+ /** Explicit local operator command. No Store, sender, credentials or remote mutation. */
3
+ import { parseArgs, isDeepStrictEqual } from "node:util";
4
+ import { readPrivateMessagingFile } from "../tunnel/messaging-config.js";
5
+ import { parseMcpBindingConfig } from "../host/mcp-binding-config.js";
6
+ import { createEndpointRuntimeBinding } from "../tunnel/endpoint-runtime-binding.js";
7
+ try {
8
+ const { values } = parseArgs({ options: { config: { type: "string" }, action: { type: "string" }, "runtime-id": { type: "string" },
9
+ "expected-revision": { type: "string" }, "accept-endpoint-scope": { type: "boolean" } } });
10
+ const action = values.action, path = values.config;
11
+ if (path === undefined || !["show", "set", "revoke"].includes(action ?? ""))
12
+ throw new Error("CE_RUNTIME_BINDING_INVALID");
13
+ if (action === "show" && !isDeepStrictEqual(Object.keys(values).sort(), ["action", "config"]) ||
14
+ action === "revoke" && values["runtime-id"] !== undefined || action === "set" && values["runtime-id"] === undefined)
15
+ throw new Error("CE_RUNTIME_BINDING_INVALID");
16
+ const file = readPrivateMessagingFile(path);
17
+ if (file === undefined)
18
+ throw new Error("CE_RUNTIME_BINDING_INVALID");
19
+ const config = parseMcpBindingConfig(JSON.parse(file.bytes.toString("utf8")));
20
+ const binding = createEndpointRuntimeBinding(path, config);
21
+ const selection = action === "show" ? binding.read() : binding.update({ runtimeId: action === "revoke" ? null : values["runtime-id"],
22
+ expectedRevision: values["expected-revision"], acceptEndpointScope: values["accept-endpoint-scope"] });
23
+ console.log(JSON.stringify({ scopeNotice: "CE Endpoint selection shared by all callers of this launch; no ChatGPT conversation identity is attested; no permissions granted",
24
+ callerEndpoint: config.endpoint, selection }));
25
+ if (selection.status === "unavailable")
26
+ process.exitCode = 1;
27
+ }
28
+ catch (error) {
29
+ const message = error instanceof Error ? error.message : "";
30
+ console.error(JSON.stringify({ error: /^CE_RUNTIME_BINDING_(INVALID|CONFLICT|RUNTIME_UNAVAILABLE|WRITE_UNCERTAIN)$/.test(message) ? message : "CE_RUNTIME_BINDING_INVALID" }));
31
+ process.exitCode = 1;
32
+ }
33
+ //# sourceMappingURL=ce-runtime-binding.js.map
@@ -39,7 +39,10 @@ import { createMcpPolicyAdmission } from "../tunnel/multi-session-admission.js";
39
39
  import { CeHookRunner } from "../hooks/runner.js";
40
40
  import { isDeepStrictEqual } from "node:util";
41
41
  import { effectiveMcpHookRules, readLoadedMultiSessionPolicy, readSelectedMultiSessionPolicy } from "../tunnel/multi-session-policy.js";
42
- import { createLiveMcpComposition, projectEndpointDiscovery, observeLiveMcpRuntime } from "../tunnel/live-mcp-composition.js";
42
+ import { createLiveMcpComposition, discoverLiveEndpoints, observeLiveMcpRuntime } from "../tunnel/live-mcp-composition.js";
43
+ import { createTaskOwnerComposition } from "./task-owner-composition.js";
44
+ import { createSourceMetadataProbe } from "../control/mcp/source-metadata-probe.js";
45
+ import { sourceMetadataProbeLaunchDigest } from "../runtime/source-metadata-probe-opt-in.js";
43
46
  debugEvent("server", "SERVER_ENTRY", { version: process.version });
44
47
  // Monitor rather than handle exceptions: preserve Node's fatal exit behavior.
45
48
  process.on("uncaughtExceptionMonitor", (error, origin) => {
@@ -137,24 +140,28 @@ async function main() {
137
140
  ack: { enabled: config.ack.enabled },
138
141
  onMessageCommitted: event => hookRunner.publish(event),
139
142
  });
140
- debugEvent("authority", "AUTHORITY_CHECK_STARTED", { stage: "requireUnowned" });
141
- const bound = CeBoundEndpoint.start(host, config.endpoint.endpointId, {
142
- renewIntervalMs: config.lease.renewIntervalSeconds * 1_000,
143
- ...(admission === undefined ? {} : { admission }),
144
- onEvent: (event) => {
145
- debugEvent("authority", "AUTHORITY_CHECK_RESULT", { stage: event.kind });
146
- if (event.kind === "renewed")
147
- return;
148
- // Codes only; renewal_deferred is retryable at the next tick,
149
- // renewal_stopped has already blocked new sends.
150
- console.error(event.kind === "renewal_deferred"
151
- ? `CE_MCP_RENEWAL_DEFERRED code=${event.code}`
152
- : `CE_MCP_RENEWAL_STOPPED code=${event.code}`);
153
- },
154
- });
155
- debugEvent("authority", "OWNERSHIP_ACQUIRED", { owned: true });
143
+ let bound;
156
144
  let probe;
157
145
  try {
146
+ debugEvent("authority", "AUTHORITY_CHECK_STARTED", { stage: "requireUnowned" });
147
+ const activeBound = CeBoundEndpoint.start(host, config.endpoint.endpointId, {
148
+ renewIntervalMs: config.lease.renewIntervalSeconds * 1_000,
149
+ ...(admission === undefined ? {} : { admission }),
150
+ onEvent: (event) => {
151
+ debugEvent("authority", "AUTHORITY_CHECK_RESULT", { stage: event.kind });
152
+ if (event.kind === "renewed")
153
+ return;
154
+ // Codes only; renewal_deferred is retryable at the next tick,
155
+ // renewal_stopped has already blocked new sends.
156
+ console.error(event.kind === "renewal_deferred"
157
+ ? `CE_MCP_RENEWAL_DEFERRED code=${event.code}`
158
+ : `CE_MCP_RENEWAL_STOPPED code=${event.code}`);
159
+ },
160
+ });
161
+ bound = activeBound;
162
+ debugEvent("authority", "OWNERSHIP_ACQUIRED", { owned: true });
163
+ const taskOwner = createTaskOwnerComposition(configPath, config, live, host, activeBound);
164
+ const sourceMetadataProbe = createSourceMetadataProbe(launchDigest, sourceMetadataProbeLaunchDigest());
158
165
  if (live !== undefined) {
159
166
  try {
160
167
  const output = execFileSync("/bin/ps", ["-p", String(process.pid), "-o", "lstart="], {
@@ -165,7 +172,7 @@ async function main() {
165
172
  throw new Error("process identity unavailable");
166
173
  probe = await startLiveAdoptionProbe({ ref: live.ref, launchDigest,
167
174
  identity: { pid: process.pid, startedKey: match[1] },
168
- observe: () => observeLiveMcpRuntime(live, host, bound, store, config.endpoint.endpointId), });
175
+ observe: () => observeLiveMcpRuntime(live, host, activeBound, store, config.endpoint.endpointId), });
169
176
  }
170
177
  catch {
171
178
  // Local observation is advisory. Unsupported socket paths/identity cannot
@@ -176,11 +183,12 @@ async function main() {
176
183
  // HANDOFF-CE-E2B-01: advertise `ce_ack` only when the validated binding
177
184
  // declares the ack opt-in; the default surface stays exactly four tools.
178
185
  const server = createExchangeMcpServer(undefined, {
179
- port: bound, ackEnabled: config.ack.enabled, executionGuard: config.debugExecutionGuard,
186
+ port: activeBound, ackEnabled: config.ack.enabled, executionGuard: config.debugExecutionGuard,
187
+ ...(taskOwner ?? {}),
180
188
  ...(live === undefined
181
189
  ? admission === undefined ? {} : { admission: () => admission({ kind: "inbox" }) }
182
- : { discovery: { discover: () => projectEndpointDiscovery(bound.discover()) } }),
183
- });
190
+ : { discovery: { discover: (previousEndpointId, runtimeId, useRuntimeBinding, group) => discoverLiveEndpoints(live, activeBound, previousEndpointId, runtimeId, useRuntimeBinding, group) } }),
191
+ }, sourceMetadataProbe);
184
192
  if (config.debugExecutionGuard.enabled) {
185
193
  debugEvent("server", "EXECUTION_GUARD_ARMED", { scope: "tools/call", stage: "unified-dispatch-entry" });
186
194
  }
@@ -199,7 +207,7 @@ async function main() {
199
207
  // Transport already gone; the lease release below is what matters.
200
208
  }
201
209
  const hookCleanup = hookRunner.close();
202
- const shutdown = await bound.shutdown();
210
+ const shutdown = await activeBound.shutdown();
203
211
  debugEvent("authority", "OWNERSHIP_RELEASED", { released: shutdown.released, detached: shutdown.detached });
204
212
  console.error(shutdown.released
205
213
  ? `CE_MCP_STOPPED released=true detached=${shutdown.detached}`
@@ -230,6 +238,7 @@ async function main() {
230
238
  ...MESSAGING_TOOL_NAMES,
231
239
  ...(config.ack.enabled ? [CE_ACK_TOOL.name] : []),
232
240
  ...(live === undefined ? [] : ["ce_endpoints"]),
241
+ ...(taskOwner === undefined ? [] : ["ce_task_owner"]),
233
242
  ];
234
243
  console.error(`CE_MCP_STARTED tools=${advertisedTools.join(",")}`);
235
244
  await shutdownRequested;
@@ -242,7 +251,7 @@ async function main() {
242
251
  finally {
243
252
  const hooks = hookRunner.close();
244
253
  try {
245
- await bound.shutdown();
254
+ await bound?.shutdown();
246
255
  }
247
256
  finally {
248
257
  await hooks;
@@ -0,0 +1,47 @@
1
+ import { createTaskOwnerRegistryPort, loadTaskOwnershipSidecar } from "../control/mcp/task-owner-registry.js";
2
+ const INVALID = "CE_MCP_TASK_OWNERSHIP_INVALID";
3
+ const DENIED = "CE_MCP_TASK_OWNERSHIP_DENIED";
4
+ /** Compose TaskOwner only from a private sidecar and the current live Session.
5
+ * Runtime selection, endpoint binding and delivery outcomes grant no ownership. */
6
+ export function createTaskOwnerComposition(configPath, config, live, host, bound) {
7
+ const sidecar = loadTaskOwnershipSidecar(configPath);
8
+ if (sidecar === undefined)
9
+ return undefined;
10
+ if (live === undefined)
11
+ throw new Error(INVALID);
12
+ const loaded = live.snapshot();
13
+ const activePi = loaded.manifest.registrations.filter(registration => registration.status === "active" &&
14
+ config.recipients.some(recipient => recipient.adapter === "pi" && recipient.endpointId === registration.endpointId));
15
+ const selected = sidecar.piEndpoint === undefined
16
+ ? activePi.length === 1 ? activePi[0] : undefined
17
+ : activePi.find(registration => registration.endpointId === sidecar.piEndpoint);
18
+ if (selected === undefined || (sidecar.piEndpoint === undefined && activePi.length !== 1))
19
+ throw new Error(INVALID);
20
+ const initial = host.status(config.endpoint.endpointId);
21
+ if (initial.lease !== "ACTIVE" || initial.exchangeId === undefined)
22
+ throw new Error(INVALID);
23
+ const scope = Object.freeze({ exchangeId: initial.exchangeId, from: selected.endpointId, to: config.endpoint.endpointId });
24
+ const taskOwner = createTaskOwnerRegistryPort(sidecar.registryDirectory, scope);
25
+ const taskOwnerAdmission = () => {
26
+ const operational = bound.operationalStatus();
27
+ const status = host.status(config.endpoint.endpointId);
28
+ if (operational.state !== "ACTIVE" || operational.renewal !== "RUNNING" || status.lease !== "ACTIVE" ||
29
+ status.exchangeId !== scope.exchangeId)
30
+ throw new Error(DENIED);
31
+ const prepared = live.recipients.snapshot();
32
+ const current = live.snapshot();
33
+ if (!prepared.recipients.some(recipient => recipient.adapter === "pi" && recipient.endpointId === scope.from) ||
34
+ !current.manifest.registrations.some(registration => registration.endpointId === scope.from &&
35
+ registration.runtimeSessionId === selected.runtimeSessionId && registration.epoch === selected.epoch && registration.status === "active")) {
36
+ throw new Error(DENIED);
37
+ }
38
+ try {
39
+ live.admission({ kind: "inbox" }, prepared);
40
+ }
41
+ catch {
42
+ throw new Error(DENIED);
43
+ }
44
+ };
45
+ return Object.freeze({ taskOwner, taskOwnerAdmission });
46
+ }
47
+ //# sourceMappingURL=task-owner-composition.js.map
@@ -3,6 +3,7 @@
3
3
  import { Type } from "@sinclair/typebox";
4
4
  import { Value } from "@sinclair/typebox/value";
5
5
  import { ErrorCode, McpError } from "@modelcontextprotocol/sdk/types.js";
6
+ import { normalizeRuntimeGroup, RUNTIME_GROUP_PATTERN } from "../../runtime/runtime-group.js";
6
7
  export const CE_ENDPOINTS_TOOL_NAME = "ce_endpoints";
7
8
  const closed = { additionalProperties: false };
8
9
  const identity = {
@@ -10,6 +11,25 @@ const identity = {
10
11
  endpointId: Type.String({ minLength: 1, maxLength: 256 }),
11
12
  };
12
13
  const state = Type.Union([Type.Literal("true"), Type.Literal("false"), Type.Literal("unknown")]);
14
+ const previousEndpoint = Type.String({ minLength: 1, maxLength: 256 });
15
+ export const SessionSwitchResultSchema = Type.Union([
16
+ Type.Object({ status: Type.Literal("unknown"), previousEndpointId: previousEndpoint }, closed),
17
+ Type.Object({ status: Type.Literal("verified"), previousEndpointId: previousEndpoint, successorEndpointId: previousEndpoint,
18
+ source: Type.Literal("pi.new.lifecycle"), observedAt: Type.String({ pattern: "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]{3}Z$" }) }, closed),
19
+ ]);
20
+ const runtimeId = Type.String({ pattern: "^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$" });
21
+ const timestamp = Type.String({ pattern: "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}[.][0-9]{3}Z$" });
22
+ export const CurrentBindingResultSchema = Type.Union([
23
+ Type.Object({ status: Type.Union([Type.Literal("unknown"), Type.Literal("ambiguous")]), runtimeId }, closed),
24
+ Type.Object({ status: Type.Literal("verified"), runtimeId, endpointId: previousEndpoint,
25
+ source: Type.Literal("pi.runtime.lifecycle"), observedAt: timestamp, expiresAt: timestamp }, closed),
26
+ ]);
27
+ const selectionFields = { scope: Type.Literal("ce-endpoint"), group: Type.Optional(Type.String({ pattern: RUNTIME_GROUP_PATTERN })) };
28
+ const RuntimeSelectionSchema = Type.Union([
29
+ Type.Object({ ...selectionFields, status: Type.Literal("unavailable") }, closed),
30
+ Type.Object({ ...selectionFields, status: Type.Literal("unbound"), revision: Type.String({ pattern: "^(unbound|[a-f0-9]{64})$" }) }, closed),
31
+ Type.Object({ ...selectionFields, status: Type.Literal("bound"), revision: Type.String({ pattern: "^[a-f0-9]{64}$" }), runtimeId }, closed),
32
+ ]);
13
33
  export const EndpointDiscoveryResultSchema = Type.Object({
14
34
  self: Type.Object({
15
35
  ...identity,
@@ -27,24 +47,44 @@ export const EndpointDiscoveryResultSchema = Type.Object({
27
47
  Type.Literal("MCP_OPERATION_BLOCKED"),
28
48
  ]),
29
49
  }, closed), { maxItems: 128 }),
50
+ sessionSwitch: Type.Optional(SessionSwitchResultSchema),
51
+ runtimes: Type.Optional(Type.Array(Type.Object({ runtimeId }, closed), { maxItems: 128 })),
52
+ currentBinding: Type.Optional(CurrentBindingResultSchema),
53
+ runtimeSelection: Type.Optional(RuntimeSelectionSchema),
30
54
  observedAt: Type.String({ pattern: "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]{3}Z$" }),
31
55
  viewDigest: Type.String({ pattern: "^[0-9a-f]{64}$" }),
32
56
  }, closed);
33
- const argsSchema = Type.Object({}, closed);
57
+ const legacyArgs = Type.Object({ previousEndpointId: Type.Optional(previousEndpoint), runtimeId: Type.Optional(runtimeId) }, closed);
58
+ const boundArgs = Type.Object({ useRuntimeBinding: Type.Literal(true) }, closed);
59
+ const groupArgs = Type.Object({ group: Type.String({ minLength: 1, maxLength: 256 }) }, closed);
60
+ const argsSchema = Type.Union([legacyArgs, boundArgs, groupArgs]);
34
61
  export const CE_ENDPOINTS_TOOL = {
35
62
  name: CE_ENDPOINTS_TOOL_NAME,
36
- description: "Read this caller's own identity and authorized exact targets. Advisory observations only; sends recheck authority. Ambiguous targets require explicit user selection.",
37
- inputSchema: { ...argsSchema },
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
+ inputSchema: { ...Type.Object({ ...legacyArgs.properties, useRuntimeBinding: Type.Optional(Type.Literal(true)), group: Type.Optional(groupArgs.properties.group) }, closed),
65
+ oneOf: [legacyArgs, boundArgs, groupArgs] },
38
66
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
39
67
  };
40
68
  export function callEndpointDiscovery(port, args) {
41
69
  if (!Value.Check(argsSchema, args)) {
42
- throw new McpError(ErrorCode.InvalidParams, "endpoint discovery takes no arguments");
70
+ throw new McpError(ErrorCode.InvalidParams, "invalid endpoint discovery query");
71
+ }
72
+ let group;
73
+ if ("group" in args) {
74
+ try {
75
+ group = normalizeRuntimeGroup(args.group);
76
+ }
77
+ catch {
78
+ throw new McpError(ErrorCode.InvalidParams, "invalid runtime group");
79
+ }
43
80
  }
44
81
  try {
45
82
  // Snapshot once into plain JSON, then validate the exact bytes to be exposed.
46
83
  // This also prevents custom serialization from bypassing the closed schema.
47
- const text = JSON.stringify(port.discover());
84
+ const text = JSON.stringify("group" in args ? port.discover(undefined, undefined, undefined, group)
85
+ : "useRuntimeBinding" in args ? port.discover(undefined, undefined, true)
86
+ : args.runtimeId !== undefined ? port.discover(args.previousEndpointId, args.runtimeId)
87
+ : args.previousEndpointId === undefined ? port.discover() : port.discover(args.previousEndpointId));
48
88
  const result = JSON.parse(text);
49
89
  if (!Value.Check(EndpointDiscoveryResultSchema, result))
50
90
  throw new Error();
@@ -23,8 +23,9 @@ import { observeTransport } from "./debug-transport.js";
23
23
  import { PING_TOOL_NAME, PingArgsSchema, PingResultSchema, defaultHostLabel, ping } from "./ping.js";
24
24
  import { callMessagingTool, CE_ACK_TOOL, isAckToolName, isMessagingToolName, MESSAGING_TOOLS, } from "./messaging-tools.js";
25
25
  import { callEndpointDiscovery, CE_ENDPOINTS_TOOL, CE_ENDPOINTS_TOOL_NAME } from "./endpoint-discovery.js";
26
+ import { callTaskOwner, CE_TASK_OWNER_TOOL, CE_TASK_OWNER_TOOL_NAME } from "./task-owner.js";
26
27
  export const SERVER_NAME = "pi-chat-exchange";
27
- export const SERVER_VERSION = "0.3.2";
28
+ export const SERVER_VERSION = "0.3.3";
28
29
  const PING_TOOL = {
29
30
  name: PING_TOOL_NAME,
30
31
  description: "Read-only liveness probe for the pi-chat-exchange service. " +
@@ -38,7 +39,7 @@ const PING_TOOL = {
38
39
  openWorldHint: false,
39
40
  },
40
41
  };
41
- export function createExchangeMcpServer(hostLabel = defaultHostLabel(), messaging = undefined) {
42
+ export function createExchangeMcpServer(hostLabel = defaultHostLabel(), messaging = undefined, sourceMetadataProbe) {
42
43
  const server = new Server({ name: SERVER_NAME, version: SERVER_VERSION }, { capabilities: { tools: {} } });
43
44
  debugEvent("server", "SERVER_CREATED");
44
45
  // NOTE: the line below is a pinned check-contract anchor (ping-only by
@@ -48,7 +49,8 @@ export function createExchangeMcpServer(hostLabel = defaultHostLabel(), messagin
48
49
  // HANDOFF-CE-E2B-01: `ce_ack` is advertised last, and only on the explicit
49
50
  // operator ack opt-in carried by the binding.
50
51
  const withAck = messaging?.ackEnabled === true ? [...tools, CE_ACK_TOOL] : tools;
51
- const advertised = messaging?.discovery === undefined ? withAck : [...withAck, CE_ENDPOINTS_TOOL];
52
+ const withDiscovery = messaging?.discovery === undefined ? withAck : [...withAck, CE_ENDPOINTS_TOOL];
53
+ const advertised = messaging?.taskOwner === undefined ? withDiscovery : [...withDiscovery, CE_TASK_OWNER_TOOL];
52
54
  for (const tool of advertised)
53
55
  debugEvent("tool", "TOOL_REGISTERED", { tool: tool.name });
54
56
  const admit = () => {
@@ -66,7 +68,7 @@ export function createExchangeMcpServer(hostLabel = defaultHostLabel(), messagin
66
68
  });
67
69
  server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
68
70
  const { name, arguments: args } = request.params;
69
- const tool = isMessagingToolName(name) || isAckToolName(name) || name === PING_TOOL_NAME ? name : "unknown-tool";
71
+ const tool = isMessagingToolName(name) || isAckToolName(name) || name === PING_TOOL_NAME || name === CE_TASK_OWNER_TOOL_NAME ? name : "unknown-tool";
70
72
  const started = Date.now();
71
73
  // HANDOFF-CE-DIAG-06: the single unified dispatch entry. When the
72
74
  // development execution guard is armed, refuse BEFORE any business
@@ -87,6 +89,18 @@ export function createExchangeMcpServer(hostLabel = defaultHostLabel(), messagin
87
89
  admit();
88
90
  debugEvent("tool", "TOOL_CALL_STARTED", { tool, args: argumentShape(args) });
89
91
  try {
92
+ if (name === CE_TASK_OWNER_TOOL_NAME) {
93
+ if (messaging?.taskOwner === undefined) {
94
+ throw new McpError(ErrorCode.MethodNotFound, "unknown tool: ce_task_owner");
95
+ }
96
+ try {
97
+ messaging.taskOwnerAdmission?.();
98
+ }
99
+ catch {
100
+ throw new McpError(ErrorCode.InternalError, "runtime admission denied");
101
+ }
102
+ return callTaskOwner(messaging.taskOwner, args ?? {});
103
+ }
90
104
  // HANDOFF-CE-E2B-01: `ce_ack` exists only behind the explicit opt-in; a
91
105
  // call without it fails closed exactly like an unadvertised tool.
92
106
  if (name === CE_ENDPOINTS_TOOL_NAME) {
@@ -127,6 +141,11 @@ export function createExchangeMcpServer(hostLabel = defaultHostLabel(), messagin
127
141
  if (!Value.Check(PingArgsSchema, args ?? {})) {
128
142
  throw new McpError(ErrorCode.InvalidParams, "ping takes no arguments; unexpected argument shape rejected");
129
143
  }
144
+ // Trusted diagnostics only: invalid, denied, and non-ping calls never sample.
145
+ try {
146
+ sourceMetadataProbe?.(extra._meta);
147
+ }
148
+ catch { /* Preserve the frozen ping behavior. */ }
130
149
  const result = ping(hostLabel);
131
150
  if (!Value.Check(PingResultSchema, result)) {
132
151
  // Defensive: the result is constructed in-process, but never serve a
@@ -0,0 +1,46 @@
1
+ import { createHmac, randomBytes } from "node:crypto";
2
+ import { writeSync } from "node:fs";
3
+ /** Opt-in is supplied by the trusted launch owner, never tool arguments or _meta. */
4
+ export function createSourceMetadataProbe(launchDigest, enabledLaunchDigest = undefined, emit = row => { writeSync(2, JSON.stringify(row) + "\n"); }) {
5
+ if (!/^[a-f0-9]{64}$/.test(launchDigest) || enabledLaunchDigest !== launchDigest)
6
+ return undefined;
7
+ const key = randomBytes(32);
8
+ let consumed = false;
9
+ return metadata => {
10
+ if (consumed)
11
+ return;
12
+ // Missing/malformed metadata and failed logging still consume this trial.
13
+ consumed = true;
14
+ let observation = { event: "SOURCE_METADATA_OBSERVATION", present: false, type: "missing" };
15
+ try {
16
+ if (metadata !== undefined && (metadata === null || typeof metadata !== "object" || Array.isArray(metadata))) {
17
+ observation = { ...observation, type: "invalid-metadata" };
18
+ }
19
+ else if (metadata !== undefined) {
20
+ const field = Object.getOwnPropertyDescriptor(metadata, "openai/session");
21
+ if (field !== undefined) {
22
+ if (!("value" in field))
23
+ observation = { ...observation, present: true, type: "accessor" };
24
+ else {
25
+ const value = field.value;
26
+ observation = { ...observation, present: true, type: value === null ? "null" : Array.isArray(value) ? "array" : typeof value };
27
+ if (typeof value === "string" && value.length > 0 && value.length <= 4096) {
28
+ // The private key prevents dictionary matching and cross-probe correlation.
29
+ const digest = createHmac("sha256", key)
30
+ .update(JSON.stringify(["ce.source-metadata.v1", launchDigest, value])).digest("hex");
31
+ observation = { ...observation, digest };
32
+ }
33
+ }
34
+ }
35
+ }
36
+ }
37
+ catch {
38
+ observation = { ...observation, present: false, type: "unreadable" };
39
+ }
40
+ try {
41
+ emit(observation);
42
+ }
43
+ catch { /* Diagnostics must never alter tool behavior. */ }
44
+ };
45
+ }
46
+ //# sourceMappingURL=source-metadata-probe.js.map
@@ -0,0 +1,113 @@
1
+ import fs from "node:fs";
2
+ import { isAbsolute, join, parse, resolve, sep } from "node:path";
3
+ import { validMessageId, validRegisteredTaskOwner } from "./task-owner.js";
4
+ const MAX_BYTES = 16_384;
5
+ const INVALID = "CE_MCP_TASK_OWNERSHIP_INVALID";
6
+ function invalid() { throw new Error(INVALID); }
7
+ function parseFlatUniqueJson(bytes) {
8
+ try {
9
+ const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
10
+ const value = JSON.parse(text);
11
+ if (typeof value !== "object" || value === null || Array.isArray(value) ||
12
+ Object.values(value).some(item => typeof item === "object" && item !== null))
13
+ return invalid();
14
+ const keys = new Set();
15
+ for (const match of text.matchAll(/"(?:\\.|[^"\\])*"/g)) {
16
+ if (!/^\s*:/.test(text.slice((match.index ?? 0) + match[0].length)))
17
+ continue;
18
+ const key = JSON.parse(match[0]);
19
+ if (typeof key !== "string" || keys.has(key))
20
+ return invalid();
21
+ keys.add(key);
22
+ }
23
+ return value;
24
+ }
25
+ catch {
26
+ return invalid();
27
+ }
28
+ }
29
+ function assertPrivateDirectory(directory) {
30
+ if (!isAbsolute(directory) || resolve(directory) !== directory)
31
+ return invalid();
32
+ const root = parse(directory).root;
33
+ let current = root;
34
+ for (const part of directory.slice(root.length).split(sep).filter(Boolean)) {
35
+ current = join(current, part);
36
+ const info = fs.lstatSync(current);
37
+ if (!info.isDirectory() || info.isSymbolicLink())
38
+ return invalid();
39
+ }
40
+ const info = fs.lstatSync(directory);
41
+ if ((info.mode & 0o7777) !== 0o700 || (process.geteuid !== undefined && info.uid !== process.geteuid()))
42
+ return invalid();
43
+ }
44
+ function readPrivateBounded(path) {
45
+ const fd = fs.openSync(path, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
46
+ try {
47
+ const info = fs.fstatSync(fd);
48
+ if (!info.isFile() || info.size > MAX_BYTES || (info.mode & 0o7777) !== 0o600 || info.nlink !== 1 ||
49
+ (process.geteuid !== undefined && info.uid !== process.geteuid()))
50
+ return invalid();
51
+ const bytes = Buffer.alloc(MAX_BYTES + 1);
52
+ let length = 0;
53
+ while (length < bytes.length) {
54
+ const count = fs.readSync(fd, bytes, length, bytes.length - length, null);
55
+ if (count === 0)
56
+ break;
57
+ length += count;
58
+ }
59
+ if (length > MAX_BYTES)
60
+ return invalid();
61
+ return bytes.subarray(0, length);
62
+ }
63
+ finally {
64
+ fs.closeSync(fd);
65
+ }
66
+ }
67
+ export function loadTaskOwnershipSidecar(configPath) {
68
+ if (!isAbsolute(configPath) || resolve(configPath) !== configPath)
69
+ return invalid();
70
+ const path = `${configPath}.task-ownership.json`;
71
+ try {
72
+ fs.lstatSync(path);
73
+ }
74
+ catch (error) {
75
+ if (error.code === "ENOENT")
76
+ return undefined;
77
+ return invalid();
78
+ }
79
+ try {
80
+ const value = parseFlatUniqueJson(readPrivateBounded(path));
81
+ const expectedKeys = "piEndpoint" in value ? 3 : 2;
82
+ if (Object.keys(value).length !== expectedKeys || value.schemaVersion !== 1 || typeof value.registryDirectory !== "string" ||
83
+ value.registryDirectory.includes("\0") || !isAbsolute(value.registryDirectory) || resolve(value.registryDirectory) !== value.registryDirectory)
84
+ return invalid();
85
+ const piEndpoint = value.piEndpoint;
86
+ if ("piEndpoint" in value && (typeof piEndpoint !== "string" || !/^pi\/[A-Za-z0-9-]{1,64}$/.test(piEndpoint)))
87
+ return invalid();
88
+ return { schemaVersion: 1, registryDirectory: value.registryDirectory,
89
+ ...(typeof piEndpoint === "string" ? { piEndpoint } : {}) };
90
+ }
91
+ catch {
92
+ return invalid();
93
+ }
94
+ }
95
+ export function createTaskOwnerRegistryPort(directory, scope) {
96
+ return Object.freeze({ lookup(messageId) {
97
+ const unverified = { messageId, ownerStatus: "UNVERIFIED" };
98
+ if (!validMessageId(messageId))
99
+ return unverified;
100
+ try {
101
+ assertPrivateDirectory(directory);
102
+ const candidate = parseFlatUniqueJson(readPrivateBounded(join(directory, `${messageId}.json`)));
103
+ if (!validRegisteredTaskOwner(candidate) || candidate.messageId !== messageId || candidate.exchangeId !== scope.exchangeId ||
104
+ candidate.from !== scope.from || candidate.to !== scope.to || candidate.taskOwner !== scope.from)
105
+ return unverified;
106
+ return candidate;
107
+ }
108
+ catch {
109
+ return unverified;
110
+ }
111
+ } });
112
+ }
113
+ //# sourceMappingURL=task-owner-registry.js.map
@@ -0,0 +1,49 @@
1
+ import { Type } from "@sinclair/typebox";
2
+ import { Value } from "@sinclair/typebox/value";
3
+ import { ErrorCode, McpError } from "@modelcontextprotocol/sdk/types.js";
4
+ export const CE_TASK_OWNER_TOOL_NAME = "ce_task_owner";
5
+ const MessageIdSchema = Type.String({ pattern: "^msg_[0-9A-HJKMNP-TV-Z]{26}$" });
6
+ const LabelSchema = Type.String({ minLength: 1, maxLength: 4096 });
7
+ const closed = { additionalProperties: false };
8
+ const TaskOwnerArgsSchema = Type.Object({ messageId: MessageIdSchema }, closed);
9
+ const RegisteredTaskOwnerSchema = Type.Object({
10
+ schemaVersion: Type.Literal(1),
11
+ exchangeId: LabelSchema,
12
+ requestMessageId: MessageIdSchema,
13
+ messageId: MessageIdSchema,
14
+ from: LabelSchema,
15
+ to: LabelSchema,
16
+ projectLabel: LabelSchema,
17
+ taskOwner: LabelSchema,
18
+ ownerStatus: Type.Literal("REGISTERED"),
19
+ probeId: Type.String({ pattern: "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89aAbB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$" }),
20
+ }, closed);
21
+ export const CE_TASK_OWNER_TOOL = {
22
+ name: CE_TASK_OWNER_TOOL_NAME,
23
+ description: "Read registered task ownership metadata for one exact message ID. UNVERIFIED means no matching verified registration is available.",
24
+ inputSchema: { ...TaskOwnerArgsSchema },
25
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
26
+ };
27
+ export function validMessageId(value) {
28
+ return Value.Check(MessageIdSchema, value);
29
+ }
30
+ export function validRegisteredTaskOwner(value) {
31
+ return Value.Check(RegisteredTaskOwnerSchema, value);
32
+ }
33
+ export function callTaskOwner(port, args) {
34
+ if (!Value.Check(TaskOwnerArgsSchema, args)) {
35
+ throw new McpError(ErrorCode.InvalidParams, "exact messageId required; other arguments are rejected");
36
+ }
37
+ const messageId = args.messageId;
38
+ let result = { messageId, ownerStatus: "UNVERIFIED" };
39
+ try {
40
+ const candidate = JSON.parse(JSON.stringify(port.lookup(messageId)));
41
+ if (validRegisteredTaskOwner(candidate) && candidate.messageId === messageId)
42
+ result = candidate;
43
+ }
44
+ catch {
45
+ // A registry failure never grants ownership and never exposes its details.
46
+ }
47
+ return { content: [{ type: "text", text: JSON.stringify(result) }], structuredContent: result, isError: false };
48
+ }
49
+ //# sourceMappingURL=task-owner.js.map
@@ -0,0 +1,10 @@
1
+ export const RUNTIME_GROUP_PATTERN = "^[a-z0-9][a-z0-9._-]{0,63}$";
2
+ /** Canonicalize the operator-supplied group label before any lookup or write. */
3
+ export function normalizeRuntimeGroup(name) {
4
+ const normalized = name.normalize("NFKC").toLowerCase();
5
+ if (!new RegExp(RUNTIME_GROUP_PATTERN).test(normalized)) {
6
+ throw new Error("CE_RUNTIME_BINDING_INVALID");
7
+ }
8
+ return normalized;
9
+ }
10
+ //# sourceMappingURL=runtime-group.js.map
@@ -0,0 +1,6 @@
1
+ /** Trusted launch-only environment boundary. MCP control and composition stay
2
+ * environment-free; the returned digest is still matched to the exact launch. */
3
+ export function sourceMetadataProbeLaunchDigest() {
4
+ return process.env.CE_SOURCE_METADATA_PROBE_LAUNCH_DIGEST;
5
+ }
6
+ //# sourceMappingURL=source-metadata-probe-opt-in.js.map