@zieglar/pi-chat-exchange 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +137 -2
- package/dist/bin/ce-native.js +119 -0
- package/dist/bin/mcp-stdio.js +196 -0
- package/dist/control/debug-log.js +67 -0
- package/dist/control/mcp/debug-transport.js +48 -0
- package/dist/control/mcp/messaging-tools.js +278 -0
- package/dist/control/mcp/ping.js +43 -0
- package/dist/control/mcp/server.js +153 -0
- package/dist/core/authorization.js +32 -0
- package/dist/core/reference.js +32 -0
- package/dist/core/rules.js +468 -0
- package/dist/endpoints/pi/contract.js +2 -0
- package/dist/endpoints/pi/session-host.js +39 -0
- package/dist/host/bound-endpoint.js +176 -0
- package/dist/host/endpoint-host.js +839 -0
- package/dist/host/mcp-binding-config.js +209 -0
- package/dist/host/ownership-recovery.js +257 -0
- package/dist/index.js +11 -0
- package/dist/protocol/capabilities.js +46 -0
- package/dist/protocol/endpoint-capabilities.js +15 -0
- package/dist/protocol/entities.js +185 -0
- package/dist/protocol/formats.js +13 -0
- package/dist/protocol/idempotency.js +93 -0
- package/dist/protocol/identity.js +130 -0
- package/dist/protocol/index.js +8 -0
- package/dist/protocol/lifecycle.js +125 -0
- package/dist/protocol/outcomes.js +55 -0
- package/dist/runtime/desktop-manifest.js +65 -0
- package/dist/runtime/diagnostics.js +34 -0
- package/dist/runtime/executables.js +217 -0
- package/dist/runtime/native-readiness.js +131 -0
- package/dist/storage/capability.js +221 -0
- package/dist/storage/connection.js +95 -0
- package/dist/storage/creation-request.js +176 -0
- package/dist/storage/creation.js +553 -0
- package/dist/storage/current-schema.js +397 -0
- package/dist/storage/delivery-ack.js +177 -0
- package/dist/storage/errors.js +9 -0
- package/dist/storage/filesystem.js +171 -0
- package/dist/storage/inbox-discovery.js +135 -0
- package/dist/storage/messaging.js +156 -0
- package/dist/storage/migration.js +258 -0
- package/dist/storage/native-artifact.js +234 -0
- package/dist/storage/native-compat.js +65 -0
- package/dist/storage/ownership.js +789 -0
- package/dist/storage/participant-identity.js +127 -0
- package/dist/storage/participant.js +700 -0
- package/dist/storage/recovery.js +99 -0
- package/dist/storage/runtime.js +256 -0
- package/dist/storage/schema.js +556 -0
- package/dist/storage/session-state.js +75 -0
- package/dist/storage/sqlite-driver-node.js +66 -0
- package/dist/storage/sqlite-driver-rust.js +121 -0
- package/dist/storage/sqlite-driver-selection.js +86 -0
- package/dist/storage/sqlite-driver.js +4 -0
- package/dist/storage/store.js +450 -0
- package/dist/storage/transaction.js +196 -0
- package/dist/storage/trust-root.js +164 -0
- package/dist/tunnel/background-manager.js +1727 -0
- package/dist/tunnel/codes.js +79 -0
- package/dist/tunnel/health.js +75 -0
- package/dist/tunnel/keychain.js +526 -0
- package/dist/tunnel/managed-binding.js +454 -0
- package/dist/tunnel/manager-panel.js +249 -0
- package/dist/tunnel/manager-ui.js +341 -0
- package/dist/tunnel/manager.js +372 -0
- package/dist/tunnel/messaging-activation-ui.js +85 -0
- package/dist/tunnel/messaging-config.js +246 -0
- package/dist/tunnel/multi-session-admission.js +31 -0
- package/dist/tunnel/multi-session-policy.js +314 -0
- package/dist/tunnel/offline-client.js +104 -0
- package/dist/tunnel/profile.js +319 -0
- package/dist/tunnel/redact.js +9 -0
- package/dist/tunnel/secure-input.js +318 -0
- package/dist/tunnel/session-process-mutex.js +338 -0
- package/dist/tunnel/setup-ui.js +443 -0
- package/dist/tunnel/setup.js +734 -0
- package/dist/tunnel/state.js +127 -0
- package/native/tunnel-keychain.swift +432 -0
- package/package.json +65 -4
- package/pi-extension/allowlist.example.json +11 -0
- package/pi-extension/index.ts +2346 -0
- package/pi-extension/multi-session-commands.ts +93 -0
- package/pi-extension/multi-session-runtime.ts +75 -0
- package/pi-extension/tui-keys.ts +40 -0
- package/scripts/reconcile-session-process-mutex.mjs +262 -0
- package/scripts/recover-stale-ownership.mjs +91 -0
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { assertSecureDatabaseArtifacts, prepareDatabasePath, exclusivelyCreateDatabase, pathStat, withRestrictiveUmask, } from "./filesystem.js";
|
|
2
|
+
import { assertRuntimeEligibility, readRuntimeIdentity, } from "./runtime.js";
|
|
3
|
+
import { resolveSqliteDriver } from "./sqlite-driver-selection.js";
|
|
4
|
+
export const DEFAULT_BUSY_TIMEOUT_MS = 1_000;
|
|
5
|
+
export const MAX_BUSY_TIMEOUT_MS = 5_000;
|
|
6
|
+
export const WAL_AUTOCHECKPOINT_PAGES = 1_000;
|
|
7
|
+
export class ConnectionPolicyError extends Error {
|
|
8
|
+
code = "STORAGE_CONNECTION_POLICY_INVALID";
|
|
9
|
+
constructor(message, options) {
|
|
10
|
+
super(message, options);
|
|
11
|
+
this.name = "ConnectionPolicyError";
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
export function assertStorageRuntimeEligibility(options) {
|
|
15
|
+
assertRuntimeEligibility((options.runtimeIdentity ?? (() => readRuntimeIdentity(options.driver)))());
|
|
16
|
+
}
|
|
17
|
+
function readPragma(db, name) {
|
|
18
|
+
const row = db.prepare(`PRAGMA ${name}`).get();
|
|
19
|
+
return row === undefined ? undefined : Object.values(row)[0];
|
|
20
|
+
}
|
|
21
|
+
function assertPragma(db, name, expected) {
|
|
22
|
+
const actual = readPragma(db, name);
|
|
23
|
+
if (actual !== expected) {
|
|
24
|
+
throw new ConnectionPolicyError(`SQLite refused required PRAGMA ${name}: expected ${String(expected)}, received ${String(actual)}`);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function initializeWriterPolicy(db, busyTimeoutMs) {
|
|
28
|
+
db.enableDefensive(true);
|
|
29
|
+
db.exec(`
|
|
30
|
+
PRAGMA journal_mode=WAL;
|
|
31
|
+
PRAGMA synchronous=FULL;
|
|
32
|
+
PRAGMA foreign_keys=ON;
|
|
33
|
+
PRAGMA recursive_triggers=ON;
|
|
34
|
+
PRAGMA trusted_schema=OFF;
|
|
35
|
+
PRAGMA busy_timeout=${busyTimeoutMs};
|
|
36
|
+
PRAGMA wal_autocheckpoint=${WAL_AUTOCHECKPOINT_PAGES};
|
|
37
|
+
`);
|
|
38
|
+
if (process.platform === "darwin") {
|
|
39
|
+
db.exec("PRAGMA fullfsync=ON; PRAGMA checkpoint_fullfsync=ON;");
|
|
40
|
+
}
|
|
41
|
+
assertPragma(db, "journal_mode", "wal");
|
|
42
|
+
assertPragma(db, "synchronous", 2);
|
|
43
|
+
assertPragma(db, "foreign_keys", 1);
|
|
44
|
+
assertPragma(db, "recursive_triggers", 1);
|
|
45
|
+
assertPragma(db, "trusted_schema", 0);
|
|
46
|
+
assertPragma(db, "busy_timeout", busyTimeoutMs);
|
|
47
|
+
assertPragma(db, "wal_autocheckpoint", WAL_AUTOCHECKPOINT_PAGES);
|
|
48
|
+
if (process.platform === "darwin") {
|
|
49
|
+
assertPragma(db, "fullfsync", 1);
|
|
50
|
+
assertPragma(db, "checkpoint_fullfsync", 1);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
export function openStorageConnection(options, validateExisting, createExclusive = false) {
|
|
54
|
+
const busyTimeoutMs = options.busyTimeoutMs ?? DEFAULT_BUSY_TIMEOUT_MS;
|
|
55
|
+
if (!Number.isSafeInteger(busyTimeoutMs) || busyTimeoutMs < 1 || busyTimeoutMs > MAX_BUSY_TIMEOUT_MS) {
|
|
56
|
+
throw new ConnectionPolicyError(`busy timeout must be an integer from 1 to ${MAX_BUSY_TIMEOUT_MS} milliseconds`);
|
|
57
|
+
}
|
|
58
|
+
assertStorageRuntimeEligibility(options);
|
|
59
|
+
const databasePath = prepareDatabasePath(options);
|
|
60
|
+
assertSecureDatabaseArtifacts(databasePath);
|
|
61
|
+
if (createExclusive || pathStat(databasePath) === undefined) {
|
|
62
|
+
if (validateExisting !== undefined)
|
|
63
|
+
throw new ConnectionPolicyError("existing store disappeared before writer open");
|
|
64
|
+
exclusivelyCreateDatabase(databasePath);
|
|
65
|
+
}
|
|
66
|
+
let db;
|
|
67
|
+
try {
|
|
68
|
+
const driver = options.driver ?? resolveSqliteDriver();
|
|
69
|
+
db = withRestrictiveUmask(() => driver.open(databasePath, { defensive: true, timeout: busyTimeoutMs }));
|
|
70
|
+
// Revalidate identity/compatibility before persistent writer PRAGMAs.
|
|
71
|
+
// A read transaction gives these checks one consistent schema/data snapshot.
|
|
72
|
+
if (validateExisting !== undefined) {
|
|
73
|
+
db.exec("BEGIN");
|
|
74
|
+
try {
|
|
75
|
+
validateExisting(db);
|
|
76
|
+
}
|
|
77
|
+
finally {
|
|
78
|
+
db.exec("ROLLBACK");
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
initializeWriterPolicy(db, busyTimeoutMs);
|
|
82
|
+
assertSecureDatabaseArtifacts(databasePath);
|
|
83
|
+
return db;
|
|
84
|
+
}
|
|
85
|
+
catch (error) {
|
|
86
|
+
if (db !== undefined)
|
|
87
|
+
db.close();
|
|
88
|
+
if (error instanceof ConnectionPolicyError)
|
|
89
|
+
throw error;
|
|
90
|
+
throw new ConnectionPolicyError("failed to establish the required SQLite connection policy", {
|
|
91
|
+
cause: error,
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
//# sourceMappingURL=connection.js.map
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { types } from "node:util";
|
|
3
|
+
import { Value } from "@sinclair/typebox/value";
|
|
4
|
+
import { EndpointRefSchema } from "../protocol/entities.js";
|
|
5
|
+
import { EXCHANGE_ID_PATTERN } from "../protocol/identity.js";
|
|
6
|
+
import { canonicalDigest, IDEMPOTENCY_KEY_MAX_LENGTH, NAMESPACE_MAX_LENGTH } from "../protocol/idempotency.js";
|
|
7
|
+
/** Private host policy in bytes, not a protocol field or Result character limit. */
|
|
8
|
+
export const MAX_CREATION_PAYLOAD_BYTES = 1_048_576;
|
|
9
|
+
export class CreationRequestError extends Error {
|
|
10
|
+
code = "STORAGE_CREATE_REQUEST_INVALID";
|
|
11
|
+
retryable = false;
|
|
12
|
+
constructor(detail) {
|
|
13
|
+
super(`creation request rejected: ${detail}`);
|
|
14
|
+
this.name = "CreationRequestError";
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
// These intrinsic getters cannot be shadowed by properties on the input view.
|
|
18
|
+
// Hostile process-level replacement of intrinsics is not sandboxed.
|
|
19
|
+
const typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);
|
|
20
|
+
const bufferGetter = Object.getOwnPropertyDescriptor(typedArrayPrototype, "buffer").get;
|
|
21
|
+
const byteLengthGetter = Object.getOwnPropertyDescriptor(typedArrayPrototype, "byteLength").get;
|
|
22
|
+
function reject(detail) {
|
|
23
|
+
throw new CreationRequestError(detail);
|
|
24
|
+
}
|
|
25
|
+
/** Capture enumerable own fields once. Never retain arbitrary accessor failures. */
|
|
26
|
+
function capture(input, allowed, required, path) {
|
|
27
|
+
try {
|
|
28
|
+
if (typeof input !== "object" || input === null)
|
|
29
|
+
reject(`${path}: expected object`);
|
|
30
|
+
const prototype = Object.getPrototypeOf(input);
|
|
31
|
+
if (prototype !== Object.prototype && prototype !== null)
|
|
32
|
+
reject(`${path}: expected plain object`);
|
|
33
|
+
const keys = Reflect.ownKeys(input);
|
|
34
|
+
for (const key of keys) {
|
|
35
|
+
if (typeof key !== "string" || !allowed.includes(key))
|
|
36
|
+
reject(`${path}: unknown field`);
|
|
37
|
+
if (!Object.getOwnPropertyDescriptor(input, key)?.enumerable)
|
|
38
|
+
reject(`${path}: non-enumerable field`);
|
|
39
|
+
}
|
|
40
|
+
for (const key of required) {
|
|
41
|
+
if (!keys.includes(key))
|
|
42
|
+
reject(`${path}: missing required field`);
|
|
43
|
+
}
|
|
44
|
+
const result = Object.create(null);
|
|
45
|
+
for (const key of keys)
|
|
46
|
+
result[key] = input[key];
|
|
47
|
+
return result;
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
// Do not inspect or preserve a caller-thrown error, even if it has our class.
|
|
51
|
+
return reject(`${path}: invalid fields or inaccessible input`);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
function text(value, path, maximum, noNul = false) {
|
|
55
|
+
// Unicode mode treats a valid surrogate pair as one non-surrogate code point.
|
|
56
|
+
if (typeof value !== "string" || value.length === 0 || value.length > maximum || /[\uD800-\uDFFF]/u.test(value) || (noNul && value.includes("\u0000"))) {
|
|
57
|
+
reject(`${path}: invalid string`);
|
|
58
|
+
}
|
|
59
|
+
return value;
|
|
60
|
+
}
|
|
61
|
+
function normalizeEndpoint(input, path) {
|
|
62
|
+
const fields = capture(input, ["adapter", "endpointId", "instanceId"], ["adapter", "endpointId"], path);
|
|
63
|
+
const endpoint = {
|
|
64
|
+
adapter: text(fields.adapter, `${path}.adapter`, 64),
|
|
65
|
+
endpointId: text(fields.endpointId, `${path}.endpointId`, 256),
|
|
66
|
+
};
|
|
67
|
+
if (Object.hasOwn(fields, "instanceId")) {
|
|
68
|
+
endpoint.instanceId = text(fields.instanceId, `${path}.instanceId`, 256);
|
|
69
|
+
}
|
|
70
|
+
if (!Value.Check(EndpointRefSchema, endpoint))
|
|
71
|
+
reject(`${path}: invalid endpoint`);
|
|
72
|
+
return Object.freeze(endpoint);
|
|
73
|
+
}
|
|
74
|
+
function copyPayload(input) {
|
|
75
|
+
if (!types.isUint8Array(input))
|
|
76
|
+
reject("payload: expected Uint8Array or Buffer");
|
|
77
|
+
let copied;
|
|
78
|
+
try {
|
|
79
|
+
const buffer = bufferGetter.call(input);
|
|
80
|
+
if (types.isSharedArrayBuffer(buffer))
|
|
81
|
+
reject("payload: shared backing is unsupported");
|
|
82
|
+
// Early refusal avoids a needless oversized allocation. Acceptance still
|
|
83
|
+
// checks the actual copy below. A detached zero-length view fails on copy.
|
|
84
|
+
if (byteLengthGetter.call(input) > MAX_CREATION_PAYLOAD_BYTES)
|
|
85
|
+
reject("payload: byte limit exceeded");
|
|
86
|
+
copied = new Uint8Array(input);
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
return reject("payload: detached, shared, oversized, or inaccessible bytes");
|
|
90
|
+
}
|
|
91
|
+
if (copied.byteLength > MAX_CREATION_PAYLOAD_BYTES)
|
|
92
|
+
reject("payload: byte limit exceeded");
|
|
93
|
+
return copied;
|
|
94
|
+
}
|
|
95
|
+
/** The private snapshot never escapes. S0/S1 exposes no persistence operation.
|
|
96
|
+
* Hash and length are derived only from this independent copy. This guarantees
|
|
97
|
+
* consistency with these bytes, not an atomic snapshot of external mutation. */
|
|
98
|
+
class CapturedMessage {
|
|
99
|
+
#payload;
|
|
100
|
+
namespace;
|
|
101
|
+
idempotencyKey;
|
|
102
|
+
requestDigest;
|
|
103
|
+
exchangeId;
|
|
104
|
+
from;
|
|
105
|
+
to;
|
|
106
|
+
fromEndpointJson;
|
|
107
|
+
toEndpointJson;
|
|
108
|
+
payloadDigest;
|
|
109
|
+
payloadLength;
|
|
110
|
+
constructor(exchangeId, idempotencyKey, from, to, copiedBytes) {
|
|
111
|
+
this.#payload = copiedBytes;
|
|
112
|
+
this.exchangeId = exchangeId;
|
|
113
|
+
this.idempotencyKey = idempotencyKey;
|
|
114
|
+
this.from = from;
|
|
115
|
+
this.to = to;
|
|
116
|
+
this.namespace = JSON.stringify(["message.create", exchangeId]);
|
|
117
|
+
this.fromEndpointJson = JSON.stringify(from);
|
|
118
|
+
this.toEndpointJson = JSON.stringify(to);
|
|
119
|
+
this.payloadLength = this.#payload.byteLength;
|
|
120
|
+
this.payloadDigest = createHash("sha256").update(this.#payload).digest("hex");
|
|
121
|
+
this.requestDigest = canonicalDigest({
|
|
122
|
+
op: "chat-exchange/message.create", v: 1, exchangeId, from, to,
|
|
123
|
+
payloadDigest: this.payloadDigest, payloadLength: this.payloadLength,
|
|
124
|
+
});
|
|
125
|
+
Object.freeze(this);
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Private-field access is the runtime provenance brand: plain lookalikes,
|
|
129
|
+
* prototype-forged objects, Proxy wrappers (revoked or not) and foreign
|
|
130
|
+
* classes all fail here without invoking any caller-controlled trap or
|
|
131
|
+
* getter. Only a fresh independent copy leaves this module.
|
|
132
|
+
*/
|
|
133
|
+
static copyPayloadForPersistence(value) {
|
|
134
|
+
return new Uint8Array(value.#payload);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
/** Trusted-host, private normalization only: no authentication or SQL writes. */
|
|
138
|
+
export function normalizeCreateExchangeRequest(input) {
|
|
139
|
+
const fields = capture(input, ["namespace", "idempotencyKey"], ["namespace", "idempotencyKey"], "request");
|
|
140
|
+
const namespace = text(fields.namespace, "namespace", NAMESPACE_MAX_LENGTH, true);
|
|
141
|
+
const idempotencyKey = text(fields.idempotencyKey, "idempotencyKey", IDEMPOTENCY_KEY_MAX_LENGTH, true);
|
|
142
|
+
return Object.freeze({
|
|
143
|
+
namespace: JSON.stringify(["exchange.create", namespace]),
|
|
144
|
+
idempotencyKey,
|
|
145
|
+
requestDigest: canonicalDigest({ op: "chat-exchange/exchange.create", v: 1 }),
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
/** Does not retain the original request, EndpointRefs, or caller byte storage. */
|
|
149
|
+
export function normalizeCreateMessageRequest(input) {
|
|
150
|
+
const names = ["exchangeId", "from", "to", "payload", "idempotencyKey"];
|
|
151
|
+
const fields = capture(input, names, names, "request");
|
|
152
|
+
const exchangeId = text(fields.exchangeId, "exchangeId", 29);
|
|
153
|
+
if (!EXCHANGE_ID_PATTERN.test(exchangeId))
|
|
154
|
+
reject("exchangeId: invalid identity");
|
|
155
|
+
const idempotencyKey = text(fields.idempotencyKey, "idempotencyKey", IDEMPOTENCY_KEY_MAX_LENGTH, true);
|
|
156
|
+
const from = normalizeEndpoint(fields.from, "from");
|
|
157
|
+
const to = normalizeEndpoint(fields.to, "to");
|
|
158
|
+
const copiedBytes = copyPayload(fields.payload);
|
|
159
|
+
return new CapturedMessage(exchangeId, idempotencyKey, from, to, copiedBytes);
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Package-private persistence bridge for the durable storage writer only.
|
|
163
|
+
* Never exported through a public barrel and never given SQLite knowledge.
|
|
164
|
+
* The caller receives a one-use fresh copy; the authoritative snapshot and the
|
|
165
|
+
* original caller bytes are never returned, reread, or otherwise exposed.
|
|
166
|
+
*/
|
|
167
|
+
export function copyCapturedMessagePayloadForPersistence(normalized) {
|
|
168
|
+
try {
|
|
169
|
+
return CapturedMessage.copyPayloadForPersistence(normalized);
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
// Provenance and allocation failures are indistinguishable to the caller.
|
|
173
|
+
return reject("payload: unrecognized normalized request provenance");
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
//# sourceMappingURL=creation-request.js.map
|