@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,214 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import { isDeepStrictEqual } from "node:util";
|
|
3
|
+
import { CeHostRefusal, type CeMappingIdentifiers } from "../dist/endpoints/pi/session-host.js";
|
|
4
|
+
|
|
5
|
+
type Entry = Record<string, unknown>;
|
|
6
|
+
type Store = { readonly directory: string; readonly file: string };
|
|
7
|
+
export interface RecoveryAttempt {
|
|
8
|
+
readonly version: 1;
|
|
9
|
+
readonly attemptId: string;
|
|
10
|
+
readonly piSessionId: string;
|
|
11
|
+
readonly endpointId: string;
|
|
12
|
+
readonly store: Store;
|
|
13
|
+
readonly oldMapping: CeMappingIdentifiers;
|
|
14
|
+
readonly failureIds: readonly string[];
|
|
15
|
+
readonly policyIdentity: string;
|
|
16
|
+
}
|
|
17
|
+
export interface AutomaticRecoveryAttempt extends Omit<RecoveryAttempt, "version"> {
|
|
18
|
+
readonly version: 2;
|
|
19
|
+
readonly mode: "automatic";
|
|
20
|
+
readonly sourceMappingEntryId: string;
|
|
21
|
+
}
|
|
22
|
+
type Attempt = RecoveryAttempt | AutomaticRecoveryAttempt;
|
|
23
|
+
function deny(): never { throw new CeHostRefusal("CE_HOST_MAPPING_INVALID"); }
|
|
24
|
+
const record = (value: unknown): value is Entry => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
25
|
+
const id = (value: unknown): value is string => typeof value === "string" && value.length > 0 && value.length <= 4096;
|
|
26
|
+
const exact = (value: Entry, keys: readonly string[]) => Object.keys(value).length === keys.length && keys.every(key => Object.hasOwn(value, key));
|
|
27
|
+
const mappingKeys = ["endpointId", "participantId", "sessionId", "exchangeId"] as const;
|
|
28
|
+
export const mappingIdentifiers = (value: unknown): value is CeMappingIdentifiers => record(value) && exact(value, mappingKeys) && mappingKeys.every(key => id(value[key]));
|
|
29
|
+
const attemptKeys = ["version", "attemptId", "piSessionId", "endpointId", "store", "oldMapping", "failureIds", "policyIdentity"];
|
|
30
|
+
function attempt(value: unknown): value is Attempt {
|
|
31
|
+
if (!record(value)) return false;
|
|
32
|
+
const keys = value.version === 1 ? attemptKeys : value.version === 2 ? [...attemptKeys, "mode", "sourceMappingEntryId"] : [];
|
|
33
|
+
return exact(value, keys) && (value.version === 1 || (value.version === 2 && value.mode === "automatic" && id(value.sourceMappingEntryId))) &&
|
|
34
|
+
id(value.attemptId) && id(value.piSessionId) && id(value.endpointId) && record(value.store) && exact(value.store, ["directory", "file"]) &&
|
|
35
|
+
id(value.store.directory) && id(value.store.file) && mappingIdentifiers(value.oldMapping) && value.oldMapping.endpointId === value.endpointId &&
|
|
36
|
+
Array.isArray(value.failureIds) && value.failureIds.length > 0 && value.failureIds.every(id) && new Set(value.failureIds).size === value.failureIds.length &&
|
|
37
|
+
typeof value.policyIdentity === "string" && /^[a-f0-9]{64}$/.test(value.policyIdentity);
|
|
38
|
+
}
|
|
39
|
+
export interface RecoveryDiagnostics {
|
|
40
|
+
readonly invalid: boolean;
|
|
41
|
+
readonly failures: readonly Entry[];
|
|
42
|
+
}
|
|
43
|
+
export interface NativeSessionLifecycle extends RecoveryDiagnostics {
|
|
44
|
+
readonly mapping?: CeMappingIdentifiers;
|
|
45
|
+
readonly sourceMappingEntryId?: string;
|
|
46
|
+
readonly releaseIntent?: "shutdown" | "deactivate" | "legacy";
|
|
47
|
+
readonly hasRecovery: boolean;
|
|
48
|
+
readonly initialRepairEligible: boolean;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Native append order is evidence only. The caller still needs ordinary
|
|
52
|
+
* policy, process mutex and Host authority checks before adopting a binding. */
|
|
53
|
+
export function nativeSessionLifecycle(history: readonly unknown[], piSessionId: string, store: Store): NativeSessionLifecycle {
|
|
54
|
+
const failures: Entry[] = [];
|
|
55
|
+
let hasRecovery = false;
|
|
56
|
+
try {
|
|
57
|
+
if (!id(piSessionId)) deny();
|
|
58
|
+
const entries = new Map<string, { entry: Entry; index: number }>();
|
|
59
|
+
for (const [index, e] of history.entries()) {
|
|
60
|
+
if (!record(e) || !id(e.id) || entries.has(e.id)) deny();
|
|
61
|
+
entries.set(e.id, { entry: e, index });
|
|
62
|
+
}
|
|
63
|
+
const resolved = new Set<string>(), attemptIds = new Set<string>();
|
|
64
|
+
const tuples = new Map<string, string>();
|
|
65
|
+
let mapping: CeMappingIdentifiers | undefined;
|
|
66
|
+
let sourceMappingEntryId: string | undefined;
|
|
67
|
+
let releaseIntent: NativeSessionLifecycle["releaseIntent"];
|
|
68
|
+
let anyRelease = false;
|
|
69
|
+
let pending: { data: Attempt; id: string; index: number; mappingId?: string; newMapping?: CeMappingIdentifiers } | undefined;
|
|
70
|
+
for (const [index, raw] of history.entries()) {
|
|
71
|
+
const e = raw as Entry;
|
|
72
|
+
if (e.type !== "custom") continue;
|
|
73
|
+
const data = e.data;
|
|
74
|
+
switch (e.customType) {
|
|
75
|
+
case "ce-lifecycle-blocked":
|
|
76
|
+
if (!record(data) || !exact(data, ["piSessionId", "endpointId", "code"]) || data.piSessionId !== piSessionId || !id(data.endpointId) || !id(data.code) || pending) deny();
|
|
77
|
+
failures.push(e);
|
|
78
|
+
break;
|
|
79
|
+
case "ce-messaging-released":
|
|
80
|
+
if (!record(data) || !exact(data, [...mappingKeys, "piSessionId", ...(Object.hasOwn(data, "intent") ? ["intent"] : [])]) ||
|
|
81
|
+
data.piSessionId !== piSessionId || !mapping || !mappingKeys.every(key => data[key] === mapping![key]) || pending ||
|
|
82
|
+
(Object.hasOwn(data, "intent") && data.intent !== "shutdown" && data.intent !== "deactivate")) deny();
|
|
83
|
+
releaseIntent = data.intent === undefined ? "legacy" : data.intent as "shutdown" | "deactivate";
|
|
84
|
+
anyRelease = true;
|
|
85
|
+
break;
|
|
86
|
+
case "ce-recovery-attempt": {
|
|
87
|
+
hasRecovery = true;
|
|
88
|
+
if (pending || !attempt(data) || data.piSessionId !== piSessionId || !isDeepStrictEqual(data.store, store) ||
|
|
89
|
+
!isDeepStrictEqual(mapping, data.oldMapping) || releaseIntent || attemptIds.has(data.attemptId)) deny();
|
|
90
|
+
const applicable = failures.filter(f => !resolved.has(String(f.id)));
|
|
91
|
+
if (applicable.some(f => (f.data as Entry).endpointId !== data.endpointId) ||
|
|
92
|
+
!isDeepStrictEqual(new Set(data.failureIds), new Set(applicable.map(f => f.id)))) deny();
|
|
93
|
+
if (data.version === 2 && (tuples.size !== 1 || anyRelease || attemptIds.size !== 0 || data.sourceMappingEntryId !== sourceMappingEntryId)) deny();
|
|
94
|
+
attemptIds.add(data.attemptId);
|
|
95
|
+
pending = { data, id: String(e.id), index };
|
|
96
|
+
break;
|
|
97
|
+
}
|
|
98
|
+
case "ce-mapping": {
|
|
99
|
+
if (!mappingIdentifiers(data)) deny();
|
|
100
|
+
const changed = mapping !== undefined && !isDeepStrictEqual(mapping, data);
|
|
101
|
+
if (pending) {
|
|
102
|
+
if (pending.mappingId || !changed || data.endpointId !== pending.data.endpointId || data.participantId !== pending.data.oldMapping.participantId ||
|
|
103
|
+
data.exchangeId !== pending.data.oldMapping.exchangeId || data.sessionId === pending.data.oldMapping.sessionId) deny();
|
|
104
|
+
pending.mappingId = String(e.id); pending.newMapping = data;
|
|
105
|
+
} else if (changed && !releaseIntent) deny();
|
|
106
|
+
mapping = data;
|
|
107
|
+
const key = JSON.stringify(mappingKeys.map(k => data[k]));
|
|
108
|
+
if (!tuples.has(key)) tuples.set(key, String(e.id));
|
|
109
|
+
sourceMappingEntryId = tuples.get(key)!;
|
|
110
|
+
releaseIntent = undefined;
|
|
111
|
+
break;
|
|
112
|
+
}
|
|
113
|
+
case "ce-recovery-resolved": {
|
|
114
|
+
hasRecovery = true;
|
|
115
|
+
if (!pending || !record(data)) deny();
|
|
116
|
+
const { attemptEntryId, mappingEntryId, newMapping, ...copy } = data;
|
|
117
|
+
if (!attempt(copy) || !isDeepStrictEqual(copy, pending.data) || attemptEntryId !== pending.id || mappingEntryId !== pending.mappingId ||
|
|
118
|
+
!pending.newMapping || !isDeepStrictEqual(newMapping, pending.newMapping) || index <= pending.index ||
|
|
119
|
+
!id(mappingEntryId) || entries.get(mappingEntryId)!.index >= index) deny();
|
|
120
|
+
for (const failureId of pending.data.failureIds) resolved.add(failureId);
|
|
121
|
+
pending = undefined;
|
|
122
|
+
break;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
if (pending || failures.some(f => mapping && (f.data as Entry).endpointId !== mapping.endpointId)) deny();
|
|
127
|
+
const unresolved = failures.filter(f => !resolved.has(String(f.id)));
|
|
128
|
+
return { invalid: false, failures: unresolved, hasRecovery, initialRepairEligible: !hasRecovery && tuples.size === 1 && unresolved.length > 0 && !anyRelease,
|
|
129
|
+
...(mapping ? { mapping } : {}), ...(sourceMappingEntryId ? { sourceMappingEntryId } : {}), ...(releaseIntent ? { releaseIntent } : {}) };
|
|
130
|
+
} catch {
|
|
131
|
+
return { invalid: true, failures, hasRecovery, initialRepairEligible: false };
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Retained shape for callers migrating from branch-scoped diagnostics. */
|
|
136
|
+
export function recoveryDiagnostics(branch: readonly Entry[], history: readonly Entry[] | undefined, piSessionId: string, store: Store): RecoveryDiagnostics {
|
|
137
|
+
const result = nativeSessionLifecycle(history ?? branch, piSessionId, store);
|
|
138
|
+
return { invalid: result.invalid || (history === undefined && result.hasRecovery), failures: result.failures };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// Pi owns writes. This descriptor is only a consistency/durability witness,
|
|
142
|
+
// never a lock or a substitute for Host admission.
|
|
143
|
+
export function openRecoveryJournal(path: string | undefined) {
|
|
144
|
+
if (!path) deny();
|
|
145
|
+
const fd = fs.openSync(path, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
|
|
146
|
+
const initial = fs.fstatSync(fd);
|
|
147
|
+
const assertIdentity = () => {
|
|
148
|
+
const current = fs.fstatSync(fd), named = fs.lstatSync(path);
|
|
149
|
+
if (!current.isFile() || !named.isFile() || current.uid !== process.geteuid?.() || (current.mode & 0o022) !== 0 ||
|
|
150
|
+
current.dev !== initial.dev || current.ino !== initial.ino || current.uid !== initial.uid ||
|
|
151
|
+
named.dev !== current.dev || named.ino !== current.ino || named.uid !== current.uid || named.mode !== current.mode || current.size === 0) deny();
|
|
152
|
+
return current;
|
|
153
|
+
};
|
|
154
|
+
try { assertIdentity(); } catch (error) { fs.closeSync(fd); throw error; }
|
|
155
|
+
let nativeId: string | undefined;
|
|
156
|
+
const readHistory = (piSessionId?: string) => {
|
|
157
|
+
const before = assertIdentity();
|
|
158
|
+
if (before.size > 64 * 1024 * 1024) deny();
|
|
159
|
+
const buffer = Buffer.alloc(before.size);
|
|
160
|
+
if (fs.readSync(fd, buffer, 0, buffer.length, 0) !== buffer.length) deny();
|
|
161
|
+
const text = new TextDecoder("utf-8", { fatal: true }).decode(buffer);
|
|
162
|
+
const lines = text.split("\n");
|
|
163
|
+
if (lines.pop() !== "") deny();
|
|
164
|
+
let values: unknown[];
|
|
165
|
+
try { values = lines.map(line => JSON.parse(line)); } catch { deny(); }
|
|
166
|
+
const header = values.shift();
|
|
167
|
+
if (!record(header) || header.type !== "session" || header.version !== 3 || !id(header.id) ||
|
|
168
|
+
(piSessionId !== undefined && header.id !== piSessionId) || (nativeId !== undefined && header.id !== nativeId) || !id(header.timestamp) || !id(header.cwd) ||
|
|
169
|
+
!exact(header, ["type", "version", "id", "timestamp", "cwd", ...(Object.hasOwn(header, "parentSession") ? ["parentSession"] : [])]) ||
|
|
170
|
+
(Object.hasOwn(header, "parentSession") && !id(header.parentSession))) deny();
|
|
171
|
+
const ids = new Set<string>([header.id]);
|
|
172
|
+
for (const e of values) {
|
|
173
|
+
if (!record(e) || !id(e.id) || !id(e.type) || e.type === "session" || ids.has(e.id)) deny();
|
|
174
|
+
ids.add(e.id);
|
|
175
|
+
}
|
|
176
|
+
const assertUnchanged = () => {
|
|
177
|
+
const after = assertIdentity();
|
|
178
|
+
if (after.size !== before.size || after.mtimeMs !== before.mtimeMs || after.ctimeMs !== before.ctimeMs) deny();
|
|
179
|
+
};
|
|
180
|
+
assertUnchanged();
|
|
181
|
+
return { values, nativeId: header.id, assertUnchanged };
|
|
182
|
+
};
|
|
183
|
+
let expected: unknown[] | undefined;
|
|
184
|
+
return {
|
|
185
|
+
assertIdentity,
|
|
186
|
+
verifyHistory(entries: readonly unknown[], piSessionId: string): void {
|
|
187
|
+
let snapshot: unknown[];
|
|
188
|
+
try { snapshot = JSON.parse(JSON.stringify(entries)); } catch { deny(); }
|
|
189
|
+
const read = readHistory(piSessionId);
|
|
190
|
+
if (!Array.isArray(snapshot) || !isDeepStrictEqual(read.values, snapshot) ||
|
|
191
|
+
(expected && !isDeepStrictEqual(snapshot, expected))) deny();
|
|
192
|
+
read.assertUnchanged();
|
|
193
|
+
nativeId = read.nativeId;
|
|
194
|
+
expected = snapshot;
|
|
195
|
+
},
|
|
196
|
+
verify(entry: unknown): void {
|
|
197
|
+
if (!record(entry) || !id(entry.id)) deny();
|
|
198
|
+
let snapshot: Entry;
|
|
199
|
+
try { snapshot = JSON.parse(JSON.stringify(entry)); } catch { deny(); }
|
|
200
|
+
const read = readHistory();
|
|
201
|
+
if (expected) {
|
|
202
|
+
const next = [...expected, snapshot];
|
|
203
|
+
// Callers may have verified the just-appended full snapshot already.
|
|
204
|
+
if (!isDeepStrictEqual(read.values, next) && !isDeepStrictEqual(read.values, expected)) deny();
|
|
205
|
+
if (!isDeepStrictEqual(read.values.at(-1), snapshot)) deny();
|
|
206
|
+
} else if (read.values.filter(e => record(e) && e.id === entry.id).length !== 1 || !isDeepStrictEqual(read.values.at(-1), snapshot)) deny();
|
|
207
|
+
fs.fsyncSync(fd);
|
|
208
|
+
read.assertUnchanged();
|
|
209
|
+
nativeId = read.nativeId;
|
|
210
|
+
expected = read.values;
|
|
211
|
+
},
|
|
212
|
+
close(): void { fs.closeSync(fd); },
|
|
213
|
+
};
|
|
214
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: ce-hook-script
|
|
3
|
+
description: Use when configuring a local Pi Chat Exchange message Hook or writing a metadata-only notification script for ChatGPT to Pi or Pi to ChatGPT messages.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Local CE Hook scripts
|
|
7
|
+
|
|
8
|
+
Read the package's [Hook contract](../../docs/hooks.md) in a source checkout before adapting a script. In an installed package, use the contract below. Use the bundled [Python stdlib example](examples/file-notification.py); it requires a POSIX Python 3 interpreter supporting `O_NOFOLLOW`. It performs no network requests and does not invoke CE, ACK messages, or change task state.
|
|
9
|
+
|
|
10
|
+
## Choose the sending process
|
|
11
|
+
|
|
12
|
+
Hooks run after a new Message and Payload successfully commit to Store, without waiting for Endpoint delivery or ACK. Configure the process that sends the message:
|
|
13
|
+
|
|
14
|
+
| Direction | Local configuration owning the rule | Exact recipient |
|
|
15
|
+
| --- | --- | --- |
|
|
16
|
+
| ChatGPT → Pi | Sender MCP binding configuration, top-level `hooks` | `{ "adapter": "pi", "endpointId": "pi/main" }` |
|
|
17
|
+
| Pi → ChatGPT | Sender Pi explicit `CE_ALLOWLIST` file or legacy allowlist, top-level `hooks` | `{ "adapter": "chatgpt", "endpointId": "chatgpt/main" }` |
|
|
18
|
+
| Pi → ChatGPT (multi-session) | Selected `ce-multi-session-v1` manifest, the sending Session's `registrations[]` item, optional `hooks` | Exactly `manifest.chatgptEndpoint` |
|
|
19
|
+
|
|
20
|
+
Replace sample Endpoint IDs with the actual complete recipient identity. In multi-session mode, MCP → Pi rules remain in binding `hooks` and must target active registered Pi Endpoints. Pi projects only the selected Session registration's rules. There is no global manifest `hooks` field or new permission; absence remains backward compatible. Do not silently switch configuration modes.
|
|
21
|
+
|
|
22
|
+
## Static local rule
|
|
23
|
+
|
|
24
|
+
Locate the actual interpreter with `python3 -c 'import sys; print(sys.executable)'`. Resolve the bundled script to its absolute installed path. Prepare an operator-owned private directory (mode 0700) outside Store for notifications. Replace all illustrative paths below with absolute local paths; keep interpreter, script, and output filename fixed in local configuration. Use this fragment in operator-controlled authoring inputs, preserving all other required fields. For multi-session Pi, place the array on the relevant manifest registration. MCP binding and manifest are separate digest-paired files in an immutable generation: prepare inputs offline and publish through the existing operator-authorized controlled generation path. Never edit production content-addressed files in place. There is no automatic migration or new Hook CLI; `/ce-tunnel convert` and `/ce-tunnel register` have no flags for adding Hooks:
|
|
25
|
+
|
|
26
|
+
```json
|
|
27
|
+
{
|
|
28
|
+
"hooks": [
|
|
29
|
+
{
|
|
30
|
+
"id": "pi-file-notification",
|
|
31
|
+
"event": "ce.message.committed.v1",
|
|
32
|
+
"recipient": { "adapter": "pi", "endpointId": "pi/main" },
|
|
33
|
+
"command": "/absolute/path/to/python3",
|
|
34
|
+
"args": ["/absolute/path/to/skills/ce-hook-script/examples/file-notification.py", "/absolute/private/notifications.jsonl"],
|
|
35
|
+
"timeoutMs": 30000,
|
|
36
|
+
"enabled": true
|
|
37
|
+
}
|
|
38
|
+
]
|
|
39
|
+
}
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
For Pi → ChatGPT, use the same static command and args in the Pi allowlist or corresponding multi-session manifest registration, with a distinct rule ID and the actual ChatGPT recipient (exactly `manifest.chatgptEndpoint` in multi-session mode). Matching requires both event and complete recipient. Timeout accepts 1000–60000 ms. CE directly spawns the interpreter with `shell:false`; never interpolate remote content or metadata into paths, arguments, or shell code. Remote messages cannot select commands.
|
|
43
|
+
|
|
44
|
+
## stdin contract
|
|
45
|
+
|
|
46
|
+
The runner supplies one UTF-8 JSON document followed by EOF, with exactly these top-level fields:
|
|
47
|
+
|
|
48
|
+
```text
|
|
49
|
+
schemaVersion,event,eventId,eventKey,messageId,exchangeId,sender,recipient,createdAt,payloadDigest,payloadLength
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
`schemaVersion` is 1; `event` is `ce.message.committed.v1`. Sender and recipient contain exactly `adapter` and `endpointId`. IDs and `createdAt` are strings; `payloadDigest` is the original Payload's SHA-256 hex digest; `payloadLength` is its UTF-8 byte length. There is no payloadText, session, capability, or invented correlation field. Hook configuration grants no payload-read authority.
|
|
53
|
+
|
|
54
|
+
The example bounds input to 16384 bytes, rejects duplicate/unknown fields and invalid metadata, and appends one JSON line containing exactly the validated envelope. It never derives the output path from stdin. Output must be a private regular file owned by the operator, with one hard link; symlinks and special files are refused. Keep ancestor directories trusted. Existing contents are preserved. Success is silent; failure exits 1 with only `notification rejected` on stderr.
|
|
55
|
+
|
|
56
|
+
## Audit and failure handling
|
|
57
|
+
|
|
58
|
+
Pi `/ce-hooks` displays the **loaded rules**, including configuration source, fixed command/args and recipient. `configured` counts loaded rules; in multi-session mode `active` counts the effective current subset, with source `selected multi-session profile registration`. Only identical enabled static rules in both loaded and current policy remain effective, with matching registration identity, Endpoint and epoch, and active status in both. MCP rules additionally require an admitted registered recipient. Current policy can narrow the loaded snapshot but cannot expand it; additions or changed rules require reloading the owning process/configuration through its normal lifecycle. MCP reports sanitized counts on stderr.
|
|
59
|
+
|
|
60
|
+
An optional runner admission gate checks current policy before each child starts, including queued work. Denial records `SKIPPED_POLICY_DENIED` without spawning; already running children are not cancelled by this check.
|
|
61
|
+
|
|
62
|
+
Execution records are `<store.directory>/ce-hooks/executions.jsonl`. The runner ignores child stdout/stderr. Failures, timeouts, queue overflow and shutdown skips do not change delivery, ACK, task completion, or the committed send result. There is no automatic retry, startup replay, or exactly-once guarantee. Do not replay side-effecting scripts after a missing final record or timeout: a notification may already have been written. This example is a notification sink, not a durable task queue or deduplication mechanism.
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Append one metadata notification to an operator-selected private local file."""
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
import stat
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
MAX_INPUT = 16384
|
|
10
|
+
FIELDS = {
|
|
11
|
+
"schemaVersion", "event", "eventId", "eventKey", "messageId", "exchangeId",
|
|
12
|
+
"sender", "recipient", "createdAt", "payloadDigest", "payloadLength",
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def text(value, maximum):
|
|
17
|
+
return (isinstance(value, str) and 0 < len(value) <= maximum
|
|
18
|
+
and not any(ord(char) < 32 or ord(char) == 127 for char in value))
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def unique_object(pairs):
|
|
22
|
+
result = {}
|
|
23
|
+
for key, value in pairs:
|
|
24
|
+
if key in result:
|
|
25
|
+
raise ValueError("duplicate field")
|
|
26
|
+
result[key] = value
|
|
27
|
+
return result
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def main():
|
|
31
|
+
if len(sys.argv) != 2 or not os.path.isabs(sys.argv[1]):
|
|
32
|
+
raise ValueError("absolute output required")
|
|
33
|
+
raw = sys.stdin.buffer.read(MAX_INPUT + 1)
|
|
34
|
+
if len(raw) > MAX_INPUT:
|
|
35
|
+
raise ValueError("input too large")
|
|
36
|
+
try:
|
|
37
|
+
event = json.loads(raw.decode("utf-8"), object_pairs_hook=unique_object)
|
|
38
|
+
except (ValueError, UnicodeError) as error:
|
|
39
|
+
raise ValueError("invalid JSON metadata") from error
|
|
40
|
+
if not isinstance(event, dict) or set(event) != FIELDS:
|
|
41
|
+
raise ValueError("invalid fields")
|
|
42
|
+
if type(event["schemaVersion"]) is not int or event["schemaVersion"] != 1:
|
|
43
|
+
raise ValueError("invalid version")
|
|
44
|
+
if event["event"] != "ce.message.committed.v1":
|
|
45
|
+
raise ValueError("invalid event")
|
|
46
|
+
for field in ("eventId", "eventKey", "messageId", "exchangeId", "createdAt"):
|
|
47
|
+
if not text(event[field], 512):
|
|
48
|
+
raise ValueError("invalid reference")
|
|
49
|
+
for field in ("sender", "recipient"):
|
|
50
|
+
endpoint = event[field]
|
|
51
|
+
if (not isinstance(endpoint, dict) or set(endpoint) != {"adapter", "endpointId"}
|
|
52
|
+
or not text(endpoint["adapter"], 64) or not text(endpoint["endpointId"], 256)):
|
|
53
|
+
raise ValueError("invalid endpoint")
|
|
54
|
+
if not isinstance(event["payloadDigest"], str) or not re.fullmatch(r"[0-9a-f]{64}", event["payloadDigest"]):
|
|
55
|
+
raise ValueError("invalid digest")
|
|
56
|
+
if type(event["payloadLength"]) is not int or not 0 <= event["payloadLength"] <= 9007199254740991:
|
|
57
|
+
raise ValueError("invalid length")
|
|
58
|
+
line = (json.dumps(event, ensure_ascii=True, separators=(",", ":")) + "\n").encode("ascii")
|
|
59
|
+
# The parent directory must be private and operator controlled. Never derive
|
|
60
|
+
# paths from metadata; refuse symlinks, special files and shared output files.
|
|
61
|
+
fd = os.open(sys.argv[1], os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600)
|
|
62
|
+
try:
|
|
63
|
+
info = os.fstat(fd)
|
|
64
|
+
if (not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid()
|
|
65
|
+
or info.st_mode & 0o077 or info.st_nlink != 1):
|
|
66
|
+
raise ValueError("unsafe output")
|
|
67
|
+
with os.fdopen(fd, "ab", closefd=False) as output:
|
|
68
|
+
output.write(line)
|
|
69
|
+
finally:
|
|
70
|
+
os.close(fd)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
if __name__ == "__main__":
|
|
74
|
+
try:
|
|
75
|
+
main()
|
|
76
|
+
except (ValueError, OSError, UnicodeError, RecursionError):
|
|
77
|
+
# Do not echo metadata, paths or interpreter tracebacks to a host stream.
|
|
78
|
+
sys.stderr.write("notification rejected\n")
|
|
79
|
+
sys.exit(1)
|