@peer2peer/cli 0.0.0-stage → 0.1.0
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 +201 -0
- package/README.md +366 -2
- package/dist/ancestry.d.ts +13 -0
- package/dist/ancestry.js +71 -0
- package/dist/app.d.ts +363 -0
- package/dist/app.js +1177 -0
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +56 -0
- package/dist/circle-ops.d.ts +402 -0
- package/dist/circle-ops.js +1725 -0
- package/dist/cli.d.ts +611 -0
- package/dist/cli.js +1650 -0
- package/dist/codes.d.ts +231 -0
- package/dist/codes.js +998 -0
- package/dist/config.d.ts +112 -0
- package/dist/config.js +243 -0
- package/dist/doctor.d.ts +99 -0
- package/dist/doctor.js +817 -0
- package/dist/errors.d.ts +8 -0
- package/dist/errors.js +29 -0
- package/dist/ext-host.d.ts +32 -0
- package/dist/ext-host.js +259 -0
- package/dist/extensions.d.ts +386 -0
- package/dist/extensions.js +395 -0
- package/dist/features.d.ts +91 -0
- package/dist/features.js +164 -0
- package/dist/format.d.ts +57 -0
- package/dist/format.js +248 -0
- package/dist/identity.d.ts +236 -0
- package/dist/identity.js +751 -0
- package/dist/inbound.d.ts +32 -0
- package/dist/inbound.js +258 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +14 -0
- package/dist/join-answers.d.ts +49 -0
- package/dist/join-answers.js +149 -0
- package/dist/outbox.d.ts +109 -0
- package/dist/outbox.js +337 -0
- package/dist/pretty.d.ts +100 -0
- package/dist/pretty.js +256 -0
- package/dist/procstart.d.ts +1 -0
- package/dist/procstart.js +66 -0
- package/dist/progress.d.ts +30 -0
- package/dist/progress.js +78 -0
- package/dist/projects.d.ts +240 -0
- package/dist/projects.js +699 -0
- package/dist/prompt/picker.d.ts +64 -0
- package/dist/prompt/picker.js +152 -0
- package/dist/prompt/tty.d.ts +29 -0
- package/dist/prompt/tty.js +122 -0
- package/dist/readonly.d.ts +20 -0
- package/dist/readonly.js +50 -0
- package/dist/receipts.d.ts +99 -0
- package/dist/receipts.js +180 -0
- package/dist/relay-client.d.ts +277 -0
- package/dist/relay-client.js +873 -0
- package/dist/relay-info.d.ts +24 -0
- package/dist/relay-info.js +53 -0
- package/dist/rotation.d.ts +402 -0
- package/dist/rotation.js +2054 -0
- package/dist/running.d.ts +5 -0
- package/dist/running.js +74 -0
- package/dist/sessions.d.ts +340 -0
- package/dist/sessions.js +1152 -0
- package/dist/shortcode.d.ts +149 -0
- package/dist/shortcode.js +465 -0
- package/dist/social.d.ts +139 -0
- package/dist/social.js +485 -0
- package/dist/state.d.ts +483 -0
- package/dist/state.js +217 -0
- package/dist/stdin.d.ts +17 -0
- package/dist/stdin.js +46 -0
- package/dist/sync.d.ts +77 -0
- package/dist/sync.js +375 -0
- package/dist/transient.d.ts +1 -0
- package/dist/transient.js +28 -0
- package/dist/trust.d.ts +37 -0
- package/dist/trust.js +134 -0
- package/dist/tty-confirm.d.ts +2 -0
- package/dist/tty-confirm.js +53 -0
- package/dist/tui/command.d.ts +20 -0
- package/dist/tui/command.js +70 -0
- package/dist/tui/frame.d.ts +43 -0
- package/dist/tui/frame.js +111 -0
- package/dist/tui/model.d.ts +215 -0
- package/dist/tui/model.js +255 -0
- package/dist/tui/sanitize.d.ts +13 -0
- package/dist/tui/sanitize.js +151 -0
- package/dist/tui/terminal.d.ts +88 -0
- package/dist/tui/terminal.js +354 -0
- package/dist/tui/tui.d.ts +71 -0
- package/dist/tui/tui.js +571 -0
- package/dist/tui/view.d.ts +4 -0
- package/dist/tui/view.js +356 -0
- package/dist/unknown-kinds.d.ts +12 -0
- package/dist/unknown-kinds.js +66 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +5 -0
- package/dist/want-pow.d.ts +12 -0
- package/dist/want-pow.js +46 -0
- package/dist/watch.d.ts +35 -0
- package/dist/watch.js +325 -0
- package/dist/xstate.d.ts +125 -0
- package/dist/xstate.js +422 -0
- package/package.json +60 -4
package/dist/xstate.js
ADDED
|
@@ -0,0 +1,422 @@
|
|
|
1
|
+
// Copyright 2026 Ix Infrastructure Inc.
|
|
2
|
+
//
|
|
3
|
+
// Extension state kinds (docs/protocol.md §4.3 "Extension state kinds", cap
|
|
4
|
+
// xstate.v1; footprint P2). An extension declares some of its kinds as state
|
|
5
|
+
// (P2PExtension.state): a session's latest value of such a kind, such as an
|
|
6
|
+
// Ix footprint, rather than an event.
|
|
7
|
+
//
|
|
8
|
+
// - Sending (`publishExtensionState`, ExtContext.publish): to the session's
|
|
9
|
+
// status audience (§4.2, as `p2p status`), never to one target. Gated per
|
|
10
|
+
// recipient: a user gets it only when every live session of theirs we know
|
|
11
|
+
// of advertises xstate.v1, and then only on the devices those sessions run
|
|
12
|
+
// on. A device with no live session, or an older client, never gets one.
|
|
13
|
+
// The plaintext carries `state: {ttl}`. A sender updates one kind of one
|
|
14
|
+
// session at most every EXT_STATE_MIN_INTERVAL_MS (`rate_limited`).
|
|
15
|
+
// - Receiving (`onStateEnvelope`): only from the session's owner. Latest wins
|
|
16
|
+
// per (sender, session, kind), replacing what was stored, after the
|
|
17
|
+
// extension (when installed) validated it. Never an event: not logged, not
|
|
18
|
+
// printed by `watch`, never toasted or shown to a model. Size-capped, rate
|
|
19
|
+
// limited (by the envelopes' own spacing and per (sender, session)),
|
|
20
|
+
// bounded per session, per sender (count and charged size) and in total,
|
|
21
|
+
// where the biggest holder is evicted first. A kind the owning extension
|
|
22
|
+
// doesn't declare as state keeps only its fallback.
|
|
23
|
+
// - Reading (`liveStates`): only for live sessions (§4.3, 150 s) and within
|
|
24
|
+
// the value's ttl. `ls --json` gets a bounded summary (no bodies);
|
|
25
|
+
// ExtContext gets an extension's own kinds' kept bodies.
|
|
26
|
+
import { EXT_STATE_MAX_BYTES, EXT_STATE_MIN_INTERVAL_MS, EXT_STATE_TTL_DEFAULT, extensionKindCap, FALLBACK_MAX, isExtensionKind, isExtStateTtl, isLive, sanitizePeerText, STATUS_CAP_XSTATE, STATUS_LIVE_MS, } from "@peer2peer/core/v3";
|
|
27
|
+
import { createHash } from "node:crypto";
|
|
28
|
+
import { CliError } from "./errors.js";
|
|
29
|
+
import { MAX_RENDERED_BYTES, renderExtension } from "./extensions.js";
|
|
30
|
+
import { bindFromEnv, checkSid, getSession, rosterAudience, sessionRef } from "./sessions.js";
|
|
31
|
+
import { supportsIn } from "./features.js";
|
|
32
|
+
import { sessKey } from "./state.js";
|
|
33
|
+
/** At most this many state kinds stored per session; a new kind beyond it is dropped. */
|
|
34
|
+
export const XSTATE_KINDS_PER_SESSION = 8;
|
|
35
|
+
/** At most this many values kept per sender (all their sessions); their oldest go first. */
|
|
36
|
+
export const XSTATE_VALUES_PER_USER = 64;
|
|
37
|
+
/** At most this much kept per sender, counted with xstateCost(); their oldest values go first. */
|
|
38
|
+
export const XSTATE_BYTES_PER_USER = 64 * 1024;
|
|
39
|
+
/** What every value is charged at least (a tiny value still costs a record), plus its strings and XSTATE_OVERHEAD. */
|
|
40
|
+
export const XSTATE_MIN_COST = 1024;
|
|
41
|
+
export const XSTATE_OVERHEAD = 128;
|
|
42
|
+
/**
|
|
43
|
+
* At most this many values kept in all. Over it, the sender holding the most
|
|
44
|
+
* loses their oldest value first (never another sender's by age), so one
|
|
45
|
+
* sender can't evict everyone else's state.
|
|
46
|
+
*/
|
|
47
|
+
export const XSTATE_MAX_RECORDS = 512;
|
|
48
|
+
/** Updates accepted per minute for one (sender, session), all its kinds; the rest are dropped (flood guard). */
|
|
49
|
+
export const XSTATE_UPDATES_PER_MIN = 120;
|
|
50
|
+
/** ...and for one sender across all their sessions (session ids are free to make up). */
|
|
51
|
+
export const XSTATE_SENDER_UPDATES_PER_MIN = 240;
|
|
52
|
+
/** At most this many per-session rate windows kept per sender; the oldest go first. */
|
|
53
|
+
export const XSTATE_RATE_WINDOWS_MAX = 128;
|
|
54
|
+
/** A receiver drops an update this much sooner than EXT_STATE_MIN_INTERVAL_MS after the last (clock jitter). */
|
|
55
|
+
export const XSTATE_SPACING_SLACK_MS = 1_000;
|
|
56
|
+
/** `ls --json`: at most this many state summaries per row. */
|
|
57
|
+
export const XSTATE_LS_MAX = 8;
|
|
58
|
+
/** What a stored value is charged against its sender's XSTATE_BYTES_PER_USER. */
|
|
59
|
+
export function xstateCost(r) {
|
|
60
|
+
return Math.max(r.bytes, XSTATE_MIN_COST) + Buffer.byteLength(r.fallback, "utf8") + r.kind.length + r.sid.length + XSTATE_OVERHEAD;
|
|
61
|
+
}
|
|
62
|
+
/** Within a sender's document: one value per (sid, kind). */
|
|
63
|
+
const valueKey = (sid, kind) => `${sid}|${kind}`;
|
|
64
|
+
/** Each sender's values live in a document of their own (`xstate-<16 hex of sha256(userId)>`); `xstate` is the small index. */
|
|
65
|
+
export const senderDoc = (own) => `xstate-${createHash("sha256").update(own).digest("hex").slice(0, 16)}`;
|
|
66
|
+
/** The kinds the loaded extensions declare as state, with their declared ttl. */
|
|
67
|
+
export function declaredState(reg, kind) {
|
|
68
|
+
const ext = reg?.forKind(kind);
|
|
69
|
+
const d = ext?.state?.[kind];
|
|
70
|
+
if (!d)
|
|
71
|
+
return undefined;
|
|
72
|
+
return { ttl: isExtStateTtl(d.ttl) ? d.ttl : EXT_STATE_TTL_DEFAULT };
|
|
73
|
+
}
|
|
74
|
+
/** The caps this client advertises for state kinds: `<kind>.v1` for each one a loaded extension declares. */
|
|
75
|
+
export function stateKindCaps(reg) {
|
|
76
|
+
const out = [];
|
|
77
|
+
for (const { ext } of reg?.list() ?? []) {
|
|
78
|
+
for (const kind of Object.keys(ext.state ?? {})) {
|
|
79
|
+
const cap = extensionKindCap(kind);
|
|
80
|
+
if (cap && !out.includes(cap))
|
|
81
|
+
out.push(cap);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return out;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* The devices of `u` that get a state kind: none unless every live session of
|
|
88
|
+
* theirs we know of (other than this device's own) advertises xstate.v1 (the
|
|
89
|
+
* agents.v1 rule), and then only the devices those sessions run on.
|
|
90
|
+
*/
|
|
91
|
+
export function stateDevices(peers, u, self, now = Date.now()) {
|
|
92
|
+
if (!supportsIn({ peers, self, now }, u, { all: true }, STATUS_CAP_XSTATE))
|
|
93
|
+
return [];
|
|
94
|
+
const live = Object.values(peers).filter((p) => p.own === u && isLive(p.ts, now) && !(p.own === self.userId && p.did === self.did));
|
|
95
|
+
return [...new Set(live.map((p) => p.did))];
|
|
96
|
+
}
|
|
97
|
+
export async function publishExtensionState(app, o) {
|
|
98
|
+
const sid = checkSid(o.fromSession, "--from-session");
|
|
99
|
+
if (!isExtensionKind(o.kind))
|
|
100
|
+
throw new CliError("usage", `${o.kind} is not an extension kind (x:<ns>.<type>)`);
|
|
101
|
+
if (!Number.isSafeInteger(o.v) || o.v < 0)
|
|
102
|
+
throw new CliError("usage", "ext.v must be a non-negative integer");
|
|
103
|
+
if (typeof o.fallback !== "string" || o.fallback.trim() === "" || [...o.fallback].length > FALLBACK_MAX) {
|
|
104
|
+
throw new CliError("usage", `a state kind needs a plain-text fallback of 1-${FALLBACK_MAX} characters (§8.1)`);
|
|
105
|
+
}
|
|
106
|
+
const ttl = o.ttl ?? EXT_STATE_TTL_DEFAULT;
|
|
107
|
+
if (!isExtStateTtl(ttl))
|
|
108
|
+
throw new CliError("usage", "a state kind's ttl is an integer of 10-3600 seconds");
|
|
109
|
+
const ext = { v: o.v, body: o.body };
|
|
110
|
+
const json = JSON.stringify(ext);
|
|
111
|
+
if (json === undefined)
|
|
112
|
+
throw new CliError("usage", "the state body must be JSON");
|
|
113
|
+
const bytes = Buffer.byteLength(json, "utf8");
|
|
114
|
+
if (bytes > EXT_STATE_MAX_BYTES)
|
|
115
|
+
throw new CliError("too_large", `the state body is ${bytes} bytes; at most ${EXT_STATE_MAX_BYTES}`);
|
|
116
|
+
// The sender's own rate limit: one update of a kind per session every EXT_STATE_MIN_INTERVAL_MS.
|
|
117
|
+
const now = Date.now();
|
|
118
|
+
const slot = `${sid}|${o.kind}`;
|
|
119
|
+
const wait = await app.state.update("xstateSent", (cur = {}) => {
|
|
120
|
+
const last = cur[slot] ?? 0;
|
|
121
|
+
if (now - last < EXT_STATE_MIN_INTERVAL_MS && last <= now)
|
|
122
|
+
return { result: EXT_STATE_MIN_INTERVAL_MS - (now - last) };
|
|
123
|
+
const next = {};
|
|
124
|
+
// Forget slots older than a day.
|
|
125
|
+
for (const [k, t] of Object.entries(cur))
|
|
126
|
+
if (now - t < 86_400_000)
|
|
127
|
+
next[k] = t;
|
|
128
|
+
next[slot] = now;
|
|
129
|
+
return { next, result: 0 };
|
|
130
|
+
});
|
|
131
|
+
if (wait > 0)
|
|
132
|
+
throw new CliError("rate_limited", `${o.kind} for session ${sid} was published less than ${EXT_STATE_MIN_INTERVAL_MS / 1000} s ago; try again in ${Math.ceil(wait / 1000)} s`, { retryAfterMs: wait });
|
|
133
|
+
// Bound like a status (projects.ts): the session's projects decide who its state reaches.
|
|
134
|
+
await bindFromEnv(app, sid);
|
|
135
|
+
await app.connectAndDrain();
|
|
136
|
+
const sess = await getSession(app, sid);
|
|
137
|
+
const audience = await rosterAudience(app, sess);
|
|
138
|
+
const peers = (await app.state.get("peers")) ?? {};
|
|
139
|
+
const plaintext = { ext, fallback: o.fallback, roster: sess.jws, state: { ttl } };
|
|
140
|
+
const result = { kind: o.kind, bytes, ttl, delivered: [], skipped: [], failed: [] };
|
|
141
|
+
for (const u of [...audience, app.userId]) {
|
|
142
|
+
if (u === app.userId) {
|
|
143
|
+
const v = await app.view(app.userId);
|
|
144
|
+
if (!v || !v.devices.some((d) => d !== app.did))
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
const address = await app.addressOf(u);
|
|
148
|
+
const devices = stateDevices(peers, u, { userId: app.userId, did: app.did });
|
|
149
|
+
if (devices.length === 0) {
|
|
150
|
+
result.skipped.push({ userId: u, address, reason: `no live session that advertises ${STATUS_CAP_XSTATE}` });
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
try {
|
|
154
|
+
const d = await app.deliver(u, o.kind, { own: app.userId, sid }, plaintext, { onlyDevices: devices });
|
|
155
|
+
if (d.relays.length > 0)
|
|
156
|
+
result.delivered.push({ userId: u, address, relays: d.relays.length, devices: d.devices });
|
|
157
|
+
else
|
|
158
|
+
result.failed.push({ userId: u, address, error: "delivered via 0 relays" });
|
|
159
|
+
}
|
|
160
|
+
catch (e) {
|
|
161
|
+
result.failed.push({ userId: u, address, error: e.message });
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
// This device keeps its own latest value too (its own `ls`, ExtContext.peerState).
|
|
165
|
+
const own = keepFor(app.extensions, o.kind, o.v, o.body, o.fallback, { userId: app.userId, address: await app.addressOf(app.userId), self: true }, { own: app.userId, sid, ref: sessionRef(app.userId, sid) }, ttl);
|
|
166
|
+
await store(app, { own: app.userId, sid, did: app.did, kind: o.kind, ts: now, at: now, ttl, v: o.v, fallback: sanitizePeerText(o.fallback, FALLBACK_MAX), bytes, ...own, self: true });
|
|
167
|
+
return result;
|
|
168
|
+
}
|
|
169
|
+
/** Whether an inbound extension kind is a state kind: it says so, or a loaded extension declares it. */
|
|
170
|
+
export function isStateEnvelope(reg, pt) {
|
|
171
|
+
return pt.state !== undefined || declaredState(reg, pt.kind) !== undefined;
|
|
172
|
+
}
|
|
173
|
+
/** Validates and keeps the body through the extension; nothing kept when there is none, or it refuses. */
|
|
174
|
+
function keepFor(reg, kind, v, body, fallback, from, session, ttl) {
|
|
175
|
+
const r = renderExtension(reg, { kind, v, body, fallback, from, session, state: { ttl } });
|
|
176
|
+
if (r.extError)
|
|
177
|
+
return { extError: r.extError };
|
|
178
|
+
if (r.kept === undefined)
|
|
179
|
+
return {};
|
|
180
|
+
const s = JSON.stringify(r.kept.body);
|
|
181
|
+
// The kept value is held to the state cap too (an extension can't grow what it keeps).
|
|
182
|
+
if (s === undefined || Buffer.byteLength(s, "utf8") > EXT_STATE_MAX_BYTES)
|
|
183
|
+
return { extError: "the kept state was too large" };
|
|
184
|
+
return { body: r.kept.body };
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* An inbound state kind: stored (latest wins) or dropped, never an event.
|
|
188
|
+
* Only the session's owner publishes its state.
|
|
189
|
+
*/
|
|
190
|
+
/** `now` is the receiver's clock (its rate windows and arrival time); tests pass a fixed one. */
|
|
191
|
+
export async function onStateEnvelope(app, r, pt, from, now = Date.now()) {
|
|
192
|
+
const e = r.envelope;
|
|
193
|
+
const debug = (why) => {
|
|
194
|
+
if (app.env.P2P_DEBUG === "1")
|
|
195
|
+
app.io.err(`p2p: dropped ${sanitizePeerText(pt.kind, 60)} from ${sanitizePeerText(from.address, 80)}: ${why}`);
|
|
196
|
+
};
|
|
197
|
+
if (e.from !== e.own) {
|
|
198
|
+
debug("only a session's owner publishes its state");
|
|
199
|
+
return "not-owner";
|
|
200
|
+
}
|
|
201
|
+
const bytes = Buffer.byteLength(JSON.stringify(pt.ext) ?? "", "utf8");
|
|
202
|
+
if (bytes > EXT_STATE_MAX_BYTES) {
|
|
203
|
+
debug(`${bytes} bytes; at most ${EXT_STATE_MAX_BYTES}`);
|
|
204
|
+
return "too-large";
|
|
205
|
+
}
|
|
206
|
+
const ttl = pt.state?.ttl ?? declaredState(app.extensions, pt.kind)?.ttl ?? EXT_STATE_TTL_DEFAULT;
|
|
207
|
+
const ref = sessionRef(e.own, e.sid);
|
|
208
|
+
// L1: an extension that owns the namespace but doesn't declare this kind as state never sees it as
|
|
209
|
+
// one: only the fallback is kept.
|
|
210
|
+
const owner = app.extensions?.forKind(pt.kind);
|
|
211
|
+
const kept = owner && !declaredState(app.extensions, pt.kind) ? { extError: `${pt.kind} isn't a state kind of ${owner.name}` } : keepFor(app.extensions, pt.kind, pt.ext.v, pt.ext.body, pt.fallback, from, { own: e.own, sid: e.sid, ref }, ttl);
|
|
212
|
+
const verdict = await store(app, { own: e.own, sid: e.sid, did: e.fdid, kind: pt.kind, ts: e.ts, at: now, ttl, v: pt.ext.v, fallback: sanitizePeerText(pt.fallback, FALLBACK_MAX), bytes, ...kept, ...(from.self ? { self: true } : {}) });
|
|
213
|
+
if (verdict !== "stored")
|
|
214
|
+
debug(verdict);
|
|
215
|
+
return verdict;
|
|
216
|
+
}
|
|
217
|
+
const emptyIndex = () => ({ v: 2, users: {} });
|
|
218
|
+
export function asIndex(v) {
|
|
219
|
+
const x = v;
|
|
220
|
+
return x && x.v === 2 && typeof x.users === "object" && x.users !== null ? x : emptyIndex();
|
|
221
|
+
}
|
|
222
|
+
function asSenderDoc(v, own) {
|
|
223
|
+
const x = v;
|
|
224
|
+
return x && x.own === own && typeof x.recs === "object" && x.recs !== null
|
|
225
|
+
? { own, recs: { ...x.recs }, rate: { ...(x.rate ?? {}) }, ...(x.all ? { all: x.all } : {}) }
|
|
226
|
+
: { own, recs: {}, rate: {} };
|
|
227
|
+
}
|
|
228
|
+
/** Rate windows still open at `now`: stale ones dropped, at most XSTATE_RATE_WINDOWS_MAX (the oldest go first). */
|
|
229
|
+
function liveWindows(rate, now) {
|
|
230
|
+
const open = Object.entries(rate)
|
|
231
|
+
.filter(([, w]) => now - w.start < 60_000)
|
|
232
|
+
.sort((a, b) => b[1].start - a[1].start)
|
|
233
|
+
.slice(0, XSTATE_RATE_WINDOWS_MAX);
|
|
234
|
+
return Object.fromEntries(open);
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Writes a sender's document with its rate windows pruned. Once it holds no
|
|
238
|
+
* values and no open rate window it is deleted (N2): a window still open is
|
|
239
|
+
* kept for its minute, or deleting it would reset a flooding sender's limit.
|
|
240
|
+
* False when the document is gone.
|
|
241
|
+
*/
|
|
242
|
+
async function writeSender(backend, name, doc, now) {
|
|
243
|
+
const rate = liveWindows(doc.rate, now);
|
|
244
|
+
const all = doc.all && now - doc.all.start < 60_000 ? doc.all : undefined;
|
|
245
|
+
if (Object.keys(doc.recs).length === 0 && Object.keys(rate).length === 0 && !all && backend.remove) {
|
|
246
|
+
await backend.remove(name);
|
|
247
|
+
return false;
|
|
248
|
+
}
|
|
249
|
+
await backend.write(name, { own: doc.own, recs: doc.recs, rate, ...(all ? { all } : {}) });
|
|
250
|
+
return true;
|
|
251
|
+
}
|
|
252
|
+
/** Backends whose index was reconciled with the sender documents in this process (N3). */
|
|
253
|
+
const reconciled = new WeakSet();
|
|
254
|
+
/**
|
|
255
|
+
* The index with each sender's totals recomputed from their document (N3);
|
|
256
|
+
* senders whose document is gone are dropped, and an empty document whose
|
|
257
|
+
* rate windows have closed is deleted.
|
|
258
|
+
*/
|
|
259
|
+
async function reconcile(backend, index, now) {
|
|
260
|
+
const users = {};
|
|
261
|
+
for (const [own, u] of Object.entries(index.users)) {
|
|
262
|
+
const raw = await backend.read(u.doc);
|
|
263
|
+
if (raw === undefined)
|
|
264
|
+
continue;
|
|
265
|
+
const doc = asSenderDoc(raw, own);
|
|
266
|
+
if (await writeSender(backend, u.doc, doc, now))
|
|
267
|
+
users[own] = { doc: u.doc, ...summarize(doc.recs) };
|
|
268
|
+
}
|
|
269
|
+
if (JSON.stringify(users) !== JSON.stringify(index.users))
|
|
270
|
+
await backend.write("xstate", { v: 2, users });
|
|
271
|
+
return { v: 2, users };
|
|
272
|
+
}
|
|
273
|
+
/** Drops a sender's oldest values (never `keep`) until they hold at most `max` values and `budget` cost. */
|
|
274
|
+
function trimSender(recs, max, budget, keep) {
|
|
275
|
+
const order = Object.entries(recs)
|
|
276
|
+
.filter(([k]) => k !== keep)
|
|
277
|
+
.sort((a, b) => a[1].at - b[1].at);
|
|
278
|
+
let n = Object.keys(recs).length;
|
|
279
|
+
let cost = Object.values(recs).reduce((t, r) => t + xstateCost(r), 0);
|
|
280
|
+
for (const [k, r] of order) {
|
|
281
|
+
if (n <= max && cost <= budget)
|
|
282
|
+
break;
|
|
283
|
+
delete recs[k];
|
|
284
|
+
n--;
|
|
285
|
+
cost -= xstateCost(r);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
const summarize = (recs) => ({ n: Object.keys(recs).length, cost: Object.values(recs).reduce((t, r) => t + xstateCost(r), 0) });
|
|
289
|
+
/**
|
|
290
|
+
* Writes one value under the state lock: latest wins, within every bound;
|
|
291
|
+
* prunes what is dead. Only the sender's own document is rewritten, plus the
|
|
292
|
+
* small index when their totals change (and, over the global cap, the
|
|
293
|
+
* documents of the senders holding the most).
|
|
294
|
+
*/
|
|
295
|
+
async function store(app, rec) {
|
|
296
|
+
const peers = (await app.state.get("peers")) ?? {};
|
|
297
|
+
const backend = app.state.backend;
|
|
298
|
+
return backend.withLock(async () => {
|
|
299
|
+
const now = rec.at;
|
|
300
|
+
let index = asIndex(await backend.read("xstate"));
|
|
301
|
+
if (!reconciled.has(backend)) {
|
|
302
|
+
index = await reconcile(backend, index, now);
|
|
303
|
+
reconciled.add(backend);
|
|
304
|
+
}
|
|
305
|
+
const name = senderDoc(rec.own);
|
|
306
|
+
const doc = asSenderDoc(await backend.read(name), rec.own);
|
|
307
|
+
const key = valueKey(rec.sid, rec.kind);
|
|
308
|
+
const recs = prune(doc.recs, peers, now);
|
|
309
|
+
const old = recs[key];
|
|
310
|
+
if (old && old.ts >= rec.ts)
|
|
311
|
+
return "older";
|
|
312
|
+
if (old && !rec.self && rec.ts - old.ts < EXT_STATE_MIN_INTERVAL_MS - XSTATE_SPACING_SLACK_MS)
|
|
313
|
+
return "rate-limited";
|
|
314
|
+
if (!old && Object.values(recs).filter((x) => x.sid === rec.sid).length >= XSTATE_KINDS_PER_SESSION)
|
|
315
|
+
return "too-many-kinds";
|
|
316
|
+
// Per (sender, session) at most XSTATE_UPDATES_PER_MIN, and per sender at most
|
|
317
|
+
// XSTATE_SENDER_UPDATES_PER_MIN, accepted a minute (this device's own aren't counted).
|
|
318
|
+
doc.rate = liveWindows(doc.rate, now);
|
|
319
|
+
if (!rec.self) {
|
|
320
|
+
const all = doc.all && now - doc.all.start < 60_000 ? doc.all : { start: now, n: 0 };
|
|
321
|
+
const w = doc.rate[rec.sid] ?? { start: now, n: 0 };
|
|
322
|
+
if (w.n >= XSTATE_UPDATES_PER_MIN || all.n >= XSTATE_SENDER_UPDATES_PER_MIN) {
|
|
323
|
+
await writeSender(backend, name, { ...doc, recs }, now);
|
|
324
|
+
return "flood";
|
|
325
|
+
}
|
|
326
|
+
doc.rate[rec.sid] = { start: w.start, n: w.n + 1 };
|
|
327
|
+
doc.all = { start: all.start, n: all.n + 1 };
|
|
328
|
+
}
|
|
329
|
+
recs[key] = rec;
|
|
330
|
+
// Per sender: at most XSTATE_VALUES_PER_USER values and XSTATE_BYTES_PER_USER of cost, their oldest first.
|
|
331
|
+
trimSender(recs, XSTATE_VALUES_PER_USER, XSTATE_BYTES_PER_USER, key);
|
|
332
|
+
const users = { ...index.users, [rec.own]: { doc: name, ...summarize(recs) } };
|
|
333
|
+
// A new sender is in the index before their document exists (N3: no document the index doesn't know).
|
|
334
|
+
if (!index.users[rec.own])
|
|
335
|
+
await backend.write("xstate", { v: 2, users });
|
|
336
|
+
await writeSender(backend, name, { ...doc, recs }, now);
|
|
337
|
+
const gone = new Set();
|
|
338
|
+
// In all: over XSTATE_MAX_RECORDS, the sender holding the most gives up their oldest value first.
|
|
339
|
+
let total = Object.values(users).reduce((t, u) => t + u.n, 0);
|
|
340
|
+
while (total > XSTATE_MAX_RECORDS) {
|
|
341
|
+
// The sender holding the most (then the most cost) that has a value to give up; the new value never goes.
|
|
342
|
+
let evicted = false;
|
|
343
|
+
for (const [own, u] of Object.entries(users).sort((x, y) => y[1].n - x[1].n || y[1].cost - x[1].cost)) {
|
|
344
|
+
const theirs = own === rec.own ? doc : asSenderDoc(await backend.read(u.doc), own);
|
|
345
|
+
const live = own === rec.own ? recs : prune(theirs.recs, peers, now);
|
|
346
|
+
const victim = Object.entries(live)
|
|
347
|
+
.filter(([k]) => !(own === rec.own && k === key))
|
|
348
|
+
.sort((x, y) => x[1].at - y[1].at)[0];
|
|
349
|
+
if (!victim && Object.keys(live).length === u.n)
|
|
350
|
+
continue;
|
|
351
|
+
if (victim)
|
|
352
|
+
delete live[victim[0]];
|
|
353
|
+
if (!(await writeSender(backend, u.doc, { ...theirs, recs: live }, now)))
|
|
354
|
+
gone.add(own);
|
|
355
|
+
users[own] = { doc: u.doc, ...summarize(live) };
|
|
356
|
+
evicted = true;
|
|
357
|
+
break;
|
|
358
|
+
}
|
|
359
|
+
if (!evicted)
|
|
360
|
+
break;
|
|
361
|
+
total = Object.values(users).reduce((t, u) => t + u.n, 0);
|
|
362
|
+
}
|
|
363
|
+
// A sender stays indexed while their document exists (an empty one keeps an open rate window).
|
|
364
|
+
for (const own of gone)
|
|
365
|
+
delete users[own];
|
|
366
|
+
if (JSON.stringify(users) !== JSON.stringify(index.users))
|
|
367
|
+
await backend.write("xstate", { v: 2, users });
|
|
368
|
+
return "stored";
|
|
369
|
+
});
|
|
370
|
+
}
|
|
371
|
+
/** Expiry: the ttl from the earlier of the envelope's ts and arrival (a ts set ahead can't stretch it). */
|
|
372
|
+
export function expiresAt(rec) {
|
|
373
|
+
return Math.min(rec.ts, rec.at) + rec.ttl * 1000;
|
|
374
|
+
}
|
|
375
|
+
/** Without the values that expired, or whose session isn't live (and wasn't heard from in the last 150 s). */
|
|
376
|
+
function prune(recs, peers, now) {
|
|
377
|
+
const out = {};
|
|
378
|
+
for (const [k, r] of Object.entries(recs)) {
|
|
379
|
+
if (now >= expiresAt(r))
|
|
380
|
+
continue;
|
|
381
|
+
// A value may arrive before its session's status: kept for a status's lifetime meanwhile.
|
|
382
|
+
if (!isLive(peers[sessKey(r.own, r.sid)]?.ts, now) && now - r.at > STATUS_LIVE_MS)
|
|
383
|
+
continue;
|
|
384
|
+
out[k] = r;
|
|
385
|
+
}
|
|
386
|
+
return out;
|
|
387
|
+
}
|
|
388
|
+
// ---------------------------------------------------------------------------
|
|
389
|
+
// Reading
|
|
390
|
+
/** The stored values of live sessions, within their ttl; optionally of one kind, or one namespace. */
|
|
391
|
+
export async function liveStates(app, filter = {}, now = Date.now()) {
|
|
392
|
+
const index = asIndex(await app.state.backend.read("xstate"));
|
|
393
|
+
const peers = (await app.state.get("peers")) ?? {};
|
|
394
|
+
const out = [];
|
|
395
|
+
for (const [own, u] of Object.entries(index.users)) {
|
|
396
|
+
const doc = asSenderDoc(await app.state.backend.read(u.doc), own);
|
|
397
|
+
for (const r of Object.values(doc.recs)) {
|
|
398
|
+
if (r.own === own &&
|
|
399
|
+
now < expiresAt(r) &&
|
|
400
|
+
isLive(peers[sessKey(r.own, r.sid)]?.ts, now) &&
|
|
401
|
+
(filter.kind === undefined || r.kind === filter.kind) &&
|
|
402
|
+
(filter.ns === undefined || r.kind.startsWith(`x:${filter.ns}.`))) {
|
|
403
|
+
out.push(r);
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
return out;
|
|
408
|
+
}
|
|
409
|
+
/** The bounded `ls` summary of one session's state: at most XSTATE_LS_MAX, newest first. */
|
|
410
|
+
export function stateSummaries(recs) {
|
|
411
|
+
return [...recs]
|
|
412
|
+
.sort((a, b) => b.ts - a.ts)
|
|
413
|
+
.slice(0, XSTATE_LS_MAX)
|
|
414
|
+
.map((r) => ({ kind: r.kind, at: r.ts, expiresAt: expiresAt(r), fallback: sanitizePeerText(r.fallback, FALLBACK_MAX), bytes: r.bytes }));
|
|
415
|
+
}
|
|
416
|
+
/** A kept body as a copy, bounded by the rendered cap again (it was checked when stored). */
|
|
417
|
+
export function keptCopy(body) {
|
|
418
|
+
if (body === undefined)
|
|
419
|
+
return undefined;
|
|
420
|
+
const s = JSON.stringify(body);
|
|
421
|
+
return s === undefined || Buffer.byteLength(s, "utf8") > Math.max(MAX_RENDERED_BYTES, EXT_STATE_MAX_BYTES) ? undefined : JSON.parse(s);
|
|
422
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,62 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@peer2peer/cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "The standalone Peer2Peer v3 CLI (`p2p`): an account-free identity, friends, circles, end-to-end encrypted session messaging and status over open relays",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"peer2peer",
|
|
7
|
+
"p2p",
|
|
8
|
+
"cli",
|
|
9
|
+
"e2ee",
|
|
10
|
+
"messaging",
|
|
11
|
+
"claude-code",
|
|
12
|
+
"codex",
|
|
13
|
+
"ai-agents",
|
|
14
|
+
"agent-collaboration"
|
|
15
|
+
],
|
|
16
|
+
"homepage": "https://github.com/ix-infrastructure/Peer2Peer/tree/main/packages/p2p#readme",
|
|
17
|
+
"bugs": {
|
|
18
|
+
"url": "https://github.com/ix-infrastructure/Peer2Peer/issues"
|
|
19
|
+
},
|
|
20
|
+
"license": "Apache-2.0",
|
|
21
|
+
"author": "Ix Infrastructure",
|
|
22
|
+
"repository": {
|
|
23
|
+
"type": "git",
|
|
24
|
+
"url": "git+https://github.com/ix-infrastructure/Peer2Peer.git",
|
|
25
|
+
"directory": "packages/p2p"
|
|
26
|
+
},
|
|
27
|
+
"type": "module",
|
|
28
|
+
"main": "./dist/index.js",
|
|
29
|
+
"types": "./dist/index.d.ts",
|
|
30
|
+
"exports": {
|
|
31
|
+
".": {
|
|
32
|
+
"types": "./dist/index.d.ts",
|
|
33
|
+
"import": "./dist/index.js"
|
|
34
|
+
}
|
|
35
|
+
},
|
|
36
|
+
"bin": {
|
|
37
|
+
"p2p": "./dist/bin.js"
|
|
38
|
+
},
|
|
39
|
+
"files": [
|
|
40
|
+
"dist",
|
|
41
|
+
"!dist/**/__tests__",
|
|
42
|
+
"!dist/**/*.test.*",
|
|
43
|
+
"!dist/**/*.map",
|
|
44
|
+
"README.md",
|
|
45
|
+
"LICENSE"
|
|
46
|
+
],
|
|
47
|
+
"engines": {
|
|
48
|
+
"node": ">=22"
|
|
49
|
+
},
|
|
50
|
+
"publishConfig": {
|
|
51
|
+
"access": "public",
|
|
52
|
+
"provenance": true,
|
|
53
|
+
"registry": "https://registry.npmjs.org/"
|
|
54
|
+
},
|
|
55
|
+
"dependencies": {
|
|
56
|
+
"@peer2peer/codex-bridge": "0.1.0",
|
|
57
|
+
"@peer2peer/core": "0.1.0",
|
|
58
|
+
"commander": "15.0.0",
|
|
59
|
+
"uqr": "0.1.3",
|
|
60
|
+
"ws": "8.22.0"
|
|
61
|
+
}
|
|
62
|
+
}
|