@zieglar/pi-chat-exchange 0.3.2 → 0.3.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/ce-runtime-binding.js +33 -0
- package/dist/bin/mcp-stdio.js +32 -23
- package/dist/bin/task-owner-composition.js +47 -0
- package/dist/control/mcp/endpoint-discovery.js +45 -5
- package/dist/control/mcp/server.js +23 -4
- package/dist/control/mcp/source-metadata-probe.js +46 -0
- package/dist/control/mcp/task-owner-registry.js +141 -0
- package/dist/control/mcp/task-owner.js +49 -0
- package/dist/runtime/runtime-group.js +10 -0
- package/dist/runtime/source-metadata-probe-opt-in.js +6 -0
- package/dist/tunnel/current-runtime-binding.js +120 -0
- package/dist/tunnel/endpoint-runtime-binding.js +218 -0
- package/dist/tunnel/live-mcp-composition.js +41 -3
- package/dist/tunnel/session-switch-observation.js +218 -0
- package/package.json +1 -1
- package/pi-extension/index.ts +78 -3
- package/pi-extension/runtime-binding-command.ts +104 -0
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/** Bounded Pi lifecycle observations only. These records confer no CE permissions,
|
|
2
|
+
* process ownership, delivery receipt, or Task Owner authority. */
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { randomUUID } from "node:crypto";
|
|
6
|
+
import { Type } from "@sinclair/typebox";
|
|
7
|
+
import { Value } from "@sinclair/typebox/value";
|
|
8
|
+
import { readPrivateMessagingFile } from "./messaging-config.js";
|
|
9
|
+
export const CURRENT_RUNTIME_TTL_MS = 5_000;
|
|
10
|
+
export const RUNTIME_ID_PATTERN = "^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$";
|
|
11
|
+
const runtimeIdSchema = Type.String({ pattern: RUNTIME_ID_PATTERN });
|
|
12
|
+
const RecordSchema = Type.Object({ version: Type.Literal(1), runtimeId: runtimeIdSchema,
|
|
13
|
+
observerId: Type.String({ pattern: "^[a-f0-9-]{36}$" }), policyId: Type.String({ minLength: 1, maxLength: 256 }),
|
|
14
|
+
genesisDigest: Type.String({ pattern: "^[a-f0-9]{64}$" }), sessionId: Type.String({ minLength: 1, maxLength: 256 }),
|
|
15
|
+
state: Type.Union([Type.Literal("current"), Type.Literal("stopped")]),
|
|
16
|
+
observedAt: Type.Integer({ minimum: 0 }), expiresAt: Type.Integer({ minimum: 0 }),
|
|
17
|
+
}, { additionalProperties: false });
|
|
18
|
+
function directory(ref, create = false) {
|
|
19
|
+
const path = join(ref.root, "current-runtimes");
|
|
20
|
+
if (create)
|
|
21
|
+
fs.mkdirSync(path, { mode: 0o700, recursive: true });
|
|
22
|
+
const stat = fs.lstatSync(path);
|
|
23
|
+
if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.geteuid?.() || (stat.mode & 0o7777) !== 0o700)
|
|
24
|
+
throw new Error("runtime observation unavailable");
|
|
25
|
+
return path;
|
|
26
|
+
}
|
|
27
|
+
/** The caller owns the real Pi event/heartbeat boundary. Each factory gets a
|
|
28
|
+
* distinct observer incarnation; competing writers are never a recency race. */
|
|
29
|
+
export function createCurrentRuntimeObserver(ref, runtimeId, now = Date.now, observerId = randomUUID()) {
|
|
30
|
+
if (!Value.Check(runtimeIdSchema, runtimeId) || !Value.Check(RecordSchema.properties.observerId, observerId))
|
|
31
|
+
throw new Error("invalid runtime scope");
|
|
32
|
+
let sessionId;
|
|
33
|
+
const write = (state) => {
|
|
34
|
+
if (sessionId === undefined)
|
|
35
|
+
return false;
|
|
36
|
+
let stage;
|
|
37
|
+
try {
|
|
38
|
+
const parent = directory(ref, true), time = now();
|
|
39
|
+
const record = { version: 1, runtimeId, observerId, policyId: ref.policyId, genesisDigest: ref.genesisDigest,
|
|
40
|
+
sessionId, state, observedAt: time, expiresAt: time + CURRENT_RUNTIME_TTL_MS };
|
|
41
|
+
if (!Value.Check(RecordSchema, record))
|
|
42
|
+
return false;
|
|
43
|
+
stage = join(parent, `${observerId}.${randomUUID()}.tmp`);
|
|
44
|
+
fs.writeFileSync(stage, JSON.stringify(record), { mode: 0o600, flag: "wx" });
|
|
45
|
+
fs.renameSync(stage, join(parent, `${observerId}.json`));
|
|
46
|
+
return true;
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
finally {
|
|
52
|
+
if (stage !== undefined) {
|
|
53
|
+
try {
|
|
54
|
+
fs.unlinkSync(stage);
|
|
55
|
+
}
|
|
56
|
+
catch { /* already published or unavailable */ }
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
return Object.freeze({
|
|
61
|
+
observe(currentSessionId) { sessionId = currentSessionId; return write("current"); },
|
|
62
|
+
stop() {
|
|
63
|
+
if (!write("stopped"))
|
|
64
|
+
return false;
|
|
65
|
+
// Only this process incarnation is retired. Never collect another writer's
|
|
66
|
+
// expired file: it may have refreshed since a reader inspected it.
|
|
67
|
+
try {
|
|
68
|
+
fs.unlinkSync(join(directory(ref), `${observerId}.json`));
|
|
69
|
+
}
|
|
70
|
+
catch { /* the stopped record remains deny-only */ }
|
|
71
|
+
return true;
|
|
72
|
+
},
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
/** Invalid evidence is deny-only, including an unreadable competing claim. A
|
|
76
|
+
* short lease bounds abrupt-exit residue; this is not remote reachability. */
|
|
77
|
+
export function discoverCurrentRuntimes(snapshot, visibleEndpoints, runtimeId, now = Date.now()) {
|
|
78
|
+
const unknown = () => ({ runtimes: [],
|
|
79
|
+
...(runtimeId === undefined ? {} : { currentBinding: { status: "unknown", runtimeId } }) });
|
|
80
|
+
try {
|
|
81
|
+
const parent = directory(snapshot.ref), names = fs.readdirSync(parent);
|
|
82
|
+
const claims = [];
|
|
83
|
+
for (const name of names) {
|
|
84
|
+
if (name.endsWith(".tmp"))
|
|
85
|
+
continue;
|
|
86
|
+
if (!/^[a-f0-9-]{36}\.json$/.test(name))
|
|
87
|
+
return unknown();
|
|
88
|
+
const file = readPrivateMessagingFile(join(parent, name));
|
|
89
|
+
if (file === undefined)
|
|
90
|
+
return unknown();
|
|
91
|
+
const record = JSON.parse(file.bytes.toString("utf8"));
|
|
92
|
+
if (!Value.Check(RecordSchema, record) || name !== `${record.observerId}.json` || record.policyId !== snapshot.ref.policyId || record.genesisDigest !== snapshot.ref.genesisDigest)
|
|
93
|
+
return unknown();
|
|
94
|
+
if (record.observedAt > now || record.expiresAt - record.observedAt !== CURRENT_RUNTIME_TTL_MS)
|
|
95
|
+
return unknown();
|
|
96
|
+
if (record.state !== "current" || record.expiresAt <= now)
|
|
97
|
+
continue;
|
|
98
|
+
claims.push(record);
|
|
99
|
+
// Bound live output, not historical files left behind by crashes.
|
|
100
|
+
if (claims.length > 128)
|
|
101
|
+
return unknown();
|
|
102
|
+
}
|
|
103
|
+
const visible = (claim) => snapshot.manifest.registrations.find(r => r.runtimeSessionId === claim.sessionId && r.status === "active" && r.presenceDisclosure && visibleEndpoints.includes(r.endpointId));
|
|
104
|
+
const runtimes = [...new Set(claims.filter(c => visible(c) !== undefined).map(c => c.runtimeId))].sort().map(runtimeId => ({ runtimeId }));
|
|
105
|
+
if (runtimeId === undefined)
|
|
106
|
+
return { runtimes };
|
|
107
|
+
const matches = claims.filter(c => c.runtimeId === runtimeId);
|
|
108
|
+
if (matches.length === 0 || matches.some(c => visible(c) === undefined))
|
|
109
|
+
return { runtimes, currentBinding: { status: "unknown", runtimeId } };
|
|
110
|
+
if (matches.length > 1)
|
|
111
|
+
return { runtimes, currentBinding: { status: "ambiguous", runtimeId } };
|
|
112
|
+
const claim = matches[0], registration = visible(claim);
|
|
113
|
+
return { runtimes, currentBinding: { status: "verified", runtimeId, endpointId: registration.endpointId,
|
|
114
|
+
source: "pi.runtime.lifecycle", observedAt: new Date(claim.observedAt).toISOString(), expiresAt: new Date(claim.expiresAt).toISOString() } };
|
|
115
|
+
}
|
|
116
|
+
catch {
|
|
117
|
+
return unknown();
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
//# sourceMappingURL=current-runtime-binding.js.map
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
/** Local operator selection, scoped to a trusted CE caller launch, never a
|
|
2
|
+
* ChatGPT conversation or message permission. No remote mutation API exists. */
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
5
|
+
import { dirname, isAbsolute, normalize } from "node:path";
|
|
6
|
+
import { isDeepStrictEqual } from "node:util";
|
|
7
|
+
import { Type } from "@sinclair/typebox";
|
|
8
|
+
import { Value } from "@sinclair/typebox/value";
|
|
9
|
+
import { parseMcpBindingConfig } from "../host/mcp-binding-config.js";
|
|
10
|
+
import { readPrivateMessagingFile } from "./messaging-config.js";
|
|
11
|
+
import { readLivePolicy } from "./live-session-policy.js";
|
|
12
|
+
import { discoverCurrentRuntimes, RUNTIME_ID_PATTERN } from "./current-runtime-binding.js";
|
|
13
|
+
import { normalizeRuntimeGroup, RUNTIME_GROUP_PATTERN } from "../runtime/runtime-group.js";
|
|
14
|
+
export { normalizeRuntimeGroup } from "../runtime/runtime-group.js";
|
|
15
|
+
const runtime = Type.String({ pattern: RUNTIME_ID_PATTERN });
|
|
16
|
+
const revision = Type.String({ pattern: "^(unbound|[a-f0-9]{64})$" });
|
|
17
|
+
const groupName = Type.String({ pattern: RUNTIME_GROUP_PATTERN });
|
|
18
|
+
const recordFields = { scopeDigest: Type.String({ pattern: "^[a-f0-9]{64}$" }),
|
|
19
|
+
nonce: Type.String({ pattern: "^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$" }), runtimeId: Type.Union([runtime, Type.Null()]) };
|
|
20
|
+
const groupFields = { name: groupName, runtimeId: Type.Union([runtime, Type.Null()]) };
|
|
21
|
+
const RecordSchema = Type.Union([
|
|
22
|
+
Type.Object({ version: Type.Literal(1), ...recordFields }, { additionalProperties: false }),
|
|
23
|
+
Type.Object({ version: Type.Literal(2), ...recordFields, groups: Type.Array(Type.Object(groupFields, { additionalProperties: false }), { maxItems: 128 }) }, { additionalProperties: false }),
|
|
24
|
+
]);
|
|
25
|
+
const UpdateSchema = Type.Object({ runtimeId: Type.Union([runtime, Type.Null()]), expectedRevision: revision,
|
|
26
|
+
acceptEndpointScope: Type.Literal(true) }, { additionalProperties: false });
|
|
27
|
+
const groupCommon = { group: Type.String({ minLength: 1, maxLength: 256 }), expectedRevision: revision, acceptEndpointScope: Type.Literal(true) };
|
|
28
|
+
const GroupUpdateSchema = Type.Union([
|
|
29
|
+
Type.Object({ ...groupCommon, action: Type.Union([Type.Literal("bind"), Type.Literal("rebind")]), runtimeId: runtime }, { additionalProperties: false }),
|
|
30
|
+
Type.Object({ ...groupCommon, action: Type.Literal("revoke") }, { additionalProperties: false }),
|
|
31
|
+
Type.Object({ ...groupCommon, action: Type.Literal("rename"), nextName: Type.String({ minLength: 1, maxLength: 256 }) }, { additionalProperties: false }),
|
|
32
|
+
]);
|
|
33
|
+
const unavailable = (group) => ({ scope: "ce-endpoint", status: "unavailable", ...(group === undefined ? {} : { group }) });
|
|
34
|
+
const hash = (bytes) => createHash("sha256").update(bytes).digest("hex");
|
|
35
|
+
const refusal = (kind) => new Error(`CE_RUNTIME_BINDING_${kind}`);
|
|
36
|
+
function privateDirectory(path) {
|
|
37
|
+
if (!isAbsolute(path) || normalize(path) !== path || fs.realpathSync(path) !== path)
|
|
38
|
+
throw refusal("INVALID");
|
|
39
|
+
const stat = fs.lstatSync(path);
|
|
40
|
+
if (!stat.isDirectory() || stat.uid !== process.geteuid?.() || (stat.mode & 0o7777) !== 0o700)
|
|
41
|
+
throw refusal("INVALID");
|
|
42
|
+
for (let parent = dirname(path);; parent = dirname(parent)) {
|
|
43
|
+
const s = fs.lstatSync(parent), stickyRoot = s.uid === 0 && (s.mode & 0o1000) !== 0;
|
|
44
|
+
if (!s.isDirectory() || (s.uid !== 0 && s.uid !== process.geteuid?.()) || ((s.mode & 0o022) !== 0 && !stickyRoot))
|
|
45
|
+
throw refusal("INVALID");
|
|
46
|
+
if (dirname(parent) === parent)
|
|
47
|
+
break;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
/** The host supplies this config; model arguments never choose caller identity.
|
|
51
|
+
* A different immutable config has a different sidecar scope and starts unbound. */
|
|
52
|
+
export function createEndpointRuntimeBinding(bindingPath, config) {
|
|
53
|
+
const parent = dirname(bindingPath);
|
|
54
|
+
privateDirectory(parent);
|
|
55
|
+
const launch = readPrivateMessagingFile(bindingPath);
|
|
56
|
+
if (launch === undefined || !isDeepStrictEqual(parseMcpBindingConfig(JSON.parse(launch.bytes.toString("utf8"))), config) ||
|
|
57
|
+
config.endpoint.adapter !== "chatgpt" || config.admissionPolicy === undefined ||
|
|
58
|
+
(config.admissionPolicy.kind !== "ce-live-session-v1" && config.admissionPolicy.kind !== "ce-live-session-v2"))
|
|
59
|
+
throw refusal("INVALID");
|
|
60
|
+
const ref = config.admissionPolicy, scopeDigest = hash(launch.bytes);
|
|
61
|
+
const path = bindingPath + ".runtime-binding.json", lock = path + ".lock";
|
|
62
|
+
const locked = () => { try {
|
|
63
|
+
fs.lstatSync(lock);
|
|
64
|
+
return true;
|
|
65
|
+
}
|
|
66
|
+
catch (error) {
|
|
67
|
+
if (error.code === "ENOENT")
|
|
68
|
+
return false;
|
|
69
|
+
throw error;
|
|
70
|
+
} };
|
|
71
|
+
const readCatalog = (ownLock = false) => {
|
|
72
|
+
try {
|
|
73
|
+
privateDirectory(parent);
|
|
74
|
+
const selected = readPrivateMessagingFile(bindingPath);
|
|
75
|
+
if (selected === undefined || hash(selected.bytes) !== scopeDigest || !ownLock && locked())
|
|
76
|
+
return;
|
|
77
|
+
const file = readPrivateMessagingFile(path);
|
|
78
|
+
if (!ownLock && locked())
|
|
79
|
+
return;
|
|
80
|
+
if (file === undefined)
|
|
81
|
+
return { revision: "unbound", runtimeId: null, groups: [] };
|
|
82
|
+
const value = JSON.parse(file.bytes.toString("utf8"));
|
|
83
|
+
if (!Value.Check(RecordSchema, value) || value.scopeDigest !== scopeDigest)
|
|
84
|
+
return;
|
|
85
|
+
const groups = value.version === 1 ? [] : value.groups;
|
|
86
|
+
if (new Set(groups.map(g => g.name)).size !== groups.length)
|
|
87
|
+
return;
|
|
88
|
+
return { revision: hash(file.bytes), runtimeId: value.runtimeId, groups };
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
const selection = (catalog, group) => {
|
|
95
|
+
if (catalog === undefined)
|
|
96
|
+
return unavailable(group);
|
|
97
|
+
const runtimeId = group === undefined ? catalog.runtimeId : catalog.groups.find(g => g.name === group)?.runtimeId;
|
|
98
|
+
const common = { scope: "ce-endpoint", revision: catalog.revision, ...(group === undefined ? {} : { group }) };
|
|
99
|
+
return runtimeId == null ? { ...common, status: "unbound" } : { ...common, status: "bound", runtimeId };
|
|
100
|
+
};
|
|
101
|
+
const syncParent = () => { const fd = fs.openSync(parent, fs.constants.O_RDONLY | fs.constants.O_DIRECTORY | fs.constants.O_NOFOLLOW); try {
|
|
102
|
+
fs.fsyncSync(fd);
|
|
103
|
+
}
|
|
104
|
+
finally {
|
|
105
|
+
fs.closeSync(fd);
|
|
106
|
+
} };
|
|
107
|
+
const assertRuntime = (runtimeId) => {
|
|
108
|
+
const snapshot = readLivePolicy(ref), manifest = snapshot.manifest;
|
|
109
|
+
if (!isDeepStrictEqual(manifest.store, config.store) || !isDeepStrictEqual(manifest.exchange, config.exchange) ||
|
|
110
|
+
!isDeepStrictEqual(manifest.chatgptEndpoint, config.endpoint) || manifest.mcp.payloadRead !== config.payloadRead.enabled || manifest.mcp.ack !== config.ack.enabled)
|
|
111
|
+
throw refusal("INVALID");
|
|
112
|
+
const visible = manifest.registrations.filter(r => r.status === "active" && r.presenceDisclosure).map(r => r.endpointId);
|
|
113
|
+
if (discoverCurrentRuntimes(snapshot, visible, runtimeId).currentBinding?.status !== "verified")
|
|
114
|
+
throw refusal("RUNTIME_UNAVAILABLE");
|
|
115
|
+
};
|
|
116
|
+
const commit = (expectedRevision, mutate, group) => {
|
|
117
|
+
privateDirectory(parent);
|
|
118
|
+
try {
|
|
119
|
+
fs.mkdirSync(lock, { mode: 0o700 });
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
throw refusal("CONFLICT");
|
|
123
|
+
}
|
|
124
|
+
let writing = false;
|
|
125
|
+
try {
|
|
126
|
+
const before = readCatalog(true);
|
|
127
|
+
if (before === undefined)
|
|
128
|
+
throw refusal("INVALID");
|
|
129
|
+
if (before.revision !== expectedRevision)
|
|
130
|
+
throw refusal("CONFLICT");
|
|
131
|
+
mutate(before);
|
|
132
|
+
const stage = path + ".stage-" + randomUUID();
|
|
133
|
+
// Legacy-only writes retain version 1; a named write upgrades once and
|
|
134
|
+
// keeps the unnamed selection. All names share one lock and revision.
|
|
135
|
+
const bytes = Buffer.from(JSON.stringify({ version: before.groups.length ? 2 : 1, scopeDigest, nonce: randomUUID(),
|
|
136
|
+
runtimeId: before.runtimeId, ...(before.groups.length ? { groups: before.groups.sort((a, b) => a.name.localeCompare(b.name)) } : {}) }) + "\n");
|
|
137
|
+
// Once IO begins an exception may leave durable state uncertain. Keep the
|
|
138
|
+
// lock for offline reconciliation; never infer failure means no change.
|
|
139
|
+
writing = true;
|
|
140
|
+
const fd = fs.openSync(stage, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, 0o600);
|
|
141
|
+
try {
|
|
142
|
+
fs.writeFileSync(fd, bytes);
|
|
143
|
+
fs.fsyncSync(fd);
|
|
144
|
+
}
|
|
145
|
+
finally {
|
|
146
|
+
fs.closeSync(fd);
|
|
147
|
+
}
|
|
148
|
+
fs.renameSync(stage, path);
|
|
149
|
+
syncParent();
|
|
150
|
+
const committed = selection(readCatalog(true), group);
|
|
151
|
+
if (committed.status === "unavailable")
|
|
152
|
+
throw refusal("WRITE_UNCERTAIN");
|
|
153
|
+
fs.rmdirSync(lock);
|
|
154
|
+
// Return the commit captured under our lock, not a successor's state.
|
|
155
|
+
return committed;
|
|
156
|
+
}
|
|
157
|
+
catch (error) {
|
|
158
|
+
if (!writing)
|
|
159
|
+
fs.rmdirSync(lock);
|
|
160
|
+
if (writing)
|
|
161
|
+
throw refusal("WRITE_UNCERTAIN");
|
|
162
|
+
throw error;
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
return Object.freeze({
|
|
166
|
+
read: () => selection(readCatalog()),
|
|
167
|
+
readGroup: (name) => selection(readCatalog(), normalizeRuntimeGroup(name)),
|
|
168
|
+
listGroups: () => {
|
|
169
|
+
const catalog = readCatalog();
|
|
170
|
+
if (catalog === undefined)
|
|
171
|
+
throw refusal("INVALID");
|
|
172
|
+
return catalog.groups.map(g => selection(catalog, g.name));
|
|
173
|
+
},
|
|
174
|
+
update(input) {
|
|
175
|
+
if (!Value.Check(UpdateSchema, input))
|
|
176
|
+
throw refusal("INVALID");
|
|
177
|
+
return commit(input.expectedRevision, catalog => {
|
|
178
|
+
if (input.runtimeId !== null)
|
|
179
|
+
assertRuntime(input.runtimeId);
|
|
180
|
+
catalog.runtimeId = input.runtimeId;
|
|
181
|
+
});
|
|
182
|
+
},
|
|
183
|
+
updateGroup(input) {
|
|
184
|
+
if (!Value.Check(GroupUpdateSchema, input))
|
|
185
|
+
throw refusal("INVALID");
|
|
186
|
+
const group = normalizeRuntimeGroup(input.group), nextName = input.action === "rename" ? normalizeRuntimeGroup(input.nextName) : undefined;
|
|
187
|
+
return commit(input.expectedRevision, catalog => {
|
|
188
|
+
const current = catalog.groups.find(g => g.name === group);
|
|
189
|
+
if (input.action === "rename") {
|
|
190
|
+
if (current === undefined)
|
|
191
|
+
throw refusal("GROUP_UNBOUND");
|
|
192
|
+
if (catalog.groups.some(g => g.name === nextName))
|
|
193
|
+
throw refusal("GROUP_EXISTS");
|
|
194
|
+
current.name = nextName;
|
|
195
|
+
}
|
|
196
|
+
else if (input.action === "revoke") {
|
|
197
|
+
if (current?.runtimeId == null)
|
|
198
|
+
throw refusal("GROUP_UNBOUND");
|
|
199
|
+
current.runtimeId = null;
|
|
200
|
+
}
|
|
201
|
+
else {
|
|
202
|
+
if (input.action === "bind" && current?.runtimeId != null)
|
|
203
|
+
throw refusal("GROUP_EXISTS");
|
|
204
|
+
if (input.action === "rebind" && current?.runtimeId == null)
|
|
205
|
+
throw refusal("GROUP_UNBOUND");
|
|
206
|
+
if (current === undefined && catalog.groups.length >= 128)
|
|
207
|
+
throw refusal("GROUP_LIMIT");
|
|
208
|
+
assertRuntime(input.runtimeId);
|
|
209
|
+
if (current === undefined)
|
|
210
|
+
catalog.groups.push({ name: group, runtimeId: input.runtimeId });
|
|
211
|
+
else
|
|
212
|
+
current.runtimeId = input.runtimeId;
|
|
213
|
+
}
|
|
214
|
+
}, nextName ?? group);
|
|
215
|
+
},
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
//# sourceMappingURL=endpoint-runtime-binding.js.map
|
|
@@ -6,6 +6,9 @@ import { parseTunnelProfile } from "./background-manager.js";
|
|
|
6
6
|
import { parseTunnelMcpCommand } from "./profile.js";
|
|
7
7
|
import { CeHostRefusal } from "../host/endpoint-host.js";
|
|
8
8
|
import { readLivePolicy } from "./live-session-policy.js";
|
|
9
|
+
import { discoverSessionSwitch } from "./session-switch-observation.js";
|
|
10
|
+
import { discoverCurrentRuntimes } from "./current-runtime-binding.js";
|
|
11
|
+
import { createEndpointRuntimeBinding } from "./endpoint-runtime-binding.js";
|
|
9
12
|
import { readOwnershipObservation } from "../storage/ownership.js";
|
|
10
13
|
const denied = () => { throw new CeHostRefusal("CE_HOST_AUTHORITY_ABSENT", false, "ADMISSION_POLICY_DENIED"); };
|
|
11
14
|
/** Launch bytes fix Store/Exchange/ChatGPT and the global ceilings. Every
|
|
@@ -105,7 +108,18 @@ export function createLiveMcpComposition(config, reader, options = {}) {
|
|
|
105
108
|
return original !== undefined && original.status === "active" && current.manifest.registrations.some(r => r.endpointId === original.endpointId && r.runtimeSessionId === original.runtimeSessionId && r.status === "active" && r.epoch === original.epoch) &&
|
|
106
109
|
(config.hooks ?? []).some(candidate => candidate.enabled && isDeepStrictEqual(candidate, rule));
|
|
107
110
|
};
|
|
108
|
-
|
|
111
|
+
const runtimeSelection = (group) => {
|
|
112
|
+
try {
|
|
113
|
+
if (options.bindingPath === undefined)
|
|
114
|
+
return { scope: "ce-endpoint", status: "unavailable", ...(group === undefined ? {} : { group }) };
|
|
115
|
+
const binding = createEndpointRuntimeBinding(options.bindingPath, config);
|
|
116
|
+
return group === undefined ? binding.read() : binding.readGroup(group);
|
|
117
|
+
}
|
|
118
|
+
catch {
|
|
119
|
+
return { scope: "ce-endpoint", status: "unavailable", ...(group === undefined ? {} : { group }) };
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
return Object.freeze({ ref, loaded, snapshot, recipients, admission, hookAllowed, runtimeSelection });
|
|
109
123
|
}
|
|
110
124
|
/** Synchronous observation only; never renews or changes bound admission. */
|
|
111
125
|
export function observeLiveMcpRuntime(live, host, bound, store, endpointId) {
|
|
@@ -123,7 +137,7 @@ export function observeLiveMcpRuntime(live, host, bound, store, endpointId) {
|
|
|
123
137
|
}
|
|
124
138
|
/** Only the visible projection is hashed. Internal sequence, IDs and policy
|
|
125
139
|
* digests never cross this adapter; real operational readiness remains advisory. */
|
|
126
|
-
export function projectEndpointDiscovery(discovery) {
|
|
140
|
+
export function projectEndpointDiscovery(discovery, sessionSwitch, current, runtimeSelection) {
|
|
127
141
|
const observedAt = discovery.observedAt;
|
|
128
142
|
if (!Number.isFinite(Date.parse(observedAt)))
|
|
129
143
|
return denied();
|
|
@@ -137,7 +151,31 @@ export function projectEndpointDiscovery(discovery) {
|
|
|
137
151
|
reachable: target.reason === "PORT_BLOCKED" ? "false" : "unknown",
|
|
138
152
|
reason: target.reason === "PRESENCE_WITHHELD" ? "PRESENCE_WITHHELD"
|
|
139
153
|
: target.reason === "PORT_BLOCKED" ? "MCP_OPERATION_BLOCKED" : "OBSERVATION_UNKNOWN" }));
|
|
140
|
-
const projection = { self, targets }
|
|
154
|
+
const projection = { self, targets, ...(sessionSwitch === undefined ? {} : { sessionSwitch }), ...current,
|
|
155
|
+
...(runtimeSelection === undefined ? {} : { runtimeSelection }) };
|
|
141
156
|
return { ...projection, observedAt, viewDigest: createHash("sha256").update(JSON.stringify(projection)).digest("hex") };
|
|
142
157
|
}
|
|
158
|
+
/** Equal policy tips around the complete observation bind visible targets and
|
|
159
|
+
* metadata to one revision. Any mid-query change removes the selected target. */
|
|
160
|
+
export function discoverLiveEndpoints(live, bound, previousEndpointId, runtimeId, useRuntimeBinding, group) {
|
|
161
|
+
const before = live.snapshot();
|
|
162
|
+
const selectedBinding = useRuntimeBinding === true || group !== undefined;
|
|
163
|
+
const selection = selectedBinding ? live.runtimeSelection(group) : undefined;
|
|
164
|
+
const selectedRuntime = selection === undefined ? runtimeId : selection.status === "bound" ? selection.runtimeId : undefined;
|
|
165
|
+
const admitted = bound.discover();
|
|
166
|
+
const endpoints = admitted.targets.map(target => target.endpointId);
|
|
167
|
+
const current = selectedBinding && selectedRuntime === undefined ? { runtimes: [] }
|
|
168
|
+
: discoverCurrentRuntimes(before, endpoints, selectedRuntime);
|
|
169
|
+
const relation = current.currentBinding;
|
|
170
|
+
const scoped = selectedBinding || runtimeId !== undefined;
|
|
171
|
+
const visible = !scoped ? admitted : { ...admitted, targets: admitted.targets.filter(target => relation?.status === "verified" && target.endpointId === relation.endpointId) };
|
|
172
|
+
const relationship = previousEndpointId === undefined ? undefined : discoverSessionSwitch(before, previousEndpointId, endpoints);
|
|
173
|
+
const after = live.snapshot();
|
|
174
|
+
if (selectedBinding && (before.digest !== after.digest || !isDeepStrictEqual(selection, live.runtimeSelection(group)))) {
|
|
175
|
+
return projectEndpointDiscovery({ ...admitted, targets: [] }, undefined, { runtimes: [] }, { scope: "ce-endpoint", status: "unavailable", ...(group === undefined ? {} : { group }) });
|
|
176
|
+
}
|
|
177
|
+
if (before.digest !== after.digest)
|
|
178
|
+
return projectEndpointDiscovery({ ...visible, targets: [] }, previousEndpointId === undefined ? undefined : { status: "unknown", previousEndpointId }, { runtimes: [], ...(runtimeId === undefined ? {} : { currentBinding: { status: "unknown", runtimeId } }) });
|
|
179
|
+
return projectEndpointDiscovery(visible, relationship, current, selection);
|
|
180
|
+
}
|
|
143
181
|
//# sourceMappingURL=live-mcp-composition.js.map
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
/** Metadata-only /new observations. The local Pi extension/OS user is trusted;
|
|
2
|
+
* hashes correlate its two lifecycle events, not an authority or a signature.
|
|
3
|
+
* These files never grant Endpoint permissions or move message/task state. */
|
|
4
|
+
import fs from "node:fs";
|
|
5
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
6
|
+
import { dirname, isAbsolute, join } from "node:path";
|
|
7
|
+
import { Type } from "@sinclair/typebox";
|
|
8
|
+
import { Value } from "@sinclair/typebox/value";
|
|
9
|
+
import { readPrivateMessagingFile } from "./messaging-config.js";
|
|
10
|
+
import { readLivePolicy } from "./live-session-policy.js";
|
|
11
|
+
const closed = { additionalProperties: false };
|
|
12
|
+
const label = Type.String({ minLength: 1, maxLength: 256 });
|
|
13
|
+
const digest = Type.String({ pattern: "^[a-f0-9]{64}$" });
|
|
14
|
+
const time = 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$" });
|
|
15
|
+
const Departure = Type.Object({
|
|
16
|
+
version: Type.Literal(1), source: Type.Literal("pi.session_shutdown.new"),
|
|
17
|
+
policyId: label, genesisDigest: digest, runtimeSessionId: label, endpointId: label, epoch: Type.Integer({ minimum: 1 }),
|
|
18
|
+
sessionFileDigest: digest, targetSessionFileDigest: digest, observedAt: time,
|
|
19
|
+
}, closed);
|
|
20
|
+
const Arrival = Type.Object({
|
|
21
|
+
version: Type.Literal(1), source: Type.Literal("pi.session_start.new"),
|
|
22
|
+
departureDigest: digest, runtimeSessionId: label, previousSessionFileDigest: digest, sessionFileDigest: digest, observedAt: time,
|
|
23
|
+
}, closed);
|
|
24
|
+
const hash = (value) => createHash("sha256").update(value).digest("hex");
|
|
25
|
+
const key = (runtimeSessionId, endpointId, epoch) => hash(JSON.stringify([runtimeSessionId, endpointId, epoch]));
|
|
26
|
+
const unavailable = () => { throw new Error("session switch unavailable"); };
|
|
27
|
+
function directory(ref, create = false) {
|
|
28
|
+
const path = join(ref.root, "session-switches");
|
|
29
|
+
if (create) {
|
|
30
|
+
try {
|
|
31
|
+
fs.mkdirSync(path, { mode: 0o700 });
|
|
32
|
+
}
|
|
33
|
+
catch (error) {
|
|
34
|
+
if (error.code !== "EEXIST")
|
|
35
|
+
throw error;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
const s = fs.lstatSync(path);
|
|
39
|
+
if (!s.isDirectory() || s.isSymbolicLink() || s.uid !== process.geteuid?.() || (s.mode & 0o7777) !== 0o700)
|
|
40
|
+
return unavailable();
|
|
41
|
+
return path;
|
|
42
|
+
}
|
|
43
|
+
function record(path, schema) {
|
|
44
|
+
const file = readPrivateMessagingFile(path);
|
|
45
|
+
if (file === undefined || file.bytes.length > 4096)
|
|
46
|
+
return unavailable();
|
|
47
|
+
let value;
|
|
48
|
+
try {
|
|
49
|
+
value = JSON.parse(file.bytes.toString("utf8"));
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
return unavailable();
|
|
53
|
+
}
|
|
54
|
+
if (!Value.Check(schema, value))
|
|
55
|
+
return unavailable();
|
|
56
|
+
const stamp = value.observedAt;
|
|
57
|
+
const date = new Date(stamp);
|
|
58
|
+
if (!Number.isFinite(date.getTime()) || date.toISOString() !== stamp)
|
|
59
|
+
return unavailable();
|
|
60
|
+
return { value: value, bytes: file.bytes };
|
|
61
|
+
}
|
|
62
|
+
function conflicting(path) {
|
|
63
|
+
try {
|
|
64
|
+
const fd = fs.openSync(`${path}.conflict`, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, 0o600);
|
|
65
|
+
try {
|
|
66
|
+
fs.fsyncSync(fd);
|
|
67
|
+
}
|
|
68
|
+
finally {
|
|
69
|
+
fs.closeSync(fd);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
if (error.code !== "EEXIST")
|
|
74
|
+
throw error;
|
|
75
|
+
}
|
|
76
|
+
const directory = fs.openSync(dirname(path), fs.constants.O_RDONLY | fs.constants.O_DIRECTORY | fs.constants.O_NOFOLLOW);
|
|
77
|
+
try {
|
|
78
|
+
fs.fsyncSync(directory);
|
|
79
|
+
}
|
|
80
|
+
finally {
|
|
81
|
+
fs.closeSync(directory);
|
|
82
|
+
}
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
function equivalent(a, b) {
|
|
86
|
+
// Both operands have already passed their closed record schema.
|
|
87
|
+
return JSON.stringify({ ...a, observedAt: null }) ===
|
|
88
|
+
JSON.stringify({ ...b, observedAt: null });
|
|
89
|
+
}
|
|
90
|
+
/** Publish by link, never rename over a prior observation. A failed/partial stage
|
|
91
|
+
* is not a selected half; an existing conflicting half cannot be overwritten. */
|
|
92
|
+
function publish(parent, name, schema, value) {
|
|
93
|
+
if (!Value.Check(schema, value))
|
|
94
|
+
return false;
|
|
95
|
+
const path = join(parent, name);
|
|
96
|
+
if (fs.existsSync(`${path}.conflict`))
|
|
97
|
+
return false;
|
|
98
|
+
if (fs.existsSync(path))
|
|
99
|
+
return equivalent(record(path, schema).value, value) || conflicting(path);
|
|
100
|
+
const stage = join(parent, `.stage-${randomUUID()}`);
|
|
101
|
+
const fd = fs.openSync(stage, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, 0o600);
|
|
102
|
+
try {
|
|
103
|
+
fs.writeFileSync(fd, JSON.stringify(value));
|
|
104
|
+
fs.fsyncSync(fd);
|
|
105
|
+
}
|
|
106
|
+
finally {
|
|
107
|
+
fs.closeSync(fd);
|
|
108
|
+
}
|
|
109
|
+
try {
|
|
110
|
+
fs.linkSync(stage, path);
|
|
111
|
+
}
|
|
112
|
+
catch (error) {
|
|
113
|
+
if (error.code !== "EEXIST")
|
|
114
|
+
throw error;
|
|
115
|
+
}
|
|
116
|
+
fs.unlinkSync(stage);
|
|
117
|
+
const dir = fs.openSync(parent, fs.constants.O_RDONLY | fs.constants.O_DIRECTORY | fs.constants.O_NOFOLLOW);
|
|
118
|
+
try {
|
|
119
|
+
fs.fsyncSync(dir);
|
|
120
|
+
}
|
|
121
|
+
finally {
|
|
122
|
+
fs.closeSync(dir);
|
|
123
|
+
}
|
|
124
|
+
return equivalent(record(path, schema).value, value) || conflicting(path);
|
|
125
|
+
}
|
|
126
|
+
function candidates(parent, matches) {
|
|
127
|
+
const names = fs.readdirSync(parent).filter(matches);
|
|
128
|
+
if (names.length > 128)
|
|
129
|
+
return unavailable();
|
|
130
|
+
return names;
|
|
131
|
+
}
|
|
132
|
+
function inPolicy(value, snapshot) {
|
|
133
|
+
return value.policyId === snapshot.ref.policyId && value.genesisDigest === snapshot.ref.genesisDigest;
|
|
134
|
+
}
|
|
135
|
+
export function observeSessionDeparture(ref, input) {
|
|
136
|
+
try {
|
|
137
|
+
if (input.sessionFile === undefined || input.targetSessionFile === undefined || !isAbsolute(input.sessionFile) ||
|
|
138
|
+
!isAbsolute(input.targetSessionFile) || input.sessionFile === input.targetSessionFile)
|
|
139
|
+
return false;
|
|
140
|
+
const snapshot = readLivePolicy(ref);
|
|
141
|
+
const registration = snapshot.manifest.registrations.find(r => r.status === "active" && r.runtimeSessionId === input.runtimeSessionId && r.endpointId === input.endpointId && r.epoch === input.epoch);
|
|
142
|
+
if (registration === undefined)
|
|
143
|
+
return false;
|
|
144
|
+
const value = {
|
|
145
|
+
version: 1, source: "pi.session_shutdown.new", policyId: ref.policyId, genesisDigest: ref.genesisDigest,
|
|
146
|
+
runtimeSessionId: input.runtimeSessionId, endpointId: input.endpointId, epoch: input.epoch,
|
|
147
|
+
sessionFileDigest: hash(input.sessionFile), targetSessionFileDigest: hash(input.targetSessionFile), observedAt: new Date().toISOString(),
|
|
148
|
+
};
|
|
149
|
+
return publish(directory(ref, true), `${key(value.runtimeSessionId, value.endpointId, value.epoch)}-${value.targetSessionFileDigest}.departure.json`, Departure, value);
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
return false;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
export function observeSessionArrival(ref, input) {
|
|
156
|
+
try {
|
|
157
|
+
if (input.previousSessionFile === undefined || input.sessionFile === undefined || !isAbsolute(input.previousSessionFile) ||
|
|
158
|
+
!isAbsolute(input.sessionFile) || input.previousSessionFile === input.sessionFile)
|
|
159
|
+
return false;
|
|
160
|
+
const snapshot = readLivePolicy(ref);
|
|
161
|
+
const parent = directory(ref);
|
|
162
|
+
const current = hash(input.sessionFile);
|
|
163
|
+
const names = candidates(parent, name => /^[a-f0-9]{64}-[a-f0-9]{64}\.departure\.json$/.test(name) && name.endsWith(`-${current}.departure.json`));
|
|
164
|
+
// More than one departing source for this destination is not resolved by time.
|
|
165
|
+
if (names.length !== 1)
|
|
166
|
+
return false;
|
|
167
|
+
if (fs.existsSync(join(parent, `${names[0]}.conflict`)))
|
|
168
|
+
return false;
|
|
169
|
+
const departure = record(join(parent, names[0]), Departure);
|
|
170
|
+
const d = departure.value;
|
|
171
|
+
if (!inPolicy(d, snapshot) || d.targetSessionFileDigest !== current || d.sessionFileDigest !== hash(input.previousSessionFile) || d.runtimeSessionId === input.runtimeSessionId)
|
|
172
|
+
return false;
|
|
173
|
+
return publish(parent, names[0].replace(".departure.json", ".arrival.json"), Arrival, {
|
|
174
|
+
version: 1, source: "pi.session_start.new", departureDigest: hash(departure.bytes), runtimeSessionId: input.runtimeSessionId,
|
|
175
|
+
previousSessionFileDigest: d.sessionFileDigest, sessionFileDigest: current, observedAt: new Date().toISOString(),
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
catch {
|
|
179
|
+
return false;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
export function discoverSessionSwitch(snapshot, previousEndpointId, visibleEndpoints) {
|
|
183
|
+
const unknown = { status: "unknown", previousEndpointId };
|
|
184
|
+
try {
|
|
185
|
+
if (!visibleEndpoints.includes(previousEndpointId))
|
|
186
|
+
return unknown;
|
|
187
|
+
const old = snapshot.manifest.registrations.find(r => r.endpointId === previousEndpointId && r.status === "active" && r.presenceDisclosure);
|
|
188
|
+
if (old === undefined)
|
|
189
|
+
return unknown;
|
|
190
|
+
const parent = directory(snapshot.ref);
|
|
191
|
+
const prefix = `${key(old.runtimeSessionId, old.endpointId, old.epoch)}-`;
|
|
192
|
+
const names = candidates(parent, name => name.startsWith(prefix) && /^[a-f0-9]{64}-[a-f0-9]{64}\.departure\.json$/.test(name));
|
|
193
|
+
if (names.length !== 1)
|
|
194
|
+
return unknown;
|
|
195
|
+
if (fs.existsSync(join(parent, `${names[0]}.conflict`)) || fs.existsSync(join(parent, names[0].replace(".departure.json", ".arrival.json.conflict"))))
|
|
196
|
+
return unknown;
|
|
197
|
+
const departure = record(join(parent, names[0]), Departure);
|
|
198
|
+
const d = departure.value;
|
|
199
|
+
if (!inPolicy(d, snapshot) || d.runtimeSessionId !== old.runtimeSessionId || d.endpointId !== old.endpointId || d.epoch !== old.epoch || names[0] !== `${prefix}${d.targetSessionFileDigest}.departure.json`)
|
|
200
|
+
return unknown;
|
|
201
|
+
const a = record(join(parent, names[0].replace(".departure.json", ".arrival.json")), Arrival).value;
|
|
202
|
+
if (a.departureDigest !== hash(departure.bytes) || a.previousSessionFileDigest !== d.sessionFileDigest || a.sessionFileDigest !== d.targetSessionFileDigest || a.runtimeSessionId === d.runtimeSessionId)
|
|
203
|
+
return unknown;
|
|
204
|
+
const successors = snapshot.manifest.registrations.filter(r => r.runtimeSessionId === a.runtimeSessionId && r.status === "active");
|
|
205
|
+
// A later epoch cannot reuse a pre-authorization arrival. /new creates a new
|
|
206
|
+
// UUID; only its first independent authorization can match this observation.
|
|
207
|
+
if (successors.length !== 1)
|
|
208
|
+
return unknown;
|
|
209
|
+
const next = successors[0];
|
|
210
|
+
if (next.epoch !== 1 || !next.presenceDisclosure || !visibleEndpoints.includes(next.endpointId) || next.endpointId === previousEndpointId)
|
|
211
|
+
return unknown;
|
|
212
|
+
return { status: "verified", previousEndpointId, successorEndpointId: next.endpointId, source: "pi.new.lifecycle", observedAt: a.observedAt };
|
|
213
|
+
}
|
|
214
|
+
catch {
|
|
215
|
+
return unknown;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
//# sourceMappingURL=session-switch-observation.js.map
|