@peer2peer/cli 0.0.0-stage → 0.1.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.
Files changed (111) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +370 -2
  3. package/dist/ancestry.d.ts +13 -0
  4. package/dist/ancestry.js +71 -0
  5. package/dist/app.d.ts +368 -0
  6. package/dist/app.js +1181 -0
  7. package/dist/bin.d.ts +2 -0
  8. package/dist/bin.js +56 -0
  9. package/dist/circle-ops.d.ts +402 -0
  10. package/dist/circle-ops.js +1725 -0
  11. package/dist/cli.d.ts +660 -0
  12. package/dist/cli.js +1787 -0
  13. package/dist/codes.d.ts +231 -0
  14. package/dist/codes.js +998 -0
  15. package/dist/config.d.ts +159 -0
  16. package/dist/config.js +294 -0
  17. package/dist/doctor.d.ts +113 -0
  18. package/dist/doctor.js +930 -0
  19. package/dist/errors.d.ts +8 -0
  20. package/dist/errors.js +29 -0
  21. package/dist/ext-host.d.ts +38 -0
  22. package/dist/ext-host.js +293 -0
  23. package/dist/extensions.d.ts +487 -0
  24. package/dist/extensions.js +406 -0
  25. package/dist/features.d.ts +91 -0
  26. package/dist/features.js +164 -0
  27. package/dist/format.d.ts +57 -0
  28. package/dist/format.js +248 -0
  29. package/dist/graph-memory.d.ts +107 -0
  30. package/dist/graph-memory.js +393 -0
  31. package/dist/history.d.ts +155 -0
  32. package/dist/history.js +697 -0
  33. package/dist/identity.d.ts +239 -0
  34. package/dist/identity.js +759 -0
  35. package/dist/inbound.d.ts +32 -0
  36. package/dist/inbound.js +261 -0
  37. package/dist/index.d.ts +8 -0
  38. package/dist/index.js +14 -0
  39. package/dist/ix-local.d.ts +76 -0
  40. package/dist/ix-local.js +203 -0
  41. package/dist/join-answers.d.ts +49 -0
  42. package/dist/join-answers.js +149 -0
  43. package/dist/outbox.d.ts +109 -0
  44. package/dist/outbox.js +337 -0
  45. package/dist/pretty.d.ts +100 -0
  46. package/dist/pretty.js +256 -0
  47. package/dist/procstart.d.ts +1 -0
  48. package/dist/procstart.js +66 -0
  49. package/dist/progress.d.ts +30 -0
  50. package/dist/progress.js +78 -0
  51. package/dist/projects.d.ts +491 -0
  52. package/dist/projects.js +1383 -0
  53. package/dist/prompt/picker.d.ts +64 -0
  54. package/dist/prompt/picker.js +152 -0
  55. package/dist/prompt/tty.d.ts +29 -0
  56. package/dist/prompt/tty.js +122 -0
  57. package/dist/readonly.d.ts +20 -0
  58. package/dist/readonly.js +50 -0
  59. package/dist/receipts.d.ts +99 -0
  60. package/dist/receipts.js +182 -0
  61. package/dist/relay-client.d.ts +277 -0
  62. package/dist/relay-client.js +873 -0
  63. package/dist/relay-info.d.ts +24 -0
  64. package/dist/relay-info.js +53 -0
  65. package/dist/rotation.d.ts +402 -0
  66. package/dist/rotation.js +2054 -0
  67. package/dist/running.d.ts +5 -0
  68. package/dist/running.js +74 -0
  69. package/dist/sessions.d.ts +355 -0
  70. package/dist/sessions.js +1247 -0
  71. package/dist/shortcode.d.ts +149 -0
  72. package/dist/shortcode.js +465 -0
  73. package/dist/social.d.ts +139 -0
  74. package/dist/social.js +485 -0
  75. package/dist/state.d.ts +509 -0
  76. package/dist/state.js +220 -0
  77. package/dist/stdin.d.ts +17 -0
  78. package/dist/stdin.js +46 -0
  79. package/dist/sync.d.ts +77 -0
  80. package/dist/sync.js +375 -0
  81. package/dist/transient.d.ts +1 -0
  82. package/dist/transient.js +28 -0
  83. package/dist/trust.d.ts +37 -0
  84. package/dist/trust.js +134 -0
  85. package/dist/tty-confirm.d.ts +2 -0
  86. package/dist/tty-confirm.js +53 -0
  87. package/dist/tui/command.d.ts +20 -0
  88. package/dist/tui/command.js +70 -0
  89. package/dist/tui/frame.d.ts +43 -0
  90. package/dist/tui/frame.js +111 -0
  91. package/dist/tui/model.d.ts +221 -0
  92. package/dist/tui/model.js +259 -0
  93. package/dist/tui/sanitize.d.ts +13 -0
  94. package/dist/tui/sanitize.js +151 -0
  95. package/dist/tui/terminal.d.ts +88 -0
  96. package/dist/tui/terminal.js +354 -0
  97. package/dist/tui/tui.d.ts +78 -0
  98. package/dist/tui/tui.js +612 -0
  99. package/dist/tui/view.d.ts +4 -0
  100. package/dist/tui/view.js +358 -0
  101. package/dist/unknown-kinds.d.ts +12 -0
  102. package/dist/unknown-kinds.js +66 -0
  103. package/dist/version.d.ts +1 -0
  104. package/dist/version.js +5 -0
  105. package/dist/want-pow.d.ts +12 -0
  106. package/dist/want-pow.js +46 -0
  107. package/dist/watch.d.ts +35 -0
  108. package/dist/watch.js +331 -0
  109. package/dist/xstate.d.ts +125 -0
  110. package/dist/xstate.js +422 -0
  111. package/package.json +60 -4
