@zieglar/pi-chat-exchange 0.2.2 → 0.3.1
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 +11 -7
- package/dist/bin/mcp-stdio.js +124 -56
- package/dist/control/mcp/endpoint-discovery.js +60 -0
- package/dist/control/mcp/messaging-tools.js +12 -2
- package/dist/control/mcp/server.js +10 -2
- package/dist/hooks/config.js +106 -0
- package/dist/hooks/events.js +19 -0
- package/dist/hooks/runner.js +187 -0
- package/dist/host/bound-endpoint.js +19 -6
- package/dist/host/endpoint-host.js +92 -4
- package/dist/host/mcp-binding-config.js +41 -5
- package/dist/runtime/native-readiness.js +8 -5
- package/dist/storage/creation.js +16 -0
- package/dist/storage/ownership.js +45 -1
- package/dist/tunnel/background-authorization.js +343 -0
- package/dist/tunnel/background-manager.js +104 -8
- package/dist/tunnel/background-scope.js +69 -0
- package/dist/tunnel/codes.js +1 -1
- package/dist/tunnel/hooks-management-ui.js +225 -0
- package/dist/tunnel/hooks-management.js +431 -0
- package/dist/tunnel/live-adoption-observation.js +136 -0
- package/dist/tunnel/live-adoption-probe.js +240 -0
- package/dist/tunnel/live-connection-status.js +136 -0
- package/dist/tunnel/live-mcp-composition.js +143 -0
- package/dist/tunnel/live-process-observation.js +98 -0
- package/dist/tunnel/live-session-migration.js +169 -0
- package/dist/tunnel/live-session-policy.js +578 -0
- package/dist/tunnel/manager-panel.js +4 -2
- package/dist/tunnel/manager-ui.js +71 -15
- package/dist/tunnel/multi-session-admission.js +1 -1
- package/dist/tunnel/multi-session-policy.js +45 -13
- package/dist/tunnel/setup-ui.js +2 -4
- package/dist/tunnel/status-ui.js +34 -0
- package/package.json +4 -1
- package/pi-extension/allowlist.example.json +12 -1
- package/pi-extension/desktop-target.ts +157 -0
- package/pi-extension/index.ts +1128 -132
- package/pi-extension/live-session-profile.ts +49 -0
- package/pi-extension/live-session-runtime.ts +59 -0
- package/pi-extension/multi-session-commands.ts +114 -3
- package/pi-extension/multi-session-runtime.ts +63 -11
- package/pi-extension/native-inbound.ts +235 -0
- package/pi-extension/ownership-feedback.ts +100 -0
- package/pi-extension/session-onboarding.ts +154 -0
- package/pi-extension/session-recovery.ts +214 -0
- package/skills/ce-hook-script/SKILL.md +62 -0
- package/skills/ce-hook-script/examples/file-notification.py +79 -0
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { appendFileSync, closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { matchesHookRule } from "./config.js";
|
|
5
|
+
const MAX_PENDING = 32;
|
|
6
|
+
/** Best-effort local Hook execution. No Store queue, exactly-once claim, startup
|
|
7
|
+
* scan, retry, Payload exposure, or inherited child stdout/stderr. */
|
|
8
|
+
export class CeHookRunner {
|
|
9
|
+
#directory;
|
|
10
|
+
#rules;
|
|
11
|
+
#admit;
|
|
12
|
+
#queue = [];
|
|
13
|
+
#draining;
|
|
14
|
+
#closed = false;
|
|
15
|
+
constructor(options) {
|
|
16
|
+
this.#directory = options.directory;
|
|
17
|
+
this.#rules = Object.freeze([...options.rules]);
|
|
18
|
+
this.#admit = options.admit;
|
|
19
|
+
}
|
|
20
|
+
snapshot() {
|
|
21
|
+
const rules = Object.freeze(this.#rules.map(rule => Object.freeze({ ...rule, enabled: rule.enabled && this.#allowed(rule), recipient: Object.freeze({ ...rule.recipient }), args: Object.freeze([...rule.args]) })));
|
|
22
|
+
return Object.freeze({ configured: this.#rules.length, active: rules.filter(rule => rule.enabled).length, rules });
|
|
23
|
+
}
|
|
24
|
+
publish(input) {
|
|
25
|
+
try {
|
|
26
|
+
const event = Object.freeze({
|
|
27
|
+
schemaVersion: 1,
|
|
28
|
+
event: input.event,
|
|
29
|
+
eventId: input.eventId,
|
|
30
|
+
eventKey: input.eventKey,
|
|
31
|
+
messageId: input.messageId,
|
|
32
|
+
exchangeId: input.exchangeId,
|
|
33
|
+
sender: Object.freeze({ ...input.sender }),
|
|
34
|
+
recipient: Object.freeze({ ...input.recipient }),
|
|
35
|
+
createdAt: input.createdAt,
|
|
36
|
+
payloadDigest: input.payloadDigest,
|
|
37
|
+
payloadLength: input.payloadLength,
|
|
38
|
+
});
|
|
39
|
+
for (const rule of this.#rules) {
|
|
40
|
+
if (!matchesHookRule(rule, event))
|
|
41
|
+
continue;
|
|
42
|
+
if (this.#closed) {
|
|
43
|
+
this.#record(rule, event, "SKIPPED_SHUTDOWN", null, new Date().toISOString());
|
|
44
|
+
}
|
|
45
|
+
else if (this.#queue.length >= MAX_PENDING) {
|
|
46
|
+
this.#record(rule, event, "SKIPPED_QUEUE_FULL", null, new Date().toISOString());
|
|
47
|
+
}
|
|
48
|
+
else {
|
|
49
|
+
this.#queue.push(Object.freeze({ rule, event }));
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
if (this.#queue.length > 0 && this.#draining === undefined)
|
|
53
|
+
this.#startDrain();
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
// A local Hook is never allowed to change committed CE evidence.
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
async close() {
|
|
60
|
+
this.#closed = true;
|
|
61
|
+
const finishedAt = new Date().toISOString();
|
|
62
|
+
for (const item of this.#queue.splice(0))
|
|
63
|
+
this.#record(item.rule, item.event, "SKIPPED_SHUTDOWN", null, finishedAt);
|
|
64
|
+
await this.#draining;
|
|
65
|
+
}
|
|
66
|
+
#startDrain() {
|
|
67
|
+
const task = this.#drain().finally(() => {
|
|
68
|
+
if (this.#draining === task)
|
|
69
|
+
this.#draining = undefined;
|
|
70
|
+
if (!this.#closed && this.#queue.length > 0)
|
|
71
|
+
this.#startDrain();
|
|
72
|
+
});
|
|
73
|
+
this.#draining = task;
|
|
74
|
+
}
|
|
75
|
+
async #drain() {
|
|
76
|
+
try {
|
|
77
|
+
while (!this.#closed) {
|
|
78
|
+
const item = this.#queue.shift();
|
|
79
|
+
if (item === undefined)
|
|
80
|
+
break;
|
|
81
|
+
await this.#execute(item.rule, item.event);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
// Execution and recording failures are isolated by design.
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
#allowed(rule, event) {
|
|
89
|
+
try {
|
|
90
|
+
return this.#admit === undefined || this.#admit(rule, event);
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
return false;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
async #execute(rule, event) {
|
|
97
|
+
if (!this.#allowed(rule, event)) {
|
|
98
|
+
this.#record(rule, event, "SKIPPED_POLICY_DENIED", null, new Date().toISOString());
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
const startedAt = new Date().toISOString();
|
|
102
|
+
const startedMs = Date.now();
|
|
103
|
+
this.#record(rule, event, "STARTED", startedAt, null);
|
|
104
|
+
let child;
|
|
105
|
+
try {
|
|
106
|
+
child = spawn(rule.command, [...rule.args], {
|
|
107
|
+
shell: false,
|
|
108
|
+
cwd: this.#directory,
|
|
109
|
+
env: {
|
|
110
|
+
PATH: process.env.PATH ?? "",
|
|
111
|
+
HOME: process.env.HOME ?? "",
|
|
112
|
+
LANG: process.env.LANG ?? "",
|
|
113
|
+
},
|
|
114
|
+
stdio: ["pipe", "ignore", "ignore"],
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
catch {
|
|
118
|
+
this.#record(rule, event, "SPAWN_FAILED", startedAt, new Date().toISOString(), Date.now() - startedMs, null);
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
await new Promise((resolve) => {
|
|
122
|
+
let settled = false;
|
|
123
|
+
let timedOut = false;
|
|
124
|
+
const timer = setTimeout(() => {
|
|
125
|
+
timedOut = true;
|
|
126
|
+
try {
|
|
127
|
+
child.kill("SIGKILL");
|
|
128
|
+
}
|
|
129
|
+
catch { /* close still owns the result */ }
|
|
130
|
+
}, rule.timeoutMs);
|
|
131
|
+
const finish = (status, exitCode, signal = null) => {
|
|
132
|
+
if (settled)
|
|
133
|
+
return;
|
|
134
|
+
settled = true;
|
|
135
|
+
clearTimeout(timer);
|
|
136
|
+
this.#record(rule, event, status, startedAt, new Date().toISOString(), Date.now() - startedMs, exitCode, signal, timedOut);
|
|
137
|
+
resolve();
|
|
138
|
+
};
|
|
139
|
+
child.once("error", () => finish("SPAWN_FAILED", null));
|
|
140
|
+
child.once("close", (code, signal) => finish(timedOut ? "TIMEOUT" : code === 0 ? "SUCCEEDED" : "FAILED", code, signal));
|
|
141
|
+
try {
|
|
142
|
+
child.stdin?.on("error", () => { });
|
|
143
|
+
child.stdin?.end(JSON.stringify(event));
|
|
144
|
+
}
|
|
145
|
+
catch {
|
|
146
|
+
try {
|
|
147
|
+
child.kill("SIGKILL");
|
|
148
|
+
}
|
|
149
|
+
catch { /* process close owns the outcome */ }
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
#record(rule, event, status, startedAt, finishedAt, durationMs, exitCode, signal, timeout) {
|
|
154
|
+
try {
|
|
155
|
+
const record = {
|
|
156
|
+
hookId: rule.id,
|
|
157
|
+
eventKey: event.eventKey,
|
|
158
|
+
messageId: event.messageId,
|
|
159
|
+
status,
|
|
160
|
+
startedAt,
|
|
161
|
+
finishedAt,
|
|
162
|
+
...(durationMs === undefined ? {} : { durationMs }),
|
|
163
|
+
...(exitCode === undefined ? {} : { exitCode }),
|
|
164
|
+
...(signal === undefined ? {} : { signal }),
|
|
165
|
+
...(timeout === undefined ? {} : { timeout }),
|
|
166
|
+
};
|
|
167
|
+
const directory = join(this.#directory, "ce-hooks");
|
|
168
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
169
|
+
if (!lstatSync(directory).isDirectory() || lstatSync(directory).isSymbolicLink())
|
|
170
|
+
return;
|
|
171
|
+
const fd = openSync(join(directory, "executions.jsonl"), constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | constants.O_NOFOLLOW, 0o600);
|
|
172
|
+
try {
|
|
173
|
+
const stat = fstatSync(fd);
|
|
174
|
+
if (!stat.isFile() || (process.getuid !== undefined && stat.uid !== process.getuid()))
|
|
175
|
+
return;
|
|
176
|
+
appendFileSync(fd, `${JSON.stringify(record)}\n`);
|
|
177
|
+
}
|
|
178
|
+
finally {
|
|
179
|
+
closeSync(fd);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
catch {
|
|
183
|
+
// Execution records are local evidence only, never CE message state.
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
//# sourceMappingURL=runner.js.map
|
|
@@ -19,6 +19,7 @@
|
|
|
19
19
|
* heartbeat, then `host.end` (release, then detach) exactly once. An unknown
|
|
20
20
|
* outcome is reported, never retried.
|
|
21
21
|
*/
|
|
22
|
+
import { createHash } from "node:crypto";
|
|
22
23
|
import { CeHostRefusal, } from "./endpoint-host.js";
|
|
23
24
|
const defaultTimers = {
|
|
24
25
|
setInterval: (callback, ms) => {
|
|
@@ -53,8 +54,7 @@ export class CeBoundEndpoint {
|
|
|
53
54
|
if (!Number.isSafeInteger(options.renewIntervalMs) || options.renewIntervalMs < 1) {
|
|
54
55
|
throw new CeHostRefusal("CE_HOST_INVALID_REQUEST");
|
|
55
56
|
}
|
|
56
|
-
options.admission?.({ kind: "begin" });
|
|
57
|
-
host.beginSession(endpointId, { requireUnowned: true });
|
|
57
|
+
host.runWithRecipientSnapshot(snapshot => options.admission?.({ kind: "begin" }, snapshot), () => host.beginSession(endpointId, { requireUnowned: true }));
|
|
58
58
|
const bound = new CeBoundEndpoint(host, endpointId, options);
|
|
59
59
|
bound.#heartbeat = bound.#timers.setInterval(() => bound.#renew(), options.renewIntervalMs);
|
|
60
60
|
return bound;
|
|
@@ -62,6 +62,21 @@ export class CeBoundEndpoint {
|
|
|
62
62
|
get state() {
|
|
63
63
|
return this.#state;
|
|
64
64
|
}
|
|
65
|
+
operationalStatus() {
|
|
66
|
+
return Object.freeze({ state: this.#state, renewal: this.#heartbeat === undefined ? "STOPPED" : "RUNNING" });
|
|
67
|
+
}
|
|
68
|
+
discover() {
|
|
69
|
+
return this.#run(false, { kind: "discover" }, () => {
|
|
70
|
+
const discovery = this.#host.discover(this.#endpointId);
|
|
71
|
+
if (this.#state !== "WRITE_BLOCKED")
|
|
72
|
+
return discovery;
|
|
73
|
+
const targets = Object.freeze(discovery.targets.map(target => target.reason === "PRESENCE_WITHHELD"
|
|
74
|
+
? target
|
|
75
|
+
: Object.freeze({ ...target, reachable: "FALSE", reason: "PORT_BLOCKED" })));
|
|
76
|
+
const projection = { self: { ...discovery.self, effective: { ...discovery.self.effective, send: false, ack: false } }, targets };
|
|
77
|
+
return Object.freeze({ ...discovery, ...projection, viewDigest: createHash("sha256").update(JSON.stringify(projection)).digest("hex") });
|
|
78
|
+
});
|
|
79
|
+
}
|
|
65
80
|
#emit(event) {
|
|
66
81
|
try {
|
|
67
82
|
this.#onEvent?.(event);
|
|
@@ -80,8 +95,7 @@ export class CeBoundEndpoint {
|
|
|
80
95
|
if (this.#state !== "ACTIVE")
|
|
81
96
|
return;
|
|
82
97
|
try {
|
|
83
|
-
this.#admission?.({ kind: "renew" });
|
|
84
|
-
this.#host.renew(this.#endpointId);
|
|
98
|
+
this.#host.runWithRecipientSnapshot(snapshot => this.#admission?.({ kind: "renew" }, snapshot), () => this.#host.renew(this.#endpointId));
|
|
85
99
|
this.#emit({ kind: "renewed" });
|
|
86
100
|
}
|
|
87
101
|
catch (error) {
|
|
@@ -108,10 +122,9 @@ export class CeBoundEndpoint {
|
|
|
108
122
|
}
|
|
109
123
|
#run(write, request, operation) {
|
|
110
124
|
this.#admit(write);
|
|
111
|
-
this.#admission?.(request);
|
|
112
125
|
this.#inFlight += 1;
|
|
113
126
|
try {
|
|
114
|
-
return
|
|
127
|
+
return this.#host.runWithRecipientSnapshot(snapshot => this.#admission?.(request, snapshot), operation);
|
|
115
128
|
}
|
|
116
129
|
finally {
|
|
117
130
|
this.#inFlight -= 1;
|
|
@@ -33,8 +33,10 @@
|
|
|
33
33
|
* for CE-TAKEOVER-RECOVERY-CALLER-001 is not reachable through this adapter.
|
|
34
34
|
* Restart never implies ownership recovery.
|
|
35
35
|
*/
|
|
36
|
+
import { createHash } from "node:crypto";
|
|
36
37
|
import { EXCHANGE_ID_PATTERN, MESSAGE_ID_PATTERN } from "../protocol/identity.js";
|
|
37
38
|
import { SHA256_HEX_PATTERN } from "../protocol/entities.js";
|
|
39
|
+
import { createCommittedMessageEvent } from "../hooks/events.js";
|
|
38
40
|
import { recordDeliveryAck } from "../storage/delivery-ack.js";
|
|
39
41
|
import { CreationDomainError } from "../storage/creation.js";
|
|
40
42
|
import { createExchange } from "../storage/creation.js";
|
|
@@ -44,7 +46,7 @@ import { readMessageMetadata, readMessagePayload, sendMessage, } from "../storag
|
|
|
44
46
|
import { discoverInboxMessages } from "../storage/inbox-discovery.js";
|
|
45
47
|
import { captureFields, isParticipantId, isSessionId, ParticipantRequestError, } from "../storage/participant-identity.js";
|
|
46
48
|
import { createParticipant, ParticipantDomainError, issueCapability, joinExchange, readParticipantByEndpoint, } from "../storage/participant.js";
|
|
47
|
-
import { acquireOwnership, bindSession, detachSession, generateSessionId, LEASE_DEFAULT_TTL_SECONDS, LEASE_MAX_TTL_SECONDS, LEASE_MIN_TTL_SECONDS, readCurrentOwnership, readLeaseStatus, readSessionLifecycle, releaseOwnership, renewLease, } from "../storage/ownership.js";
|
|
49
|
+
import { acquireOwnership, bindSession, detachSession, generateSessionId, LEASE_DEFAULT_TTL_SECONDS, LEASE_MAX_TTL_SECONDS, LEASE_MIN_TTL_SECONDS, readCurrentOwnership, readEndpointObservations, readLeaseStatus, readSessionLifecycle, releaseOwnership, renewLease, } from "../storage/ownership.js";
|
|
48
50
|
import { StorageTransactionError } from "../storage/transaction.js";
|
|
49
51
|
const REFUSAL_DETAIL = {
|
|
50
52
|
CE_HOST_ENDPOINT_NOT_ALLOWED: "endpoint is not in the host allowlist",
|
|
@@ -232,8 +234,12 @@ export class CeEndpointHost {
|
|
|
232
234
|
#ackEnabled;
|
|
233
235
|
/** Explicit cross-adapter recipients, validated and frozen at construction. */
|
|
234
236
|
#recipients;
|
|
237
|
+
#liveRecipients;
|
|
235
238
|
#seams;
|
|
239
|
+
#onMessageCommitted;
|
|
236
240
|
#authorities = new Map();
|
|
241
|
+
#prepared;
|
|
242
|
+
#preparing = false;
|
|
237
243
|
constructor(store, policy) {
|
|
238
244
|
if (!isEndpointLabel(policy.adapter, ADAPTER_MAX_LENGTH))
|
|
239
245
|
throw new CeHostRefusal("CE_HOST_INVALID_REQUEST");
|
|
@@ -249,12 +255,20 @@ export class CeEndpointHost {
|
|
|
249
255
|
seen.add(entry.endpointId);
|
|
250
256
|
}
|
|
251
257
|
this.#recipients = validatedRecipients(policy, seen);
|
|
258
|
+
if (policy.liveRecipients !== undefined && typeof policy.liveRecipients.snapshot !== "function") {
|
|
259
|
+
throw new CeHostRefusal("CE_HOST_INVALID_REQUEST");
|
|
260
|
+
}
|
|
261
|
+
this.#liveRecipients = policy.liveRecipients;
|
|
252
262
|
this.#store = store;
|
|
253
263
|
this.#policy = policy;
|
|
254
264
|
this.#leaseTtlSeconds = clampLeaseTtl(policy);
|
|
255
265
|
this.#payloadReadEnabled = payloadReadEnabled(policy);
|
|
256
266
|
this.#ackEnabled = ackEnabled(policy);
|
|
257
267
|
this.#seams = policy.now === undefined ? {} : { now: policy.now };
|
|
268
|
+
if (policy.onMessageCommitted !== undefined && typeof policy.onMessageCommitted !== "function") {
|
|
269
|
+
throw new CeHostRefusal("CE_HOST_INVALID_REQUEST");
|
|
270
|
+
}
|
|
271
|
+
this.#onMessageCommitted = policy.onMessageCommitted;
|
|
258
272
|
}
|
|
259
273
|
/** The durable Exchange this host operates. Creation is idempotent by the
|
|
260
274
|
* deterministic policy identity, so every call converges on one Exchange. */
|
|
@@ -270,11 +284,46 @@ export class CeEndpointHost {
|
|
|
270
284
|
/** Resolve a recipient label: an allowlisted same-adapter Endpoint first,
|
|
271
285
|
* otherwise an explicitly configured cross-adapter recipient. Any other
|
|
272
286
|
* label is refused exactly like before (`CE_HOST_ENDPOINT_NOT_ALLOWED`). */
|
|
273
|
-
|
|
287
|
+
/** One synchronous policy selection shared by outer admission and the Host
|
|
288
|
+
* operation. No async or reentrant operation may retain this authority. */
|
|
289
|
+
runWithRecipientSnapshot(admit, operation) {
|
|
290
|
+
if (this.#preparing)
|
|
291
|
+
throw new CeHostRefusal("CE_HOST_UNAVAILABLE", false, "RECIPIENT_SNAPSHOT_REENTRANT");
|
|
292
|
+
this.#preparing = true;
|
|
293
|
+
try {
|
|
294
|
+
this.#prepared = this.#readSnapshot();
|
|
295
|
+
admit(this.#prepared);
|
|
296
|
+
return operation();
|
|
297
|
+
}
|
|
298
|
+
finally {
|
|
299
|
+
this.#prepared = undefined;
|
|
300
|
+
this.#preparing = false;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
#snapshot() {
|
|
304
|
+
if (this.#preparing)
|
|
305
|
+
return this.#prepared;
|
|
306
|
+
return this.#readSnapshot();
|
|
307
|
+
}
|
|
308
|
+
#readSnapshot() {
|
|
309
|
+
if (this.#liveRecipients === undefined)
|
|
310
|
+
return undefined;
|
|
311
|
+
try {
|
|
312
|
+
const snapshot = this.#liveRecipients.snapshot();
|
|
313
|
+
const recipients = validatedRecipients({ ...this.#policy, recipients: snapshot.recipients }, new Set(this.#policy.allowlist.map(entry => entry.endpointId)));
|
|
314
|
+
if (recipients.length > 128)
|
|
315
|
+
throw new CeHostRefusal("CE_HOST_UNAVAILABLE");
|
|
316
|
+
return { ...snapshot, recipients };
|
|
317
|
+
}
|
|
318
|
+
catch (error) {
|
|
319
|
+
throw toRefusal(error);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
#recipient(label, snapshot) {
|
|
274
323
|
if (this.#policy.allowlist.some((candidate) => candidate.endpointId === label)) {
|
|
275
324
|
return { adapter: this.#policy.adapter, endpointId: label };
|
|
276
325
|
}
|
|
277
|
-
const external = this.#recipients.find((candidate) => candidate.endpointId === label);
|
|
326
|
+
const external = (snapshot?.recipients ?? this.#recipients).find((candidate) => candidate.endpointId === label);
|
|
278
327
|
if (external === undefined)
|
|
279
328
|
throw new CeHostRefusal("CE_HOST_ENDPOINT_NOT_ALLOWED");
|
|
280
329
|
return external;
|
|
@@ -550,7 +599,8 @@ export class CeEndpointHost {
|
|
|
550
599
|
if (typeof to !== "string" || to.length === 0 || to.length > 256) {
|
|
551
600
|
throw new CeHostRefusal("CE_HOST_INVALID_REQUEST");
|
|
552
601
|
}
|
|
553
|
-
const
|
|
602
|
+
const snapshot = this.#snapshot();
|
|
603
|
+
const recipient = this.#recipient(to, snapshot);
|
|
554
604
|
if (typeof text !== "string" || text.length === 0)
|
|
555
605
|
throw new CeHostRefusal("CE_HOST_INVALID_REQUEST");
|
|
556
606
|
if (typeof idempotencyKey !== "string" || idempotencyKey.length === 0 || idempotencyKey.length > 256) {
|
|
@@ -562,6 +612,12 @@ export class CeEndpointHost {
|
|
|
562
612
|
let creation;
|
|
563
613
|
try {
|
|
564
614
|
const fencingToken = this.#currentFencing(authority);
|
|
615
|
+
if (snapshot !== undefined) {
|
|
616
|
+
// Check the caller before exposing a target's membership state.
|
|
617
|
+
const observation = readEndpointObservations(this.#store, authority.exchangeId, [recipient], this.#seams);
|
|
618
|
+
if (!observation.targets[0]?.joined)
|
|
619
|
+
throw new CeHostRefusal("CE_HOST_UNAVAILABLE", false, "PARTICIPANT_NOT_MEMBER");
|
|
620
|
+
}
|
|
565
621
|
creation = sendMessage(this.#store, {
|
|
566
622
|
participantId: authority.participantId,
|
|
567
623
|
sessionId: authority.sessionId,
|
|
@@ -579,6 +635,14 @@ export class CeEndpointHost {
|
|
|
579
635
|
catch (error) {
|
|
580
636
|
throw toRefusal(error);
|
|
581
637
|
}
|
|
638
|
+
if (creation.disposition === "CREATED" && this.#onMessageCommitted !== undefined) {
|
|
639
|
+
try {
|
|
640
|
+
this.#onMessageCommitted(createCommittedMessageEvent(creation));
|
|
641
|
+
}
|
|
642
|
+
catch {
|
|
643
|
+
// The Message is already committed. Local Hook failures are not CE evidence.
|
|
644
|
+
}
|
|
645
|
+
}
|
|
582
646
|
return Object.freeze({
|
|
583
647
|
disposition: creation.disposition,
|
|
584
648
|
messageId: creation.message.messageId,
|
|
@@ -790,6 +854,30 @@ export class CeEndpointHost {
|
|
|
790
854
|
throw toRefusal(error);
|
|
791
855
|
}
|
|
792
856
|
}
|
|
857
|
+
/** Caller-bound advisory projection. Filter before any durable observation. */
|
|
858
|
+
discover(endpointId) {
|
|
859
|
+
this.#allowlisted(endpointId);
|
|
860
|
+
const authority = this.#authority(endpointId);
|
|
861
|
+
this.#currentFencing(authority);
|
|
862
|
+
const snapshot = this.#snapshot();
|
|
863
|
+
if (snapshot === undefined)
|
|
864
|
+
throw new CeHostRefusal("CE_HOST_UNAVAILABLE");
|
|
865
|
+
const visible = snapshot.recipients.filter(recipient => recipient.endpointId !== endpointId);
|
|
866
|
+
const disclosed = visible.filter(recipient => snapshot.presence.some(entry => entry.endpointId === recipient.endpointId && entry.disclose));
|
|
867
|
+
let observation;
|
|
868
|
+
try {
|
|
869
|
+
observation = readEndpointObservations(this.#store, authority.exchangeId, disclosed, this.#seams);
|
|
870
|
+
}
|
|
871
|
+
catch { /* Advisory uncertainty grants nothing. */ }
|
|
872
|
+
const targets = visible.map(recipient => {
|
|
873
|
+
const disclose = disclosed.some(entry => entry.endpointId === recipient.endpointId);
|
|
874
|
+
const observed = observation?.targets.find(entry => entry.adapter === recipient.adapter && entry.endpointId === recipient.endpointId);
|
|
875
|
+
return Object.freeze({ ...recipient, registered: true, authorized: Object.freeze({ send: true }), active: observed?.active ?? "UNKNOWN", reachable: observed === undefined ? "UNKNOWN" : observed.joined ? "TRUE" : "FALSE", reason: !disclose ? "PRESENCE_WITHHELD" : observed === undefined ? "OBSERVATION_UNKNOWN" : "OBSERVED" });
|
|
876
|
+
});
|
|
877
|
+
const self = Object.freeze({ adapter: this.#policy.adapter, endpointId, effective: Object.freeze({ send: true, readPayload: this.#payloadReadEnabled && (snapshot.ownPolicy?.payloadRead ?? true), ack: this.#ackEnabled && (snapshot.ownPolicy?.ack ?? true) }) });
|
|
878
|
+
const projection = { self, targets: Object.freeze(targets) };
|
|
879
|
+
return Object.freeze({ ...projection, observedAt: observation?.observedAt ?? "UNKNOWN", viewDigest: createHash("sha256").update(JSON.stringify(projection)).digest("hex") });
|
|
880
|
+
}
|
|
793
881
|
/** Advisory status for the operator command. Authorizes nothing. */
|
|
794
882
|
status(endpointId) {
|
|
795
883
|
const authority = this.#authorities.get(endpointId);
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
import { isAbsolute, normalize } from "node:path";
|
|
12
12
|
import { TUNNEL_ID_PATTERN as MANAGED_TUNNEL_ID } from "../tunnel/tunnel-id.js";
|
|
13
13
|
import { LEASE_MAX_TTL_SECONDS, LEASE_MIN_TTL_SECONDS } from "../storage/ownership.js";
|
|
14
|
+
import { CeHookConfigError, parseHookRules } from "../hooks/config.js";
|
|
14
15
|
export const MCP_BINDING_CONFIG_VERSION = 1;
|
|
15
16
|
export const MCP_DEFAULT_LEASE_TTL_SECONDS = 120;
|
|
16
17
|
export const MCP_DEFAULT_RENEW_INTERVAL_SECONDS = 30;
|
|
@@ -162,7 +163,7 @@ function managedMetadata(value) {
|
|
|
162
163
|
* paths, out-of-range lease settings, duplicate or self-referencing
|
|
163
164
|
* recipients, and credential-shaped strings are all refused. */
|
|
164
165
|
export function parseMcpBindingConfig(raw) {
|
|
165
|
-
const fields = plain(raw, "config", ["version", "store", "exchange", "endpoint", "recipients", "lease", "payloadRead", "ack", "debugExecutionGuard", "managed", "admissionPolicy"], ["version", "store", "exchange", "endpoint", "recipients"]);
|
|
166
|
+
const fields = plain(raw, "config", ["version", "store", "exchange", "endpoint", "recipients", "lease", "payloadRead", "ack", "debugExecutionGuard", "managed", "admissionPolicy", "hooks"], ["version", "store", "exchange", "endpoint", "recipients"]);
|
|
166
167
|
if (fields.version !== MCP_BINDING_CONFIG_VERSION)
|
|
167
168
|
throw new McpBindingConfigError("config.version");
|
|
168
169
|
const store = storeLocation(fields.store);
|
|
@@ -174,11 +175,34 @@ export function parseMcpBindingConfig(raw) {
|
|
|
174
175
|
const managed = fields.managed === undefined ? undefined : managedMetadata(fields.managed);
|
|
175
176
|
let admissionPolicy;
|
|
176
177
|
if (fields.admissionPolicy !== undefined) {
|
|
177
|
-
const
|
|
178
|
-
|
|
179
|
-
|
|
178
|
+
const kind = plain(fields.admissionPolicy, "admissionPolicy", ["kind", "profilePath", "root", "policyId", "genesisDigest", "upgradeSequence"], ["kind"]).kind;
|
|
179
|
+
if (kind === "ce-multi-session-v1") {
|
|
180
|
+
const ref = plain(fields.admissionPolicy, "admissionPolicy", ["kind", "profilePath"], ["kind", "profilePath"]);
|
|
181
|
+
const path = label(ref.profilePath, "admissionPolicy.profilePath", 4096);
|
|
182
|
+
if (!isAbsolute(path) || normalize(path) !== path || /[\u0000-\u001f\u007f]/.test(path))
|
|
183
|
+
throw new McpBindingConfigError("admissionPolicy");
|
|
184
|
+
admissionPolicy = Object.freeze({ kind, profilePath: path });
|
|
185
|
+
}
|
|
186
|
+
else if (kind === "ce-live-session-v1" || kind === "ce-live-session-v2") {
|
|
187
|
+
const keys = ["kind", "root", "policyId", "genesisDigest", ...(kind === "ce-live-session-v2" ? ["profilePath", "upgradeSequence"] : [])];
|
|
188
|
+
const ref = plain(fields.admissionPolicy, "admissionPolicy", keys, keys);
|
|
189
|
+
const root = label(ref.root, "admissionPolicy.root", 4096);
|
|
190
|
+
const policyId = label(ref.policyId, "admissionPolicy.policyId", 128);
|
|
191
|
+
if (!isAbsolute(root) || normalize(root) !== root || root === "/" || /[\u0000-\u001f\u007f]/.test(root) ||
|
|
192
|
+
typeof ref.genesisDigest !== "string" || !/^[a-f0-9]{64}$/.test(ref.genesisDigest) || !/^[A-Za-z0-9_-]{1,128}$/.test(policyId))
|
|
193
|
+
throw new McpBindingConfigError("admissionPolicy");
|
|
194
|
+
if (kind === "ce-live-session-v2") {
|
|
195
|
+
const profilePath = label(ref.profilePath, "admissionPolicy.profilePath", 4096);
|
|
196
|
+
if (!isAbsolute(profilePath) || normalize(profilePath) !== profilePath || /[\u0000-\u001f\u007f]/.test(profilePath) ||
|
|
197
|
+
typeof ref.upgradeSequence !== "number" || !Number.isSafeInteger(ref.upgradeSequence) || ref.upgradeSequence < 1 || ref.upgradeSequence > 65536)
|
|
198
|
+
throw new McpBindingConfigError("admissionPolicy");
|
|
199
|
+
admissionPolicy = Object.freeze({ kind, root, policyId, genesisDigest: ref.genesisDigest, profilePath, upgradeSequence: ref.upgradeSequence });
|
|
200
|
+
}
|
|
201
|
+
else
|
|
202
|
+
admissionPolicy = Object.freeze({ kind, root, policyId, genesisDigest: ref.genesisDigest });
|
|
203
|
+
}
|
|
204
|
+
else
|
|
180
205
|
throw new McpBindingConfigError("admissionPolicy");
|
|
181
|
-
admissionPolicy = Object.freeze({ kind: "ce-multi-session-v1", profilePath: path });
|
|
182
206
|
}
|
|
183
207
|
const endpoint = endpointRef(fields.endpoint, "endpoint");
|
|
184
208
|
if (!Array.isArray(fields.recipients))
|
|
@@ -193,6 +217,17 @@ export function parseMcpBindingConfig(raw) {
|
|
|
193
217
|
seen.add(ref.endpointId);
|
|
194
218
|
recipients.push(ref);
|
|
195
219
|
});
|
|
220
|
+
let hooks;
|
|
221
|
+
if (fields.hooks !== undefined) {
|
|
222
|
+
try {
|
|
223
|
+
hooks = parseHookRules(fields.hooks);
|
|
224
|
+
}
|
|
225
|
+
catch (error) {
|
|
226
|
+
if (error instanceof CeHookConfigError)
|
|
227
|
+
throw new McpBindingConfigError(error.field);
|
|
228
|
+
throw new McpBindingConfigError("hooks");
|
|
229
|
+
}
|
|
230
|
+
}
|
|
196
231
|
return Object.freeze({
|
|
197
232
|
store,
|
|
198
233
|
exchange,
|
|
@@ -204,6 +239,7 @@ export function parseMcpBindingConfig(raw) {
|
|
|
204
239
|
debugExecutionGuard: debugExecutionGuardPolicy(fields.debugExecutionGuard),
|
|
205
240
|
...(managed === undefined ? {} : { managed }),
|
|
206
241
|
...(admissionPolicy === undefined ? {} : { admissionPolicy }),
|
|
242
|
+
...(hooks === undefined ? {} : { hooks }),
|
|
207
243
|
});
|
|
208
244
|
}
|
|
209
245
|
//# sourceMappingURL=mcp-binding-config.js.map
|
|
@@ -92,11 +92,14 @@ export function assertNativeReadyForTunnel() {
|
|
|
92
92
|
return readiness;
|
|
93
93
|
}
|
|
94
94
|
export async function runNativeCommand(args, options = {}) {
|
|
95
|
+
return (await runNativeCommandOutcome(args, options)).message;
|
|
96
|
+
}
|
|
97
|
+
export async function runNativeCommandOutcome(args, options = {}) {
|
|
95
98
|
const command = args.trim();
|
|
96
99
|
if (command === "" || command === "status" || command === "verify")
|
|
97
|
-
return JSON.stringify(inspectNativeReadiness(options), null, 2);
|
|
100
|
+
return { kind: "ok", message: JSON.stringify(inspectNativeReadiness(options), null, 2) };
|
|
98
101
|
if (command !== "install" && command !== "repair confirm" && command !== "check-updates") {
|
|
99
|
-
return "Usage: /ce-native [status|install|verify|repair confirm|check-updates]. Repair requires explicit repair confirm.";
|
|
102
|
+
return { kind: "usage", message: "Usage: /ce-native [status|install|verify|repair confirm|check-updates]. Repair requires explicit repair confirm." };
|
|
100
103
|
}
|
|
101
104
|
const manifest = options.manifest ?? NATIVE_COMPAT;
|
|
102
105
|
try {
|
|
@@ -112,7 +115,7 @@ export async function runNativeCommand(args, options = {}) {
|
|
|
112
115
|
throw Object.assign(new Error(), { code: "CE_NATIVE_DISCOVERY_FAILED" });
|
|
113
116
|
}
|
|
114
117
|
const differs = metadata.tag_name !== `ce-sqlite-v${manifest.defaultVersion}`;
|
|
115
|
-
return `Current trusted Native version: ${manifest.defaultVersion}. Release discovery ${differs ? "differs; wait for a CE compatibility update" : "matches the trusted version"}. No driver was installed or selected
|
|
118
|
+
return { kind: "ok", message: `Current trusted Native version: ${manifest.defaultVersion}. Release discovery ${differs ? "differs; wait for a CE compatibility update" : "matches the trusted version"}. No driver was installed or selected.` };
|
|
116
119
|
}
|
|
117
120
|
if (!supported(options) || (options.platform !== undefined && options.platform !== process.platform)
|
|
118
121
|
|| (options.arch !== undefined && options.arch !== process.arch))
|
|
@@ -122,10 +125,10 @@ export async function runNativeCommand(args, options = {}) {
|
|
|
122
125
|
...(options.fetchImpl === undefined ? {} : { fetchImpl: options.fetchImpl }) });
|
|
123
126
|
// Selection changes only after the fixed default artifact has been verified.
|
|
124
127
|
writeDriverSelection({ driver: "rust-native", nativeVersion: manifest.defaultVersion }, options.selectionFile);
|
|
125
|
-
return `Trusted Native ${manifest.defaultVersion} installed and selected. Restart Pi to initialize messaging with the installed driver
|
|
128
|
+
return { kind: "ok", message: `Trusted Native ${manifest.defaultVersion} installed and selected. Restart Pi to initialize messaging with the installed driver.` };
|
|
126
129
|
}
|
|
127
130
|
catch (error) {
|
|
128
|
-
return `Native command failed (${errorCode(error)}). Current selection was not changed
|
|
131
|
+
return { kind: "failed", message: `Native command failed (${errorCode(error)}). Current selection was not changed.` };
|
|
129
132
|
}
|
|
130
133
|
}
|
|
131
134
|
//# sourceMappingURL=native-readiness.js.map
|
package/dist/storage/creation.js
CHANGED
|
@@ -69,6 +69,22 @@ function replay(tx, request) {
|
|
|
69
69
|
record: Object.freeze({ entityId: row.entity_id, requestDigest: row.request_digest, createdAt: row.created_at }),
|
|
70
70
|
});
|
|
71
71
|
}
|
|
72
|
+
/** Private advisory lookup for identity preflight. Reuse creation replay checks
|
|
73
|
+
* without entering the create path; this read never establishes authority. */
|
|
74
|
+
export function readExistingExchange(store, input) {
|
|
75
|
+
const request = normalizeCreateExchangeRequest(input);
|
|
76
|
+
const db = store.database;
|
|
77
|
+
if (db.isTransaction)
|
|
78
|
+
throw new Error("Exchange reads cannot run inside an active transaction");
|
|
79
|
+
db.exec("BEGIN");
|
|
80
|
+
try {
|
|
81
|
+
return replay(db, request);
|
|
82
|
+
}
|
|
83
|
+
finally {
|
|
84
|
+
if (db.isTransaction)
|
|
85
|
+
db.exec("ROLLBACK");
|
|
86
|
+
}
|
|
87
|
+
}
|
|
72
88
|
function hook(action) {
|
|
73
89
|
if (action === undefined)
|
|
74
90
|
return;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { randomBytes } from "node:crypto";
|
|
2
2
|
import { encodeUlid } from "../protocol/identity.js";
|
|
3
3
|
import { captureFields, rejectRequest, requireInstant, requireParticipantId, requireSessionId, SESSION_ID_PATTERN, SESSION_ID_PREFIX, } from "./participant-identity.js";
|
|
4
|
-
import { authorize, clock, hook, readParticipantRow, refuse, runOwned, } from "./participant.js";
|
|
4
|
+
import { authorize, clock, hook, readParticipantRow, readParticipantByEndpoint, readMembershipRow, refuse, runOwned, } from "./participant.js";
|
|
5
5
|
import { parseSessionRow, SESSION_COLUMNS } from "./session-state.js";
|
|
6
6
|
import { requireSingleRowChange } from "./transaction.js";
|
|
7
7
|
/**
|
|
@@ -626,6 +626,8 @@ function readSnapshot(store, body) {
|
|
|
626
626
|
throw new Error("ownership reads cannot run inside an active transaction");
|
|
627
627
|
db.exec("BEGIN");
|
|
628
628
|
try {
|
|
629
|
+
// SAFETY: the SQLite connection supplies prepare/get/all; row consumers
|
|
630
|
+
// validate unparsed SQL values before constructing domain records.
|
|
629
631
|
return body(db);
|
|
630
632
|
}
|
|
631
633
|
finally {
|
|
@@ -633,6 +635,23 @@ function readSnapshot(store, body) {
|
|
|
633
635
|
db.exec("ROLLBACK");
|
|
634
636
|
}
|
|
635
637
|
}
|
|
638
|
+
/** Private advisory aggregate. Callers filter authorized labels before entry.
|
|
639
|
+
* All parsers share one deferred snapshot and one clock; no authority is issued. */
|
|
640
|
+
export function readEndpointObservations(store, exchangeId, endpoints, seams = {}) {
|
|
641
|
+
return readSnapshot(store, (handle) => {
|
|
642
|
+
const observedAt = clock(seams);
|
|
643
|
+
const targets = endpoints.map((endpoint) => {
|
|
644
|
+
// This lookup uses the existing validated parser on the same connection.
|
|
645
|
+
const participant = readParticipantByEndpoint(store, endpoint.adapter, endpoint.endpointId);
|
|
646
|
+
const membership = participant === undefined ? undefined : readMembershipRow(handle, exchangeId, participant.participantId);
|
|
647
|
+
const ownership = participant === undefined ? undefined : loadOwnershipState(handle, participant.participantId).ownership;
|
|
648
|
+
const lease = ownership === undefined ? undefined : evaluateLease(ownership, observedAt);
|
|
649
|
+
const active = lease === "CLOCK_REGRESSION" ? "UNKNOWN" : lease === "ACTIVE" ? "TRUE" : "FALSE";
|
|
650
|
+
return Object.freeze({ ...endpoint, joined: membership !== undefined, active });
|
|
651
|
+
});
|
|
652
|
+
return Object.freeze({ observedAt, targets: Object.freeze(targets) });
|
|
653
|
+
});
|
|
654
|
+
}
|
|
636
655
|
/** One Participant–Session binding, or undefined. Detached rows are not
|
|
637
656
|
* current bindings and are reported as undefined. */
|
|
638
657
|
export function readSessionBinding(store, participantId, sessionId) {
|
|
@@ -665,6 +684,31 @@ export function readCurrentOwnership(store, participantId) {
|
|
|
665
684
|
const pid = requireParticipantId(participantId, "participantId");
|
|
666
685
|
return readSnapshot(store, (handle) => loadOwnershipState(handle, pid).ownership);
|
|
667
686
|
}
|
|
687
|
+
/** Private coherent Owner/lease observation; advisory only, never authorization. */
|
|
688
|
+
export function readOwnershipObservation(store, participantId, seams = {}) {
|
|
689
|
+
const pid = requireParticipantId(participantId, "participantId");
|
|
690
|
+
return readSnapshot(store, handle => {
|
|
691
|
+
const now = clock(seams);
|
|
692
|
+
const { ownership } = loadOwnershipState(handle, pid);
|
|
693
|
+
return Object.freeze({ ownership, lease: ownership === undefined ? "UNOWNED" : evaluateLease(ownership, now) });
|
|
694
|
+
});
|
|
695
|
+
}
|
|
696
|
+
/** Private fixed-endpoint view for a live transport observation. The Exchange
|
|
697
|
+
* comes from the caller's existing mapping; this read creates no membership. */
|
|
698
|
+
export function readEndpointOwnerObservation(store, endpoint, exchangeId, seams = {}) {
|
|
699
|
+
return readSnapshot(store, handle => {
|
|
700
|
+
const now = clock(seams);
|
|
701
|
+
const participant = readParticipantByEndpoint(store, endpoint.adapter, endpoint.endpointId);
|
|
702
|
+
if (participant === undefined || readMembershipRow(handle, exchangeId, participant.participantId) === undefined)
|
|
703
|
+
return undefined;
|
|
704
|
+
const { ownership } = loadOwnershipState(handle, participant.participantId);
|
|
705
|
+
if (ownership === undefined)
|
|
706
|
+
return undefined;
|
|
707
|
+
return Object.freeze({ endpointId: endpoint.endpointId, registered: true, participantId: participant.participantId,
|
|
708
|
+
sessionId: ownership.sessionId, exchangeId, fencingToken: ownership.fencingToken,
|
|
709
|
+
lease: evaluateLease(ownership, now), leaseExpiresAt: ownership.expiresAt });
|
|
710
|
+
});
|
|
711
|
+
}
|
|
668
712
|
/** Highest fencing token ever allocated for the Participant; 0 when none. */
|
|
669
713
|
export function readFencingHighWater(store, participantId) {
|
|
670
714
|
const pid = requireParticipantId(participantId, "participantId");
|