package/dist/watch.js ADDED
@@ -0,0 +1,331 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // `p2p watch --session <sid> --jsonl`: the one long-running command.
4
+ //
5
+ // It stays connected to every relay of the user (reconnecting with backoff,
6
+ // silently), handles each delivery (inbound.ts), and prints one compact JSON
7
+ // line per accepted event from the shared event log, so events picked up by
8
+ // any other `p2p` process are printed too. The cursor lives in
9
+ // `<home>/cursors/<sid>.cursor` and advances only after a line was handed to
10
+ // stdout, so a restart resumes where it stopped.
11
+ //
12
+ // Filtering for `--session <sid>`: session events of our own session `sid`,
13
+ // events addressed to it (`toSession`: replies in sessions it spoke to,
14
+ // notify-when-idle), session events of others' sessions that no local
15
+ // session has claimed, and every control event (contacts, circles, held).
16
+ //
17
+ // Exit codes: 0 when stopped
18
+ // (SIGINT/SIGTERM) or when the reader goes away (EPIPE), 1 on a fatal error
19
+ // (usage, no identity, every relay refusing this device).
20
+ import { watch as watchDir } from "node:fs";
21
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
22
+ import { join } from "node:path";
23
+ import { certExpiresWithin, mayRepublish, nowSec } from "@peer2peer/core/v3";
24
+ import { CLOSE_GRACE_MS, REPUBLISH_DOC_WITHIN_SEC } from "./app.js";
25
+ import { receiving } from "./inbound.js";
26
+ import { answerDeferredWants, renewOpenJoinCaps } from "./circle-ops.js";
27
+ import { checkSid, expireSubs } from "./sessions.js";
28
+ import { CliError } from "./errors.js";
29
+ import { safeJson } from "./format.js";
30
+ import { alertForeignRotations, noteDocRotations, retryRotationJoins } from "./rotation.js";
31
+ import { flushOutbox, OUTBOX_RETRY_MS } from "./outbox.js";
32
+ import { markRunning, unmarkRunning } from "./running.js";
33
+ import { graphMemoryLoop, graphMemoryTickMs } from "./graph-memory.js";
34
+ function cursorPath(app, sid) {
35
+ return join(app.home, "cursors", `${sid}.cursor`);
36
+ }
37
+ async function readCursor(app, sid) {
38
+ try {
39
+ const v = JSON.parse(await readFile(cursorPath(app, sid), "utf8"));
40
+ if (typeof v.n === "number" && typeof v.start === "number")
41
+ return v;
42
+ }
43
+ catch {
44
+ // none yet
45
+ }
46
+ return undefined;
47
+ }
48
+ async function writeCursor(app, sid, c) {
49
+ const p = cursorPath(app, sid);
50
+ await mkdir(join(app.home, "cursors"), { recursive: true, mode: 0o700 });
51
+ const tmp = `${p}.${process.pid}.tmp`;
52
+ await writeFile(tmp, JSON.stringify(c), { mode: 0o600 });
53
+ await rename(tmp, p);
54
+ }
55
+ /** Does session `sid` of `self` see this event? */
56
+ export function eventFor(e, sid, self, cursor) {
57
+ if (e.n <= cursor.n)
58
+ return false;
59
+ if (e.toSession !== undefined)
60
+ return e.toSession === sid;
61
+ // The copy of a message for a session that wasn't running (onSessionEnvelope): every other
62
+ // session shows it, never the one it was for (that one has the message itself, if it resumes).
63
+ if (e.data.unclaimedFor === sid)
64
+ return false;
65
+ // A message for no session: only the sessions whose projects reach its sender (sessions.ts routableSessions).
66
+ if (Array.isArray(e.data.routable) && !e.data.routable.includes(sid))
67
+ return false;
68
+ if (e.n <= cursor.start)
69
+ return false;
70
+ if (e.own !== undefined)
71
+ return e.own !== self;
72
+ return true;
73
+ }
74
+ /**
75
+ * The JSON line for an event: `{kind, id, at, ...data, toSession?}`. Fields
76
+ * starting with `_` are local-only (an extension's kept body) and never printed.
77
+ */
78
+ export function eventLine(e) {
79
+ const data = Object.fromEntries(Object.entries(e.data).filter(([k]) => !k.startsWith("_")));
80
+ return safeJson({ kind: e.kind, id: e.id, at: e.at, ...data, ...(e.toSession ? { toSession: e.toSession } : {}) });
81
+ }
82
+ /** How long a stopped watch waits for its own clean-up (the running marker, the app's close) before returning. */
83
+ export const WATCH_EXIT_MS = 2 * CLOSE_GRACE_MS;
84
+ /** Settles with `p`, or with undefined as soon as `signal` aborts (the work itself goes on, unawaited). */
85
+ function untilAborted(p, signal) {
86
+ if (signal.aborted) {
87
+ p.catch(() => undefined);
88
+ return Promise.resolve(undefined);
89
+ }
90
+ return new Promise((resolve, reject) => {
91
+ const off = () => signal.removeEventListener("abort", onAbort);
92
+ const onAbort = () => {
93
+ off();
94
+ resolve(undefined);
95
+ };
96
+ signal.addEventListener("abort", onAbort);
97
+ p.then((v) => {
98
+ off();
99
+ resolve(v);
100
+ }, (e) => {
101
+ off();
102
+ if (signal.aborted)
103
+ resolve(undefined);
104
+ else
105
+ reject(e);
106
+ });
107
+ });
108
+ }
109
+ /** `p`, or give up after `ms` (the work goes on, unawaited). */
110
+ function within(p, ms) {
111
+ return Promise.race([p.catch(() => undefined), new Promise((r) => setTimeout(r, ms).unref())]);
112
+ }
113
+ export async function watch(app, opts) {
114
+ const sid = checkSid(opts.session);
115
+ receiving(app);
116
+ // This session is running while this process lives (running.ts): messages for it are its own.
117
+ app.watching = sid;
118
+ await markRunning(app, sid);
119
+ let exitCode = 0;
120
+ let fatal;
121
+ const stop = new AbortController();
122
+ const onAbort = () => stop.abort();
123
+ opts.signal.addEventListener("abort", onAbort);
124
+ const log = await app.state.get("events");
125
+ let cursor = await readCursor(app, sid);
126
+ if (!cursor) {
127
+ const max = log?.items.at(-1)?.n ?? 0;
128
+ const mine = (log?.items ?? []).filter((e) => e.toSession === sid).map((e) => e.n);
129
+ cursor = { n: mine.length > 0 ? Math.min(...mine) - 1 : max, start: max };
130
+ await writeCursor(app, sid, cursor);
131
+ }
132
+ await app.connect({
133
+ reconnect: true,
134
+ onFatal: (why) => {
135
+ fatal = why;
136
+ stop.abort();
137
+ },
138
+ });
139
+ const timers = [];
140
+ const every = (ms, fn) => {
141
+ const t = setInterval(() => void fn().catch((e) => opts.log(`p2p watch: ${e.message}`)), ms);
142
+ t.unref();
143
+ timers.push(t);
144
+ };
145
+ every(60_000, () => expireSubs(app));
146
+ // Messages this device couldn't send when they were written (outbox.ts): due ones, with backoff.
147
+ // Back from a stretch with no relay: everything waiting goes out at once, not at its backoff.
148
+ let wasOffline = false;
149
+ every(OUTBOX_RETRY_MS, async () => {
150
+ const up = (app.pool?.connected.length ?? 0) > 0;
151
+ if (!up)
152
+ wasOffline = true;
153
+ else {
154
+ await flushOutbox(app, { force: wasOffline });
155
+ wasOffline = false;
156
+ }
157
+ });
158
+ // A watch starting is a new connection: everything waiting goes out now, backoff or not.
159
+ void flushOutbox(app, { force: true }).catch(() => { });
160
+ // Re-review N6: wants the first device in line didn't answer in time.
161
+ every(30_000, async () => void (await answerDeferredWants(app)));
162
+ every(10 * 60_000, async () => {
163
+ await refreshContacts(app);
164
+ await renewOpenJoinCaps(app);
165
+ });
166
+ every(3600_000, () => maintain(app));
167
+ // Graph memory (graph-memory.ts): this device's sessions' context into the local Ix graph, gathered
168
+ // from the statuses they posted and written in the background, a batch at a time. Off without the
169
+ // Ix extension, without Ix, or when the person turned it off; never on the hook path.
170
+ const memory = graphMemoryLoop(app, { log: opts.log });
171
+ every(graphMemoryTickMs(app.env), () => memory.tick());
172
+ void maintain(app).catch(() => { });
173
+ const pollMs = opts.pollMs ?? 300;
174
+ const startedAs = app.userId;
175
+ let polls = 0;
176
+ // Push, not poll: a delivery this process handled, or a change to the event log by another
177
+ // process, wakes the loop at once. The poll stays as a backstop (a file system without change
178
+ // notifications), and the scan itself is unchanged.
179
+ let woke;
180
+ let wakeUp;
181
+ const wake = () => {
182
+ woke = true;
183
+ wakeUp?.();
184
+ };
185
+ const offEvents = app.state.onEventsAdded(wake);
186
+ let logWatcher;
187
+ try {
188
+ logWatcher = watchDir(join(app.state.dir, "cli"), { persistent: false }, (_ev, name) => {
189
+ if (name === null || String(name) === "events.json")
190
+ wake();
191
+ });
192
+ logWatcher.on("error", () => {
193
+ logWatcher?.close();
194
+ logWatcher = undefined;
195
+ });
196
+ }
197
+ catch {
198
+ // no change notifications here: the poll covers it
199
+ }
200
+ try {
201
+ while (!stop.signal.aborted) {
202
+ woke = false;
203
+ // §2.8: this home's identity changed (the user followed a rotation with `p2p identity follow`,
204
+ // or rotated it, in another process). This watch holds the old keys: stop, so the next one
205
+ // starts as the new. (Never follows by itself: pre-release review H2.)
206
+ if (polls++ % 10 === 0) {
207
+ const keys = await untilAborted(app.state.get("keys"), stop.signal);
208
+ if (stop.signal.aborted)
209
+ break;
210
+ if (app.userId !== startedAs || keys?.userId !== startedAs) {
211
+ opts.log(`p2p watch: this device moved to your new identity; restart watch`);
212
+ stop.abort();
213
+ break;
214
+ }
215
+ }
216
+ // Every wait in here gives way to a stop at once: a state lock held elsewhere (a background
217
+ // refresh, another process) must never keep a stopped watch from returning.
218
+ const doc = await untilAborted(app.state.get("events"), stop.signal);
219
+ if (stop.signal.aborted)
220
+ break;
221
+ for (const e of doc?.items ?? []) {
222
+ if (stop.signal.aborted)
223
+ break;
224
+ if (!eventFor(e, sid, app.userId, cursor))
225
+ continue;
226
+ const ok = await opts.write(eventLine(e));
227
+ if (!ok) {
228
+ stop.abort();
229
+ break;
230
+ }
231
+ cursor = { ...cursor, n: e.n };
232
+ await untilAborted(writeCursor(app, sid, cursor), stop.signal);
233
+ }
234
+ if (stop.signal.aborted)
235
+ break;
236
+ // Skip past events not for us, so the scan stays short.
237
+ const last = doc?.items.at(-1)?.n ?? cursor.n;
238
+ if (last > cursor.n && !(doc?.items ?? []).some((e) => e.n > cursor.n && eventFor(e, sid, app.userId, cursor))) {
239
+ cursor = { ...cursor, n: last };
240
+ await untilAborted(writeCursor(app, sid, cursor), stop.signal);
241
+ }
242
+ if (woke)
243
+ continue;
244
+ await new Promise((r) => {
245
+ const done = () => {
246
+ clearTimeout(t);
247
+ wakeUp = undefined;
248
+ stop.signal.removeEventListener("abort", done);
249
+ r();
250
+ };
251
+ const t = setTimeout(done, pollMs);
252
+ wakeUp = done;
253
+ stop.signal.addEventListener("abort", done);
254
+ });
255
+ }
256
+ }
257
+ finally {
258
+ offEvents();
259
+ logWatcher?.close();
260
+ for (const t of timers)
261
+ clearInterval(t);
262
+ opts.signal.removeEventListener("abort", onAbort);
263
+ // Bounded: a stopped watch returns within WATCH_EXIT_MS whatever its clean-up waits on.
264
+ const deadline = Date.now() + WATCH_EXIT_MS;
265
+ await within(unmarkRunning(app, sid), CLOSE_GRACE_MS);
266
+ await within(app.close(), Math.max(0, deadline - Date.now()));
267
+ }
268
+ if (fatal) {
269
+ opts.log(`p2p watch: ${fatal}`);
270
+ exitCode = 1;
271
+ }
272
+ return exitCode;
273
+ }
274
+ /** §2.5: refresh friends' and co-members' documents (revocations spread this way). */
275
+ export async function refreshContacts(app) {
276
+ const users = new Set();
277
+ for (const f of await app.store.listFriendships())
278
+ users.add(f.inviter === app.userId ? f.invitee : f.inviter);
279
+ for (const c of await app.store.listCircles())
280
+ if (c.joinedByMe)
281
+ for (const s of Object.keys(c.statements))
282
+ users.add(s);
283
+ users.delete(app.userId);
284
+ for (const u of users) {
285
+ const v = await app.view(u);
286
+ if (v)
287
+ await app.refreshIdentity(u, v.relays, { force: true }).catch(() => undefined);
288
+ // §2.8: a final version carrying a rotation is found here with no push (conflicts are flagged).
289
+ await noteDocRotations(app, u).catch(() => undefined);
290
+ }
291
+ await app.refreshIdentity(app.userId, app.relays, { force: true }).catch(() => undefined);
292
+ await alertForeignRotations(app).catch(() => undefined);
293
+ await retryRotationJoins(app).catch(() => []);
294
+ await app.adoptCertFromDoc();
295
+ }
296
+ /** Key holders keep the document and certificates fresh (§2.3 renewal, §2.5 re-publish, single writer). */
297
+ export async function maintain(app) {
298
+ if (!app.isKeyholder) {
299
+ await app.adoptCertFromDoc();
300
+ return;
301
+ }
302
+ // Fail closed (review H2): only on a head confirmed on the relays, and never from a device that's no longer listed.
303
+ try {
304
+ await app.refreshIdentity(app.userId, app.relays, { force: true, strict: true });
305
+ }
306
+ catch (e) {
307
+ if (e instanceof CliError)
308
+ return;
309
+ throw e;
310
+ }
311
+ const v = await app.ownView();
312
+ if (!v.devices.includes(app.did) || !v.keyholders.includes(app.did))
313
+ return;
314
+ const now = nowSec();
315
+ const certSoon = (v.head.certs ?? []).some((c) => {
316
+ try {
317
+ const exp = JSON.parse(Buffer.from(c.split(".")[1], "base64url").toString()).exp;
318
+ return certExpiresWithin({ exp }, 30 * 86_400, now);
319
+ }
320
+ catch {
321
+ return false;
322
+ }
323
+ });
324
+ const docSoon = v.head.exp - now <= REPUBLISH_DOC_WITHIN_SEC;
325
+ if ((docSoon || certSoon) && mayRepublish(app.did, v.head, now)) {
326
+ await app.publishNext(() => { }).catch((e) => {
327
+ if (!(e instanceof CliError))
328
+ throw e;
329
+ });
330
+ }
331
+ }
@@ -0,0 +1,125 @@
1
+ import { type AcceptedMessageV3, type ExtensionKind, type ExtStateMarker } from "@peer2peer/core/v3";
2
+ import type { App } from "./app.js";
3
+ import { type ExtensionRegistry } from "./extensions.js";
4
+ import { type PeerStatusRec, type XStateIndex, type XStateRec } from "./state.js";
5
+ /** At most this many state kinds stored per session; a new kind beyond it is dropped. */
6
+ export declare const XSTATE_KINDS_PER_SESSION = 8;
7
+ /** At most this many values kept per sender (all their sessions); their oldest go first. */
8
+ export declare const XSTATE_VALUES_PER_USER = 64;
9
+ /** At most this much kept per sender, counted with xstateCost(); their oldest values go first. */
10
+ export declare const XSTATE_BYTES_PER_USER: number;
11
+ /** What every value is charged at least (a tiny value still costs a record), plus its strings and XSTATE_OVERHEAD. */
12
+ export declare const XSTATE_MIN_COST = 1024;
13
+ export declare const XSTATE_OVERHEAD = 128;
14
+ /**
15
+ * At most this many values kept in all. Over it, the sender holding the most
16
+ * loses their oldest value first (never another sender's by age), so one
17
+ * sender can't evict everyone else's state.
18
+ */
19
+ export declare const XSTATE_MAX_RECORDS = 512;
20
+ /** Updates accepted per minute for one (sender, session), all its kinds; the rest are dropped (flood guard). */
21
+ export declare const XSTATE_UPDATES_PER_MIN = 120;
22
+ /** ...and for one sender across all their sessions (session ids are free to make up). */
23
+ export declare const XSTATE_SENDER_UPDATES_PER_MIN = 240;
24
+ /** At most this many per-session rate windows kept per sender; the oldest go first. */
25
+ export declare const XSTATE_RATE_WINDOWS_MAX = 128;
26
+ /** A receiver drops an update this much sooner than EXT_STATE_MIN_INTERVAL_MS after the last (clock jitter). */
27
+ export declare const XSTATE_SPACING_SLACK_MS = 1000;
28
+ /** `ls --json`: at most this many state summaries per row. */
29
+ export declare const XSTATE_LS_MAX = 8;
30
+ /** What a stored value is charged against its sender's XSTATE_BYTES_PER_USER. */
31
+ export declare function xstateCost(r: Pick<XStateRec, "bytes" | "fallback" | "kind" | "sid">): number;
32
+ /** Each sender's values live in a document of their own (`xstate-<16 hex of sha256(userId)>`); `xstate` is the small index. */
33
+ export declare const senderDoc: (own: string) => string;
34
+ /** The kinds the loaded extensions declare as state, with their declared ttl. */
35
+ export declare function declaredState(reg: ExtensionRegistry | undefined, kind: string): {
36
+ ttl: number;
37
+ } | undefined;
38
+ /** The caps this client advertises for state kinds: `<kind>.v1` for each one a loaded extension declares. */
39
+ export declare function stateKindCaps(reg: ExtensionRegistry | undefined): string[];
40
+ /**
41
+ * The devices of `u` that get a state kind: none unless every live session of
42
+ * theirs we know of (other than this device's own) advertises xstate.v1 (the
43
+ * agents.v1 rule), and then only the devices those sessions run on.
44
+ */
45
+ export declare function stateDevices(peers: Record<string, PeerStatusRec>, u: string, self: {
46
+ userId: string;
47
+ did: string;
48
+ }, now?: number): string[];
49
+ export interface PublishStateOpts {
50
+ fromSession: string;
51
+ kind: string;
52
+ v: number;
53
+ body: unknown;
54
+ /** ≤200 characters of plain text: what a state-aware client without the extension shows in `ls`. */
55
+ fallback: string;
56
+ /** Seconds (EXT_STATE_TTL_MIN-MAX); default EXT_STATE_TTL_DEFAULT. */
57
+ ttl?: number;
58
+ }
59
+ export interface PublishStateResult {
60
+ kind: string;
61
+ bytes: number;
62
+ ttl: number;
63
+ delivered: {
64
+ userId: string;
65
+ address: string;
66
+ relays: number;
67
+ devices: number;
68
+ }[];
69
+ /** In the audience, but not sent: no live session that advertises xstate.v1 (an older client, or none live). */
70
+ skipped: {
71
+ userId: string;
72
+ address: string;
73
+ reason: string;
74
+ }[];
75
+ failed: {
76
+ userId: string;
77
+ address: string;
78
+ error: string;
79
+ }[];
80
+ }
81
+ export declare function publishExtensionState(app: App, o: PublishStateOpts): Promise<PublishStateResult>;
82
+ type ExtPlaintext = {
83
+ kind: ExtensionKind;
84
+ ext: {
85
+ v: number;
86
+ body: unknown;
87
+ };
88
+ fallback: string;
89
+ state?: ExtStateMarker;
90
+ };
91
+ /** Whether an inbound extension kind is a state kind: it says so, or a loaded extension declares it. */
92
+ export declare function isStateEnvelope(reg: ExtensionRegistry | undefined, pt: ExtPlaintext): boolean;
93
+ /** What happened to an inbound state value (for tests and P2P_DEBUG). */
94
+ export type StateVerdict = "stored" | "not-owner" | "too-large" | "older" | "rate-limited" | "too-many-kinds" | "flood";
95
+ /**
96
+ * An inbound state kind: stored (latest wins) or dropped, never an event.
97
+ * Only the session's owner publishes its state.
98
+ */
99
+ /** `now` is the receiver's clock (its rate windows and arrival time); tests pass a fixed one. */
100
+ export declare function onStateEnvelope(app: App, r: AcceptedMessageV3, pt: ExtPlaintext, from: {
101
+ userId: string;
102
+ address: string;
103
+ self: boolean;
104
+ }, now?: number): Promise<StateVerdict>;
105
+ export declare function asIndex(v: unknown): XStateIndex;
106
+ /** Expiry: the ttl from the earlier of the envelope's ts and arrival (a ts set ahead can't stretch it). */
107
+ export declare function expiresAt(rec: XStateRec): number;
108
+ /** The stored values of live sessions, within their ttl; optionally of one kind, or one namespace. */
109
+ export declare function liveStates(app: App, filter?: {
110
+ kind?: string;
111
+ ns?: string;
112
+ }, now?: number): Promise<XStateRec[]>;
113
+ /** One `ls --json` summary entry: no body, only what any client may show (the sanitized fallback). */
114
+ export interface StateSummary {
115
+ kind: string;
116
+ at: number;
117
+ expiresAt: number;
118
+ fallback: string;
119
+ bytes: number;
120
+ }
121
+ /** The bounded `ls` summary of one session's state: at most XSTATE_LS_MAX, newest first. */
122
+ export declare function stateSummaries(recs: readonly XStateRec[]): StateSummary[];
123
+ /** A kept body as a copy, bounded by the rendered cap again (it was checked when stored). */
124
+ export declare function keptCopy(body: unknown): unknown;
125
+ export {};