@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/sessions.js
ADDED
|
@@ -0,0 +1,1152 @@
|
|
|
1
|
+
// Copyright 2026 Ix Infrastructure Inc.
|
|
2
|
+
//
|
|
3
|
+
// Agent sessions (docs/protocol.md §3.4, §4.2, §4.3, §6): rosters, `status`
|
|
4
|
+
// envelopes, messages, `ls`, and `watch`.
|
|
5
|
+
//
|
|
6
|
+
// - A session's roster follows its project (projects.ts, §6): private until
|
|
7
|
+
// the person shares the project, and never wider than every project the
|
|
8
|
+
// session has worked in allows. It rides in every status and message we
|
|
9
|
+
// send into our own session.
|
|
10
|
+
// - `status` goes to everyone the roster allows (§4.2, computed with the
|
|
11
|
+
// core's own rule) and to our other devices. A session is live for 150 s
|
|
12
|
+
// after the `ts` of its last status (§4.3).
|
|
13
|
+
// - `send --to` resolves a user, then one of their live sessions (a `[ref]`
|
|
14
|
+
// or `/sid` picks one); with none, the message goes into our own session,
|
|
15
|
+
// whose roster must allow the recipient.
|
|
16
|
+
// - `--notify-when-idle` is a local, one-shot subscription: the next time
|
|
17
|
+
// that session's status goes busy → idle (or it sends `idle`), the sender
|
|
18
|
+
// session's watcher gets `p2p.idle`. It expires after an hour.
|
|
19
|
+
import { sessionEnded } from "./running.js";
|
|
20
|
+
import { enqueue, flushOutbox, OUTBOX_RETRYABLE, OUTBOX_TTL_MS, retryable } from "./outbox.js";
|
|
21
|
+
import { basename, dirname, resolve as resolvePath } from "node:path";
|
|
22
|
+
import { createRosterV3, displayStatus, extensionFallbackText, FALLBACK_MAX, isExtensionKind, isLive, isSafeRelativePath, liveFriendshipsV3, loadCircle, partyAuthorizedV3, sanitizePeerText, sha256, standsLookup, circlePolicy, isStatusCap, STATUS_CAP_MAX_LEN, STATUS_CAPS_MAX, STATUS_CAP_RECEIPTS, STATUS_CAP_AGENTS, STATUS_AGENTS_MAX, STATUS_AGENT_FILES_MAX, STATUS_AGENT_TASK_MAX, isStatusAgentBranch, isStatusAgentFile, isStatusAgentId, isStatusAgentType, statusAgentsError, summaryWithAgents, redactSecrets, stripAbsolutePaths, parseBound, } from "@peer2peer/core/v3";
|
|
23
|
+
import { CliError } from "./errors.js";
|
|
24
|
+
import { assertMayReach, bindSession, ceilingAudience, defaultCircleNotice, friendIds, PERSON_SESSION, sessionBinding, agentContext, sessionCeiling, sessionProjectView, sessionDirs, sessionWorkdir, MAX_SESSION_DIRS, shareHint, } from "./projects.js";
|
|
25
|
+
import { renderExtension } from "./extensions.js";
|
|
26
|
+
import { fromOf, makeEvent } from "./inbound.js";
|
|
27
|
+
import { receiptsEnabled, statusCapsEnabled } from "./config.js";
|
|
28
|
+
import { CAP_PROJECTS, CLI_CAPS, protoMinor, supportsIn } from "./features.js";
|
|
29
|
+
import { asksReceipts, newReceiptId, rememberAsked, rememberWanted } from "./receipts.js";
|
|
30
|
+
import { sessKey } from "./state.js";
|
|
31
|
+
import { isStateEnvelope, liveStates, onStateEnvelope, stateKindCaps, stateSummaries } from "./xstate.js";
|
|
32
|
+
/** Session ids: what Claude Code and Codex use (UUIDs and the like). */
|
|
33
|
+
export const SID_RE = /^[A-Za-z0-9._-]{1,128}$/;
|
|
34
|
+
export const MAX_TEXT_BYTES = 24 * 1024;
|
|
35
|
+
export const MAX_FILES = 25;
|
|
36
|
+
export const IDLE_SUB_TTL_MS = 3600_000;
|
|
37
|
+
/**
|
|
38
|
+
* What this CLI itself understands (§4.3 "Status caps"): the tolerant status
|
|
39
|
+
* parser, `status.agents` (it parses, stores and lists them), and extension
|
|
40
|
+
* state kinds (xstate.v1: it keeps them latest-wins and never logs them as
|
|
41
|
+
* events; xstate.ts). `p2p status` adds `<kind>.v1` for each state kind a
|
|
42
|
+
* loaded extension declares. A caller
|
|
43
|
+
* (the mod, the Codex bridge) adds its own with `--cap`.
|
|
44
|
+
*
|
|
45
|
+
* Two-step rollout, step 2 (footprint P1): statuses carry `caps` by default.
|
|
46
|
+
* Clients older than the amendment reject a status that carries `caps`, so a
|
|
47
|
+
* user whose peers still run one opts out with `P2P_STATUS_CAPS=0` or
|
|
48
|
+
* `"statusCaps": false` in config.json (see statusCapsEnabled).
|
|
49
|
+
*/
|
|
50
|
+
export const CLI_STATUS_CAPS = CLI_CAPS;
|
|
51
|
+
/** §4.3 "Status agents": at most this many distinct paths across `files` and every agent's. */
|
|
52
|
+
export const MAX_STATUS_PATHS = 60;
|
|
53
|
+
/** §4.3: a sender keeps a status plaintext under 8 KiB; agents are trimmed (oldest first) to fit. */
|
|
54
|
+
export const STATUS_SOFT_MAX_BYTES = 8 * 1024;
|
|
55
|
+
export function checkSid(sid, flag = "--session") {
|
|
56
|
+
if (!sid || !SID_RE.test(sid))
|
|
57
|
+
throw new CliError("usage", `${flag} must be a session id ([A-Za-z0-9._-], at most 128)`);
|
|
58
|
+
return sid;
|
|
59
|
+
}
|
|
60
|
+
/** First 6 hex characters of sha256(own + "/" + sid): a short session reference. */
|
|
61
|
+
export function sessionRef(own, sid) {
|
|
62
|
+
return [...sha256(new TextEncoder().encode(`${own}/${sid}`)).slice(0, 3)].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Decides and writes a session's roster under the state lock, against the doc
|
|
66
|
+
* as stored at that moment (review M1): two commands at once (a status post
|
|
67
|
+
* following the default circle, and `session roster --private`) can't undo
|
|
68
|
+
* each other, and a version is never reused or lowered. The trust store must
|
|
69
|
+
* take the new version too; a stale or conflicting one stops here, nothing
|
|
70
|
+
* written.
|
|
71
|
+
*/
|
|
72
|
+
async function writeRoster(app, sid, decide, want) {
|
|
73
|
+
// What this device would sign as the default roster now (`want`): an adopted one equal to it still follows the project.
|
|
74
|
+
return app.state.updateAsync("sessions", async (cur = {}) => {
|
|
75
|
+
const have = cur[sid];
|
|
76
|
+
// The trust store may hold a newer version than state (written by an older client, a crash
|
|
77
|
+
// between the two writes): adopt it first, and number past it, or the session's roster could
|
|
78
|
+
// never change again (review M-new). Only one this device signed (pre-release review low): anything
|
|
79
|
+
// else fails closed.
|
|
80
|
+
const stored = await app.store.getRoster(app.userId, sid);
|
|
81
|
+
let base = have;
|
|
82
|
+
if (stored && stored.ver > (have?.ver ?? 0) && stored.jws !== have?.jws)
|
|
83
|
+
base = docFromStored(sid, stored, app.did, want);
|
|
84
|
+
const spec = decide(base);
|
|
85
|
+
if (!spec) {
|
|
86
|
+
if (!base)
|
|
87
|
+
throw new CliError("conflict", `session ${sid} has no roster`);
|
|
88
|
+
return base === have ? { result: base } : { next: { ...cur, [sid]: base }, result: base };
|
|
89
|
+
}
|
|
90
|
+
const ver = Math.max(base?.ver ?? 0, stored?.ver ?? 0) + 1;
|
|
91
|
+
const jws = createRosterV3(app.signer(), { sid, ver, vis: spec.vis, ...(spec.circle ? { circle: spec.circle } : {}), parts: spec.parts });
|
|
92
|
+
const put = await app.store.putRoster({ iss: app.userId, sid, ver, jws });
|
|
93
|
+
if (put === "stale" || put === "conflict") {
|
|
94
|
+
throw new CliError("conflict", `session ${sid}: roster version ${ver} is ${put} against the one already held; run the command again`);
|
|
95
|
+
}
|
|
96
|
+
const doc = { sid, ver, vis: spec.vis, ...(spec.circle ? { circle: spec.circle } : {}), parts: [...spec.parts], jws, ...(spec.auto !== undefined ? { auto: spec.auto } : {}) };
|
|
97
|
+
return { next: { ...cur, [sid]: doc }, result: doc };
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* A stored roster of our own as a session doc: its signed payload read back
|
|
102
|
+
* (it is ours, verified when stored). Only a roster this device signed is
|
|
103
|
+
* adopted (pre-release review low); one signed by another device of ours, or one this
|
|
104
|
+
* client can't read, fails closed: nothing is written. Its provenance is
|
|
105
|
+
* unknown, so it counts as set explicitly (no auto-follow), unless it is
|
|
106
|
+
* exactly the default roster this device would sign now (`want`, no
|
|
107
|
+
* participants): then it keeps following the default.
|
|
108
|
+
*/
|
|
109
|
+
export function docFromStored(sid, r, did, want) {
|
|
110
|
+
let p;
|
|
111
|
+
try {
|
|
112
|
+
p = JSON.parse(Buffer.from(r.jws.split(".")[1] ?? "", "base64url").toString("utf8"));
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
p = {};
|
|
116
|
+
}
|
|
117
|
+
if (p.sid !== sid || p.ver !== r.ver || (p.vis !== "circle" && p.vis !== "private") || !Array.isArray(p.parts)) {
|
|
118
|
+
throw new CliError("conflict", `session ${sid}: the trust store holds roster version ${r.ver}, which this client can't read; it is not adopted, and the roster is left as it is`);
|
|
119
|
+
}
|
|
120
|
+
if (p.did !== did) {
|
|
121
|
+
throw new CliError("conflict", `session ${sid}: the trust store holds roster version ${r.ver} signed by another device (${sanitizePeerText(String(p.did), 80)}), not this one (${did}); this device won't adopt or overwrite it: use another session id here`);
|
|
122
|
+
}
|
|
123
|
+
const parts = p.parts.filter((x) => typeof x === "string");
|
|
124
|
+
const circle = p.vis === "circle" && typeof p.circle === "string" ? p.circle : undefined;
|
|
125
|
+
const auto = want !== undefined && parts.length === 0 && p.vis === want.vis && circle === want.circle;
|
|
126
|
+
return { sid, ver: r.ver, vis: p.vis, ...(circle ? { circle } : {}), parts, jws: r.jws, auto };
|
|
127
|
+
}
|
|
128
|
+
async function rosterCtx(app, sid) {
|
|
129
|
+
const ceiling = await sessionCeiling(app, sid);
|
|
130
|
+
const audience = await ceilingAudience(app, ceiling);
|
|
131
|
+
if (ceiling.kind !== "shared" || !audience)
|
|
132
|
+
return { ceiling, ...(audience ? { audience } : {}), auto: { vis: "private", parts: [], auto: true } };
|
|
133
|
+
const def = app.self?.defaultCircle;
|
|
134
|
+
const circle = def && ceiling.circles.includes(def) ? def : ceiling.circles[0];
|
|
135
|
+
const inCircle = new Set();
|
|
136
|
+
if (circle)
|
|
137
|
+
for (const m of (await loadCircle(app.store, circle).catch(() => undefined))?.chain.head.members ?? [])
|
|
138
|
+
inCircle.add(m);
|
|
139
|
+
const friends = await friendIds(app);
|
|
140
|
+
const parts = [...audience].filter((u) => !inCircle.has(u) && friends.has(u)).sort();
|
|
141
|
+
return { ceiling, audience, auto: { vis: circle ? "circle" : "private", ...(circle ? { circle } : {}), parts, auto: true } };
|
|
142
|
+
}
|
|
143
|
+
/** A roster cut down to what the ceiling allows (never wider than it was). */
|
|
144
|
+
function clip(spec, ctx) {
|
|
145
|
+
if (ctx.ceiling.kind === "none" || !ctx.audience)
|
|
146
|
+
return spec;
|
|
147
|
+
if (ctx.ceiling.kind === "private")
|
|
148
|
+
return { vis: "private", parts: [], auto: spec.auto };
|
|
149
|
+
const circle = spec.vis === "circle" && spec.circle && ctx.ceiling.circles.includes(spec.circle) ? spec.circle : undefined;
|
|
150
|
+
return { vis: circle ? "circle" : "private", ...(circle ? { circle } : {}), parts: spec.parts.filter((u) => ctx.audience.has(u)), auto: spec.auto };
|
|
151
|
+
}
|
|
152
|
+
function sameRoster(a, b) {
|
|
153
|
+
const pa = [...new Set(a.parts)].sort();
|
|
154
|
+
const pb = [...new Set(b.parts)].sort();
|
|
155
|
+
return a.vis === b.vis && a.circle === b.circle && pa.length === pb.length && pa.every((x, i) => x === pb[i]) && isAutoRoster(a) === (b.auto ?? false);
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Whether a session's roster is still the default one, never set explicitly.
|
|
159
|
+
* A doc from before `auto` existed counts when it is the first version with
|
|
160
|
+
* no participants: every explicit change (`session roster`) bumps the version.
|
|
161
|
+
*/
|
|
162
|
+
export function isAutoRoster(d) {
|
|
163
|
+
return d.auto ?? (d.ver === 1 && d.parts.length === 0);
|
|
164
|
+
}
|
|
165
|
+
export const OPEN_CIRCLE_SHARED = "is shared with an open circle (its policy is open now): anyone its owner admits can see it; `p2p session roster <sid> --private` (or /peers private) stops that";
|
|
166
|
+
/**
|
|
167
|
+
* Review L-c: a session shared with a circle whose policy is (or became) open
|
|
168
|
+
* says so once, on its next status (a warning in the result), and once more
|
|
169
|
+
* only if it moves to another open circle.
|
|
170
|
+
*/
|
|
171
|
+
async function noteOpenCircle(app, sess, notes) {
|
|
172
|
+
if (sess.vis !== "circle" || !sess.circle || sess.openNoted === sess.circle)
|
|
173
|
+
return sess;
|
|
174
|
+
const c = await loadCircle(app.store, sess.circle).catch(() => undefined);
|
|
175
|
+
if (!c || circlePolicy(c.chain.head) !== "open")
|
|
176
|
+
return sess;
|
|
177
|
+
notes.push(`session ${sess.sid} ${OPEN_CIRCLE_SHARED}`);
|
|
178
|
+
const circle = sess.circle;
|
|
179
|
+
return app.state.update("sessions", (cur = {}) => {
|
|
180
|
+
const d = cur[sess.sid];
|
|
181
|
+
if (!d || d.jws !== sess.jws)
|
|
182
|
+
return { result: sess };
|
|
183
|
+
const next = { ...d, openNoted: circle };
|
|
184
|
+
return { next: { ...cur, [sess.sid]: next }, result: next };
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
/** Kept for clients that match these notes (older mods); this CLI no longer says them: sessions follow their project. */
|
|
188
|
+
export const CODE_JOIN_NO_FOLLOW = "kept as it was: a code you redeemed set your default circle, and a session already running doesn't move into a circle by itself; share it with `p2p session roster <sid> --circle <cid>` (or /peers circle <cid>). New sessions start in it";
|
|
189
|
+
export const OPEN_CIRCLE_NO_FOLLOW = "kept private: your default circle is open (anyone its owner admits can see what's shared there), so a session already running doesn't move into it by itself; share it with `p2p session roster <sid> --circle <cid>` (or /peers circle <cid>)";
|
|
190
|
+
/**
|
|
191
|
+
* The session's roster, made on first use, and kept within its project ceiling (projects.ts):
|
|
192
|
+
* one nobody set by hand follows its projects' policies (private until the person shares the
|
|
193
|
+
* project); one set by hand is cut down to the ceiling when the ceiling narrows (a session that
|
|
194
|
+
* worked in a private project stays private until it ends). The person's own session, and one
|
|
195
|
+
* no project is bound to yet, have no ceiling: their roster is private until set by hand.
|
|
196
|
+
*/
|
|
197
|
+
export async function getSession(app, sid, notes) {
|
|
198
|
+
void notes;
|
|
199
|
+
const ctx = await rosterCtx(app, sid);
|
|
200
|
+
return writeRoster(app, sid, (have) => {
|
|
201
|
+
if (ctx.ceiling.kind === "none")
|
|
202
|
+
return have ? undefined : { vis: "private", parts: [], auto: true };
|
|
203
|
+
const spec = !have || isAutoRoster(have) ? ctx.auto : clip({ vis: have.vis, ...(have.circle ? { circle: have.circle } : {}), parts: have.parts, auto: false }, ctx);
|
|
204
|
+
return have && sameRoster(have, spec) ? undefined : spec;
|
|
205
|
+
}, ctx.auto);
|
|
206
|
+
}
|
|
207
|
+
async function rosterView(app, s) {
|
|
208
|
+
const c = s.circle ? await loadCircle(app.store, s.circle) : undefined;
|
|
209
|
+
return {
|
|
210
|
+
sid: s.sid,
|
|
211
|
+
ref: sessionRef(app.userId, s.sid),
|
|
212
|
+
ver: s.ver,
|
|
213
|
+
vis: s.vis,
|
|
214
|
+
...(s.circle ? { circle: s.circle } : {}),
|
|
215
|
+
...(c ? { circleName: sanitizePeerText(c.chain.head.name, 64) } : {}),
|
|
216
|
+
parts: await Promise.all(s.parts.map(async (u) => ({ userId: u, address: await app.addressOf(u) }))),
|
|
217
|
+
...(c && circlePolicy(c.chain.head) === "open" ? { openCircle: true } : {}),
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
export async function roster(app, sid, opts) {
|
|
221
|
+
checkSid(sid, "sid");
|
|
222
|
+
const cur = await getSession(app, sid);
|
|
223
|
+
const change = opts.circle !== undefined || opts.private || (opts.add?.length ?? 0) > 0 || (opts.remove?.length ?? 0) > 0;
|
|
224
|
+
if (!change)
|
|
225
|
+
return rosterView(app, cur);
|
|
226
|
+
// A change (even a narrowing one) only from the session's front end once one registered it, and
|
|
227
|
+
// never from an agent's own shell (projects.ts bindSession, N2).
|
|
228
|
+
if (!app.front) {
|
|
229
|
+
if (agentContext(app.env))
|
|
230
|
+
throw new CliError("refused", `session ${sid}: inside an agent's session only its front end changes who sees a session`);
|
|
231
|
+
if ((await sessionBinding(app, sid))?.registered)
|
|
232
|
+
throw new CliError("refused", `session ${sid} belongs to a front end of yours (the Claude mod or the Codex bridge): only it changes who sees that session`);
|
|
233
|
+
}
|
|
234
|
+
if (opts.circle !== undefined && opts.private)
|
|
235
|
+
throw new CliError("usage", "--circle and --private are exclusive");
|
|
236
|
+
let vis = cur.vis;
|
|
237
|
+
let circle = cur.circle;
|
|
238
|
+
if (opts.circle !== undefined) {
|
|
239
|
+
const { resolveCircle } = await import("./circle-ops.js");
|
|
240
|
+
const c = await resolveCircle(app, opts.circle);
|
|
241
|
+
if (!c.record.joinedByMe)
|
|
242
|
+
throw new CliError("usage", "you haven't joined that circle");
|
|
243
|
+
vis = "circle";
|
|
244
|
+
circle = c.record.cid;
|
|
245
|
+
}
|
|
246
|
+
if (opts.private) {
|
|
247
|
+
vis = "private";
|
|
248
|
+
circle = undefined;
|
|
249
|
+
}
|
|
250
|
+
const add = [];
|
|
251
|
+
for (const a of opts.add ?? []) {
|
|
252
|
+
const u = await app.resolveUser(a);
|
|
253
|
+
if (u !== app.userId)
|
|
254
|
+
add.push(u);
|
|
255
|
+
}
|
|
256
|
+
const remove = await Promise.all((opts.remove ?? []).map((r) => app.resolveUser(r)));
|
|
257
|
+
// Never wider than the session's projects allow (projects.ts): sharing beyond them is the
|
|
258
|
+
// project's policy, which only the person changes (`p2p project share`).
|
|
259
|
+
const ctx = await rosterCtx(app, sid);
|
|
260
|
+
if (ctx.ceiling.kind !== "none" && ctx.audience) {
|
|
261
|
+
const names = Object.values((await sessionBinding(app, sid))?.projects ?? {}).map((p) => p.name);
|
|
262
|
+
const ceiling = ctx.ceiling;
|
|
263
|
+
const deny = (what) => {
|
|
264
|
+
throw new CliError("not_shared", `session ${sid} works in ${names.join(", ")}, which ${ceiling.kind === "private" ? `is private (${ceiling.why}), so it isn't shared` : "isn't shared"} ${what}: ${shareHint(names)}`);
|
|
265
|
+
};
|
|
266
|
+
if (opts.circle !== undefined && circle !== undefined && (ceiling.kind !== "shared" || !ceiling.circles.includes(circle)))
|
|
267
|
+
deny(`with circle ${circle}`);
|
|
268
|
+
for (const u of add)
|
|
269
|
+
if (!ctx.audience.has(u))
|
|
270
|
+
deny(`with ${await app.addressOf(u)}`);
|
|
271
|
+
}
|
|
272
|
+
// Applied to the doc as stored when the lock is held, not as read above (review M1).
|
|
273
|
+
// Set explicitly: it no longer follows the project.
|
|
274
|
+
const next = await writeRoster(app, sid, (have) => {
|
|
275
|
+
const parts = new Set(have?.parts ?? []);
|
|
276
|
+
for (const u of add)
|
|
277
|
+
parts.add(u);
|
|
278
|
+
for (const u of remove)
|
|
279
|
+
parts.delete(u);
|
|
280
|
+
const v = opts.private ? "private" : opts.circle !== undefined ? "circle" : (have?.vis ?? vis);
|
|
281
|
+
const c = opts.private ? undefined : opts.circle !== undefined ? circle : have?.circle;
|
|
282
|
+
return clip({ vis: v, ...(c ? { circle: c } : {}), parts: [...parts], auto: false }, ctx);
|
|
283
|
+
}, ctx.auto);
|
|
284
|
+
const v = await rosterView(app, next);
|
|
285
|
+
if (v.openCircle) {
|
|
286
|
+
app.warn("this session is shared with an open circle: anyone the owner admits can see it");
|
|
287
|
+
// Warned here already: its next status doesn't say it again.
|
|
288
|
+
await app.state.update("sessions", (cur = {}) => (cur[sid]?.jws === next.jws ? { next: { ...cur, [sid]: { ...cur[sid], openNoted: next.circle } }, result: undefined } : { result: undefined }));
|
|
289
|
+
}
|
|
290
|
+
return v;
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* Who a session's status reaches, as an extension may know it (ExtContext.audience): its
|
|
294
|
+
* roster's visibility, the circle and whether that circle is open, and how many people the
|
|
295
|
+
* roster lets see it besides this user. Read only: a session with no roster yet, or whose circle
|
|
296
|
+
* can't be loaded, is undefined (nothing is created). `orgs` (distinct verified organisations) is absent until a trust
|
|
297
|
+
* provider supplies org labels (§8.2).
|
|
298
|
+
*/
|
|
299
|
+
export async function sessionAudience(app, sid) {
|
|
300
|
+
checkSid(sid, "sid");
|
|
301
|
+
const sess = (await app.state.get("sessions"))?.[sid];
|
|
302
|
+
if (!sess)
|
|
303
|
+
return undefined;
|
|
304
|
+
const c = sess.vis === "circle" && sess.circle ? await loadCircle(app.store, sess.circle).catch(() => undefined) : undefined;
|
|
305
|
+
// A circle that can't be loaded: who it reaches is unknown (an extension then fails closed).
|
|
306
|
+
if (sess.vis === "circle" && sess.circle && !c)
|
|
307
|
+
return undefined;
|
|
308
|
+
let members = (await rosterAudience(app, sess).catch(() => [])).filter((u) => u !== app.userId);
|
|
309
|
+
// The stored roster may predate a narrower ceiling (no status since): never wider than the ceiling now.
|
|
310
|
+
const cap = await ceilingAudience(app, await sessionCeiling(app, sid));
|
|
311
|
+
if (cap)
|
|
312
|
+
members = members.filter((u) => cap.has(u));
|
|
313
|
+
return { vis: sess.vis, ...(sess.circle ? { circle: sess.circle } : {}), ...(c && circlePolicy(c.chain.head) === "open" ? { open: true } : {}), people: members.length, members };
|
|
314
|
+
}
|
|
315
|
+
/** Who the roster lets see this session, besides us (§4.2, the core rule). */
|
|
316
|
+
export async function rosterAudience(app, s) {
|
|
317
|
+
const facts = {
|
|
318
|
+
friendships: await liveFriendshipsV3(app.store, app.signerCtx()),
|
|
319
|
+
unfriends: await app.store.listUnfriends(),
|
|
320
|
+
stands: await standsLookup(app.store, app.userId),
|
|
321
|
+
};
|
|
322
|
+
const r = { iss: app.userId, vis: s.vis, ...(s.circle ? { circle: s.circle } : {}), parts: s.parts };
|
|
323
|
+
const cands = new Set(s.parts);
|
|
324
|
+
if (s.circle) {
|
|
325
|
+
const c = await loadCircle(app.store, s.circle);
|
|
326
|
+
for (const m of c?.chain.head.members ?? [])
|
|
327
|
+
cands.add(m);
|
|
328
|
+
}
|
|
329
|
+
cands.delete(app.userId);
|
|
330
|
+
const blocks = new Set((await app.store.listBlocks()).map((b) => b.userId));
|
|
331
|
+
return [...cands].filter((u) => !blocks.has(u) && partyAuthorizedV3(u, r, facts).ok);
|
|
332
|
+
}
|
|
333
|
+
/**
|
|
334
|
+
* The status this session posts. Never fails over what a caller adds on top
|
|
335
|
+
* of the original fields (review L3): with status caps off (the opt-out),
|
|
336
|
+
* caller caps and agents are left out (agents still count in the summary); an
|
|
337
|
+
* invalid or surplus cap is dropped. Each is noted in `warnings`.
|
|
338
|
+
*/
|
|
339
|
+
export function buildStatus(o, prev, warnings = []) {
|
|
340
|
+
if (o.state !== "busy" && o.state !== "idle")
|
|
341
|
+
throw new CliError("usage", "--state must be busy or idle");
|
|
342
|
+
const files = o.files ?? [];
|
|
343
|
+
if (files.length > MAX_FILES)
|
|
344
|
+
throw new CliError("usage", `at most ${MAX_FILES} --file`);
|
|
345
|
+
for (const f of files)
|
|
346
|
+
if (!isSafeRelativePath(f) || f.length > 200)
|
|
347
|
+
throw new CliError("usage", `--file ${f} must be a relative path with no . or .. segments`);
|
|
348
|
+
if (o.summary !== undefined && [...o.summary].length > 280)
|
|
349
|
+
throw new CliError("usage", "--summary is at most 280 characters");
|
|
350
|
+
const label = (o.label ?? basename(o.cwd ?? process.cwd())).slice(0, 64) || "session";
|
|
351
|
+
const s = { state: o.state, label };
|
|
352
|
+
if (o.repo)
|
|
353
|
+
s.repo = o.repo;
|
|
354
|
+
if (o.branch)
|
|
355
|
+
s.branch = o.branch;
|
|
356
|
+
if (o.mode)
|
|
357
|
+
s.mode = o.mode;
|
|
358
|
+
if (o.summary) {
|
|
359
|
+
s.summary = o.summary;
|
|
360
|
+
// The line as written, without a `(+N agents)` this CLI added (caps off stores the folded one; review L1).
|
|
361
|
+
s.summaryAt = prev?.summary !== undefined && withoutAgentCount(prev.summary) === o.summary && prev.summaryAt ? prev.summaryAt : Date.now();
|
|
362
|
+
}
|
|
363
|
+
if (files.length > 0)
|
|
364
|
+
s.files = files;
|
|
365
|
+
const agents = o.agents === undefined ? undefined : normalizeAgents(o.agents, files);
|
|
366
|
+
if (o.emitCaps) {
|
|
367
|
+
s.caps = statusCaps(o.caps, warnings);
|
|
368
|
+
if (agents && agents.length > 0) {
|
|
369
|
+
s.agents = agents;
|
|
370
|
+
fitAgents(s);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
else {
|
|
374
|
+
if ((o.caps?.length ?? 0) > 0)
|
|
375
|
+
warnings.push("status caps are off (P2P_STATUS_CAPS=0 or \"statusCaps\": false), so --cap was left out");
|
|
376
|
+
// Off: the status carries only the original fields; agents at work still show as `(+N agents)`.
|
|
377
|
+
const folded = summaryWithAgents(s.summary, agents);
|
|
378
|
+
if (folded !== s.summary && folded !== undefined)
|
|
379
|
+
s.summary = folded;
|
|
380
|
+
}
|
|
381
|
+
return s;
|
|
382
|
+
}
|
|
383
|
+
/** A summary without the ` (+N agents)` summaryWithAgents() appends (or the whole of one that is only that). */
|
|
384
|
+
export function withoutAgentCount(summary) {
|
|
385
|
+
return summary.replace(/(^| )\(\+\d+ agents?\)$/, "");
|
|
386
|
+
}
|
|
387
|
+
/** CLI_STATUS_CAPS plus the caller's valid ones, deduplicated and within STATUS_CAPS_MAX; the rest are noted. */
|
|
388
|
+
function statusCaps(extra = [], warnings = []) {
|
|
389
|
+
const caps = [...CLI_STATUS_CAPS];
|
|
390
|
+
for (const c of extra) {
|
|
391
|
+
if (caps.includes(c))
|
|
392
|
+
continue;
|
|
393
|
+
if (!isStatusCap(c))
|
|
394
|
+
warnings.push(`--cap ${JSON.stringify(c).slice(0, 60)} was left out: at most ${STATUS_CAP_MAX_LEN} characters of [a-z0-9._-], starting with a letter (x: for an extension's)`);
|
|
395
|
+
else if (caps.length >= STATUS_CAPS_MAX)
|
|
396
|
+
warnings.push(`--cap ${c} was left out: at most ${STATUS_CAPS_MAX} caps in a status (${CLI_STATUS_CAPS.length} are the CLI's own)`);
|
|
397
|
+
else
|
|
398
|
+
caps.push(c);
|
|
399
|
+
}
|
|
400
|
+
return caps;
|
|
401
|
+
}
|
|
402
|
+
const AGENT_STATE = {
|
|
403
|
+
running: "running",
|
|
404
|
+
pending: "running",
|
|
405
|
+
waiting: "waiting",
|
|
406
|
+
idle: "idle",
|
|
407
|
+
done: "done",
|
|
408
|
+
completed: "done",
|
|
409
|
+
failed: "failed",
|
|
410
|
+
killed: "failed",
|
|
411
|
+
};
|
|
412
|
+
const isDone = (a) => a.state === "done" || a.state === "failed";
|
|
413
|
+
/**
|
|
414
|
+
* `--agents-json` as a valid §4.3 `agents` list: each entry's fields
|
|
415
|
+
* sanitized or dropped, at most 10 files each (never under `.claude/worktrees/`
|
|
416
|
+
* or `.git/`), ordered (at work first, then most recent), at most 8, nesting
|
|
417
|
+
* flattened to depth 2. Not an array is a usage error.
|
|
418
|
+
*/
|
|
419
|
+
export function normalizeAgents(raw, mainFiles = []) {
|
|
420
|
+
if (!Array.isArray(raw))
|
|
421
|
+
throw new CliError("usage", "--agents-json must be a JSON array of agents");
|
|
422
|
+
const out = [];
|
|
423
|
+
const seen = new Set();
|
|
424
|
+
for (const x of raw.slice(0, 64)) {
|
|
425
|
+
if (typeof x !== "object" || x === null || Array.isArray(x))
|
|
426
|
+
continue;
|
|
427
|
+
const e = x;
|
|
428
|
+
if (!isStatusAgentId(e.id) || seen.has(e.id))
|
|
429
|
+
continue;
|
|
430
|
+
const state = typeof e.state === "string" ? AGENT_STATE[e.state] : undefined;
|
|
431
|
+
if (!state)
|
|
432
|
+
continue;
|
|
433
|
+
seen.add(e.id);
|
|
434
|
+
const typeRaw = typeof e.type === "string" ? e.type.replace(/[^A-Za-z0-9:_ .-]/g, "").replace(/\s+/g, " ").trim().slice(0, 32).trim() : "";
|
|
435
|
+
const type = isStatusAgentType(typeRaw) ? typeRaw : "agent";
|
|
436
|
+
// No absolute or home paths, no secret shapes (review M3), before the 80-character cap.
|
|
437
|
+
// Sanitized first (one line, no controls), then no absolute or home paths and no secret shapes, then capped.
|
|
438
|
+
const task = sanitizePeerText(redactSecrets(stripAbsolutePaths(sanitizePeerText(typeof e.task === "string" ? e.task.slice(0, 2000) : "", 2000))), STATUS_AGENT_TASK_MAX) || type;
|
|
439
|
+
const files = [];
|
|
440
|
+
for (const f of Array.isArray(e.files) ? e.files : []) {
|
|
441
|
+
if (files.length >= STATUS_AGENT_FILES_MAX)
|
|
442
|
+
break;
|
|
443
|
+
if (!isStatusAgentFile(f) || files.includes(f))
|
|
444
|
+
continue;
|
|
445
|
+
const lower = f.toLowerCase().replace(/\\/g, "/");
|
|
446
|
+
if (lower === ".git" || lower.startsWith(".git/") || lower === ".claude/worktrees" || lower.startsWith(".claude/worktrees/"))
|
|
447
|
+
continue;
|
|
448
|
+
files.push(f);
|
|
449
|
+
}
|
|
450
|
+
const at = typeof e.at === "number" && Number.isSafeInteger(e.at) && e.at >= 0 ? e.at : Date.now();
|
|
451
|
+
out.push({
|
|
452
|
+
id: e.id,
|
|
453
|
+
...(isStatusAgentId(e.parent) && e.parent !== e.id ? { parent: e.parent } : {}),
|
|
454
|
+
type,
|
|
455
|
+
task,
|
|
456
|
+
state,
|
|
457
|
+
...(files.length > 0 ? { files } : {}),
|
|
458
|
+
...(e.wt === true ? { wt: true } : {}),
|
|
459
|
+
...(e.wt === true && isStatusAgentBranch(e.branch) ? { branch: e.branch } : {}),
|
|
460
|
+
at,
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
// At work first, then the most recent; done and failed last.
|
|
464
|
+
out.sort((a, b) => Number(isDone(a)) - Number(isDone(b)) || b.at - a.at);
|
|
465
|
+
// Over the cap: done agents with no files go first, then the oldest.
|
|
466
|
+
while (out.length > STATUS_AGENTS_MAX) {
|
|
467
|
+
let drop = out.length - 1;
|
|
468
|
+
for (let i = out.length - 1; i >= 0; i--) {
|
|
469
|
+
if (isDone(out[i]) && !out[i].files) {
|
|
470
|
+
drop = i;
|
|
471
|
+
break;
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
out.splice(drop, 1);
|
|
475
|
+
}
|
|
476
|
+
flatten(out);
|
|
477
|
+
// At most MAX_STATUS_PATHS distinct paths across the main loop's files and every agent's.
|
|
478
|
+
const paths = new Set(mainFiles);
|
|
479
|
+
for (const a of out) {
|
|
480
|
+
if (!a.files)
|
|
481
|
+
continue;
|
|
482
|
+
a.files = a.files.filter((f) => {
|
|
483
|
+
if (paths.has(f))
|
|
484
|
+
return true;
|
|
485
|
+
if (paths.size >= MAX_STATUS_PATHS)
|
|
486
|
+
return false;
|
|
487
|
+
paths.add(f);
|
|
488
|
+
return true;
|
|
489
|
+
});
|
|
490
|
+
if (a.files.length === 0)
|
|
491
|
+
delete a.files;
|
|
492
|
+
}
|
|
493
|
+
return out;
|
|
494
|
+
}
|
|
495
|
+
/** Parents that aren't listed are dropped (the agent shows as the main loop's); deeper nesting attaches to the depth-1 ancestor. */
|
|
496
|
+
function flatten(agents) {
|
|
497
|
+
const byId = new Map(agents.map((a) => [a.id, a]));
|
|
498
|
+
for (const a of agents) {
|
|
499
|
+
let p = a.parent !== undefined ? byId.get(a.parent) : undefined;
|
|
500
|
+
for (let hops = 0; p?.parent !== undefined && hops < STATUS_AGENTS_MAX; hops++)
|
|
501
|
+
p = byId.get(p.parent);
|
|
502
|
+
if (p === undefined || p === a || p.parent !== undefined)
|
|
503
|
+
delete a.parent;
|
|
504
|
+
else
|
|
505
|
+
a.parent = p.id;
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
/** Trims `s.agents` from the end until the status plaintext is under STATUS_SOFT_MAX_BYTES; a list that still fails validation is dropped whole. */
|
|
509
|
+
function fitAgents(s) {
|
|
510
|
+
const agents = s.agents;
|
|
511
|
+
if (!agents)
|
|
512
|
+
return;
|
|
513
|
+
while (agents.length > 0 && Buffer.byteLength(JSON.stringify({ status: s }), "utf8") > STATUS_SOFT_MAX_BYTES) {
|
|
514
|
+
agents.pop();
|
|
515
|
+
flatten(agents);
|
|
516
|
+
}
|
|
517
|
+
if (agents.length === 0 || statusAgentsError(agents) !== undefined)
|
|
518
|
+
delete s.agents;
|
|
519
|
+
}
|
|
520
|
+
/**
|
|
521
|
+
* The status a recipient without agents.v1 gets: no `agents` (a client from
|
|
522
|
+
* before P1 would drop it, one from before the amendment would reject the
|
|
523
|
+
* status), and the agents at work counted in the summary instead.
|
|
524
|
+
*/
|
|
525
|
+
export function statusWithoutAgents(s) {
|
|
526
|
+
if (s.agents === undefined)
|
|
527
|
+
return s;
|
|
528
|
+
const { agents, ...rest } = s;
|
|
529
|
+
const summary = summaryWithAgents(s.summary, agents);
|
|
530
|
+
return { ...rest, ...(summary !== undefined ? { summary } : {}) };
|
|
531
|
+
}
|
|
532
|
+
/**
|
|
533
|
+
* Whether user `u` gets `status.agents`: every live session of theirs we
|
|
534
|
+
* know of (other than this device's own) advertises agents.v1, and there is
|
|
535
|
+
* at least one. Status goes to a user, one plaintext for all their devices,
|
|
536
|
+
* so one session from an older client (or none at all) means the summary
|
|
537
|
+
* fallback for that user.
|
|
538
|
+
*/
|
|
539
|
+
export function understandsAgents(peers, u, self, now = Date.now()) {
|
|
540
|
+
return supportsIn({ peers, self, now }, u, { all: true }, STATUS_CAP_AGENTS);
|
|
541
|
+
}
|
|
542
|
+
/** How many recipients a status goes to at once. */
|
|
543
|
+
export const STATUS_FANOUT = 8;
|
|
544
|
+
/** `fn` over `items`, at most `limit` at a time; results in input order. */
|
|
545
|
+
export async function mapLimit(items, limit, fn) {
|
|
546
|
+
const out = new Array(items.length);
|
|
547
|
+
let next = 0;
|
|
548
|
+
const worker = async () => {
|
|
549
|
+
while (next < items.length) {
|
|
550
|
+
const i = next++;
|
|
551
|
+
out[i] = await fn(items[i]);
|
|
552
|
+
}
|
|
553
|
+
};
|
|
554
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
|
|
555
|
+
return out;
|
|
556
|
+
}
|
|
557
|
+
export async function sendStatus(app, o) {
|
|
558
|
+
const sid = checkSid(o.session);
|
|
559
|
+
// The folders of the files it says it changes are folders it works in too (a nested repository,
|
|
560
|
+
// a path through a symlink): each binds its project.
|
|
561
|
+
const work = sessionWorkdir(app.env);
|
|
562
|
+
const fileDirs = (o.files ?? []).filter((f) => typeof f === "string").map((f) => dirname(resolvePath(work, f)));
|
|
563
|
+
await bindFromEnv(app, sid, [...(o.projectDirs ?? []), ...fileDirs], { ...(o.projectDirsOver ? { over: true } : {}) });
|
|
564
|
+
const prev = (await app.state.get("peers"))?.[sessKey(app.userId, sid)];
|
|
565
|
+
const before = (await app.state.get("sessions"))?.[sid];
|
|
566
|
+
const warnings = [];
|
|
567
|
+
// The loaded extensions' state kinds are advertised as `<kind>.v1` (after the caller's own caps).
|
|
568
|
+
// receipts.v1 is the caller's to claim (it reports the outcomes), and this user's to turn off.
|
|
569
|
+
const asked = (o.caps ?? []).filter((c) => c !== STATUS_CAP_RECEIPTS || receiptsEnabled(app.env, app.home));
|
|
570
|
+
const caps = [...asked, ...stateKindCaps(app.extensions).filter((c) => !asked.includes(c))];
|
|
571
|
+
const status = buildStatus({ ...o, caps, emitCaps: o.emitCaps ?? statusCapsEnabled(app.env, app.home) }, prev?.status, warnings);
|
|
572
|
+
// Handle what's queued first (cap grants, roster and circle changes decide who gets this), then
|
|
573
|
+
// read the roster: a circle join approved in that drain makes a default roster the circle's now.
|
|
574
|
+
await app.connectAndDrain();
|
|
575
|
+
const sess = await noteOpenCircle(app, await getSession(app, sid, warnings), warnings);
|
|
576
|
+
const audience = await rosterAudience(app, sess);
|
|
577
|
+
// Narrowed since the last status: whoever could see it and no longer can gets one blank,
|
|
578
|
+
// private status under the roster they hold, so its last real one doesn't linger in their list.
|
|
579
|
+
if (before && before.jws !== sess.jws) {
|
|
580
|
+
// Never silently: whoever didn't get the blank status still lists the last real one until it expires.
|
|
581
|
+
for (const miss of await retract(app, sid, before, audience)) {
|
|
582
|
+
warnings.push(`the blank private status didn't reach ${miss.address} (${miss.error}): they still see its last status until it is no longer live`);
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
if (audience.length === 0) {
|
|
586
|
+
// Nobody but this user's own devices sees it: no summary goes out (the front end skips making one).
|
|
587
|
+
delete status.summary;
|
|
588
|
+
delete status.summaryAt;
|
|
589
|
+
const notice = await defaultCircleNotice(app, sid);
|
|
590
|
+
if (notice)
|
|
591
|
+
warnings.push(notice);
|
|
592
|
+
}
|
|
593
|
+
const peers = (await app.state.get("peers")) ?? {};
|
|
594
|
+
const lite = statusWithoutAgents(status);
|
|
595
|
+
const delivered = [];
|
|
596
|
+
const failed = [];
|
|
597
|
+
// Every recipient at once (a few at a time), not one after another: each delivery is its own
|
|
598
|
+
// identity refresh and round trip. Results keep the audience's order.
|
|
599
|
+
const outcomes = await mapLimit([...audience, app.userId], STATUS_FANOUT, async (u) => {
|
|
600
|
+
if (u === app.userId) {
|
|
601
|
+
const v = await app.view(app.userId);
|
|
602
|
+
if (!v || !v.devices.some((d) => d !== app.did))
|
|
603
|
+
return undefined;
|
|
604
|
+
}
|
|
605
|
+
const agents = status.agents !== undefined && understandsAgents(peers, u, { userId: app.userId, did: app.did });
|
|
606
|
+
try {
|
|
607
|
+
const d = await app.deliver(u, "status", { own: app.userId, sid }, { status: agents ? status : lite, roster: sess.jws });
|
|
608
|
+
if (d.relays.length > 0)
|
|
609
|
+
return { ok: { ...d, address: await app.addressOf(u), agents } };
|
|
610
|
+
return { failed: { userId: u, address: await app.addressOf(u), error: "delivered via 0 relays" } };
|
|
611
|
+
}
|
|
612
|
+
catch (e) {
|
|
613
|
+
return { failed: { userId: u, address: await app.addressOf(u), error: e.message } };
|
|
614
|
+
}
|
|
615
|
+
});
|
|
616
|
+
for (const o of outcomes) {
|
|
617
|
+
if (o?.ok)
|
|
618
|
+
delivered.push(o.ok);
|
|
619
|
+
else if (o?.failed)
|
|
620
|
+
failed.push(o.failed);
|
|
621
|
+
}
|
|
622
|
+
// This device keeps the full status: its own `ls` and ExtContext.ownStatus see the agents.
|
|
623
|
+
const rec = { own: app.userId, sid, did: app.did, ts: Date.now(), status, self: true };
|
|
624
|
+
await app.state.update("peers", (cur = {}) => ({ next: { ...cur, [sessKey(app.userId, sid)]: rec }, result: undefined }));
|
|
625
|
+
// `bound`: the folders the front end passed are bound for good (it can stop sending them).
|
|
626
|
+
return { status, roster: await rosterView(app, sess), delivered, failed, ...(warnings.length > 0 ? { warnings } : {}), project: await sessionProjectView(app, sid), bound: true };
|
|
627
|
+
}
|
|
628
|
+
/**
|
|
629
|
+
* The blank status a narrowed session leaves with those it no longer reaches (under their roster).
|
|
630
|
+
* Returns whom it didn't reach (an error, or no relay took it), for the caller to say so.
|
|
631
|
+
*/
|
|
632
|
+
async function retract(app, sid, before, now) {
|
|
633
|
+
const gone = (await rosterAudience(app, before)).filter((u) => !now.includes(u));
|
|
634
|
+
const out = await mapLimit(gone, STATUS_FANOUT, async (u) => {
|
|
635
|
+
let error;
|
|
636
|
+
try {
|
|
637
|
+
const d = await app.deliver(u, "status", { own: app.userId, sid }, { status: { state: "idle", label: "private" }, roster: before.jws });
|
|
638
|
+
if (d.relays.length === 0)
|
|
639
|
+
error = `delivered via 0 relays${d.errors?.length ? ` (${[...new Set(d.errors.map((e) => e.code))].join(", ")})` : ""}`;
|
|
640
|
+
}
|
|
641
|
+
catch (e) {
|
|
642
|
+
error = e.message;
|
|
643
|
+
}
|
|
644
|
+
return error === undefined ? undefined : { userId: u, address: await app.addressOf(u).catch(() => u), error };
|
|
645
|
+
});
|
|
646
|
+
return out.filter((x) => x !== undefined);
|
|
647
|
+
}
|
|
648
|
+
export async function listPeers(app, opts = {}) {
|
|
649
|
+
const peers = (await app.state.get("peers")) ?? {};
|
|
650
|
+
const now = Date.now();
|
|
651
|
+
const blocks = new Set((await app.store.listBlocks()).map((b) => b.userId));
|
|
652
|
+
const states = await liveStates(app, {}, now);
|
|
653
|
+
const rows = [];
|
|
654
|
+
for (const p of Object.values(peers)) {
|
|
655
|
+
if (blocks.has(p.own))
|
|
656
|
+
continue;
|
|
657
|
+
const live = isLive(p.ts, now);
|
|
658
|
+
if (!live && !opts.all)
|
|
659
|
+
continue;
|
|
660
|
+
const d = displayStatus(p.status);
|
|
661
|
+
const rosterCircle = await rosterCircleOf(app, p.own, p.sid);
|
|
662
|
+
const viewerRule = p.own === app.userId ? "owner" : p.viewerRule;
|
|
663
|
+
const viaCircle = viewerRule === "circle" || viewerRule === "participant-circle";
|
|
664
|
+
rows.push({
|
|
665
|
+
own: p.own,
|
|
666
|
+
sid: p.sid,
|
|
667
|
+
ref: sessionRef(p.own, p.sid),
|
|
668
|
+
address: await app.addressOf(p.own),
|
|
669
|
+
self: p.own === app.userId,
|
|
670
|
+
thisDevice: p.own === app.userId && p.did === app.did,
|
|
671
|
+
live,
|
|
672
|
+
ageSec: Math.max(0, Math.round((now - p.ts) / 1000)),
|
|
673
|
+
...d,
|
|
674
|
+
did: p.did,
|
|
675
|
+
...(d.caps ? { proto: protoMinor(d.caps) } : {}),
|
|
676
|
+
...(live ? stateOf(states, p.own, p.sid) : {}),
|
|
677
|
+
...(viewerRule ? { rule: viewerRule, viewerRule } : {}),
|
|
678
|
+
...(p.rule ? { senderRule: p.rule } : {}),
|
|
679
|
+
...(viaCircle && rosterCircle ? { circle: rosterCircle } : p.own === app.userId && rosterCircle ? { circle: rosterCircle } : {}),
|
|
680
|
+
});
|
|
681
|
+
}
|
|
682
|
+
return rows.sort((a, b) => Number(b.self) - Number(a.self) || a.address.localeCompare(b.address) || b.ageSec - a.ageSec);
|
|
683
|
+
}
|
|
684
|
+
function stateOf(states, own, sid) {
|
|
685
|
+
const mine = states.filter((x) => x.own === own && x.sid === sid);
|
|
686
|
+
return mine.length > 0 ? { xstate: stateSummaries(mine) } : {};
|
|
687
|
+
}
|
|
688
|
+
/** The `circle` a session's held roster names, if any. */
|
|
689
|
+
async function rosterCircleOf(app, own, sid) {
|
|
690
|
+
const r = own === app.userId ? (await app.state.get("sessions"))?.[sid] : await app.store.getRoster(own, sid);
|
|
691
|
+
if (!r)
|
|
692
|
+
return undefined;
|
|
693
|
+
if ("circle" in r && typeof r.circle === "string")
|
|
694
|
+
return r.circle;
|
|
695
|
+
try {
|
|
696
|
+
const c = JSON.parse(Buffer.from(r.jws.split(".")[1], "base64url").toString()).circle;
|
|
697
|
+
return typeof c === "string" ? c : undefined;
|
|
698
|
+
}
|
|
699
|
+
catch {
|
|
700
|
+
return undefined;
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
/** `user`, `user [ref]`, `user/ref` or `user/sid`. */
|
|
704
|
+
export function parseTarget(to) {
|
|
705
|
+
const s = to.trim();
|
|
706
|
+
const br = /^(.*?)\s*\[([0-9a-f]{6})\]$/.exec(s);
|
|
707
|
+
if (br)
|
|
708
|
+
return { user: br[1].trim(), pick: br[2] };
|
|
709
|
+
// userIds, addresses and petnames never contain "/", so the last one separates a session.
|
|
710
|
+
const i = s.lastIndexOf("/");
|
|
711
|
+
if (i > 0 && i < s.length - 1)
|
|
712
|
+
return { user: s.slice(0, i), pick: s.slice(i + 1) };
|
|
713
|
+
return { user: s };
|
|
714
|
+
}
|
|
715
|
+
/**
|
|
716
|
+
* How recently a session must have been seen (its last status) for a message to be held for it
|
|
717
|
+
* while it is offline. Relays keep an envelope for 7 days, and a recipient accepts one whose ts is
|
|
718
|
+
* at most 7 days old; but a session silent for a day has most likely ended (`/exit`, `/clear`),
|
|
719
|
+
* and a message for it would only reach its user as an unclaimed notice. A day covers a laptop
|
|
720
|
+
* asleep overnight or a dropped connection, which is what this is for; older sessions are
|
|
721
|
+
* refused as before (not_found), so a sender never queues into one long gone.
|
|
722
|
+
*/
|
|
723
|
+
export const OFFLINE_TARGET_MS = 24 * 3600 * 1000;
|
|
724
|
+
/**
|
|
725
|
+
* Where a message to `toArg` goes: one of their live sessions, or our own
|
|
726
|
+
* session `fromSession` when its roster lets them in (see the header).
|
|
727
|
+
*/
|
|
728
|
+
async function resolveTarget(app, fromSession, toArg) {
|
|
729
|
+
const { user, pick } = parseTarget(toArg);
|
|
730
|
+
const userId = await app.resolveUser(user);
|
|
731
|
+
if (await app.store.isBlocked(userId))
|
|
732
|
+
throw new CliError("blocked", "you blocked that user");
|
|
733
|
+
const peers = (await app.state.get("peers")) ?? {};
|
|
734
|
+
const now = Date.now();
|
|
735
|
+
const live = Object.values(peers).filter((p) => p.own === userId && isLive(p.ts, now) && !(p.own === app.userId && (p.sid === fromSession || p.did === app.did)) && (!pick || p.sid === pick || sessionRef(p.own, p.sid) === pick));
|
|
736
|
+
let target;
|
|
737
|
+
let offlineSince;
|
|
738
|
+
// Not live now, but seen recently (a dropped connection, a laptop asleep): the same sessions a
|
|
739
|
+
// live one would be picked from, by the same rules, only within OFFLINE_TARGET_MS.
|
|
740
|
+
const recent = live.length > 0
|
|
741
|
+
? []
|
|
742
|
+
: Object.values(peers)
|
|
743
|
+
.filter((p) => p.own === userId &&
|
|
744
|
+
now - p.ts <= OFFLINE_TARGET_MS &&
|
|
745
|
+
!(p.own === app.userId && (p.sid === fromSession || p.did === app.did)) &&
|
|
746
|
+
(!pick || p.sid === pick || sessionRef(p.own, p.sid) === pick))
|
|
747
|
+
.sort((a, b) => b.ts - a.ts);
|
|
748
|
+
if (live.length === 1)
|
|
749
|
+
target = { own: userId, sid: live[0].sid, did: live[0].did };
|
|
750
|
+
else if (live.length === 0 && recent.length === 1) {
|
|
751
|
+
target = { own: userId, sid: recent[0].sid, did: recent[0].did };
|
|
752
|
+
offlineSince = recent[0].ts;
|
|
753
|
+
}
|
|
754
|
+
else if (live.length === 0 && recent.length > 1) {
|
|
755
|
+
throw new CliError("ambiguous", `${await app.addressOf(userId)} has no live session and ${recent.length} seen recently: pick one with "<user> [ref]"`, {
|
|
756
|
+
delivered: false,
|
|
757
|
+
candidates: await Promise.all(recent.map(async (p) => ({ address: await app.addressOf(p.own), sid: p.sid, ref: sessionRef(p.own, p.sid), label: sanitizePeerText(p.status.label, 64), state: "offline", lastSeen: p.ts }))),
|
|
758
|
+
});
|
|
759
|
+
}
|
|
760
|
+
else if (live.length > 1) {
|
|
761
|
+
throw new CliError("ambiguous", `${await app.addressOf(userId)} has ${live.length} live sessions: pick one with "<user> [ref]"`, {
|
|
762
|
+
delivered: false,
|
|
763
|
+
candidates: await Promise.all(live.map(async (p) => ({ address: await app.addressOf(p.own), sid: p.sid, ref: sessionRef(p.own, p.sid), label: sanitizePeerText(p.status.label, 64) }))),
|
|
764
|
+
});
|
|
765
|
+
}
|
|
766
|
+
else if (pick) {
|
|
767
|
+
throw new CliError("not_found", `no live session ${pick} of ${await app.addressOf(userId)}`, { delivered: false });
|
|
768
|
+
}
|
|
769
|
+
else {
|
|
770
|
+
// No live session of theirs: into our own session, if its roster lets them in.
|
|
771
|
+
const sess = await getSession(app, fromSession);
|
|
772
|
+
if (userId !== app.userId && !(await rosterAudience(app, sess)).includes(userId)) {
|
|
773
|
+
throw new CliError("not_shared", `${await app.addressOf(userId)} has no live session you can see, and your session ${fromSession} isn't shared with them: \`p2p session roster ${fromSession} --add ${user}\``, { delivered: false });
|
|
774
|
+
}
|
|
775
|
+
target = { own: app.userId, sid: fromSession };
|
|
776
|
+
}
|
|
777
|
+
const ref = sessionRef(target.own, target.sid);
|
|
778
|
+
return { userId, target, to: { userId, address: await app.addressOf(userId), own: target.own, sid: target.sid, ref }, ...(offlineSince !== undefined ? { offlineSince } : {}) };
|
|
779
|
+
}
|
|
780
|
+
/** The roster JWS that rides with a message into (own, sid). */
|
|
781
|
+
async function rosterFor(app, target) {
|
|
782
|
+
// One of ours on another device: its roster as held (that device signs it, never this one).
|
|
783
|
+
const here = target.own === app.userId && (target.did === undefined || target.did === app.did);
|
|
784
|
+
return here ? (await getSession(app, target.sid)).jws : (await app.store.getRoster(target.own, target.sid))?.jws;
|
|
785
|
+
}
|
|
786
|
+
/**
|
|
787
|
+
* A send by a person at a terminal (the `tui` session: `p2p send` with no --from-session, or `p2p tui`):
|
|
788
|
+
* a recipient who isn't in the session's audience is added to its roster first, so the message can
|
|
789
|
+
* land there and their replies reach it, and the add is undone if the send fails. `shared` names whom
|
|
790
|
+
* it shared with. Never used for --from-session or off a terminal: there a missing share is refused.
|
|
791
|
+
*/
|
|
792
|
+
export async function sendSharing(app, o) {
|
|
793
|
+
const sid = checkSid(o.fromSession, "--from-session");
|
|
794
|
+
const uid = await app.resolveUser(o.to.replace(/\s*\[[^\]]*\]\s*$/, "").replace(/\/[^/]*$/, ""));
|
|
795
|
+
let added = false;
|
|
796
|
+
if (uid !== app.userId && !(await rosterAudience(app, await getSession(app, sid))).includes(uid)) {
|
|
797
|
+
await roster(app, sid, { add: [uid] });
|
|
798
|
+
added = true;
|
|
799
|
+
}
|
|
800
|
+
try {
|
|
801
|
+
const result = await sendMessage(app, { ...o, person: true });
|
|
802
|
+
return added ? { result, shared: { userId: uid, address: await app.addressOf(uid) } } : { result };
|
|
803
|
+
}
|
|
804
|
+
catch (e) {
|
|
805
|
+
// Nothing was sent: the session goes back to whom it was shared with before.
|
|
806
|
+
if (added)
|
|
807
|
+
await roster(app, sid, { remove: [uid] }).catch(() => undefined);
|
|
808
|
+
throw e;
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
export async function sendMessage(app, o) {
|
|
812
|
+
const fromSession = checkSid(o.fromSession, "--from-session");
|
|
813
|
+
if (Buffer.byteLength(o.text, "utf8") > MAX_TEXT_BYTES)
|
|
814
|
+
throw new CliError("too_large", `message text is at most ${MAX_TEXT_BYTES} bytes`);
|
|
815
|
+
if (o.text === "" && !o.notifyWhenIdle)
|
|
816
|
+
throw new CliError("usage", "nothing to send (give text, or --notify-when-idle)");
|
|
817
|
+
// Bound before anything is read or sent: the project ceiling decides who this may reach.
|
|
818
|
+
await bindFromEnv(app, fromSession, o.projectDirs ?? [], { person: o.person === true, ...(o.projectDirsOver ? { over: true } : {}) });
|
|
819
|
+
// This device can't reach any of its relays: the message can still be sealed and kept in the
|
|
820
|
+
// outbox (outbox.ts) for `watch` to send once it can.
|
|
821
|
+
let offline = false;
|
|
822
|
+
await app.connectAndDrain().catch((e) => {
|
|
823
|
+
if (e instanceof CliError && e.code === "no_relay")
|
|
824
|
+
offline = true;
|
|
825
|
+
else
|
|
826
|
+
throw e;
|
|
827
|
+
});
|
|
828
|
+
const { userId, target, to, offlineSince } = await resolveTarget(app, fromSession, o.to);
|
|
829
|
+
// The exfiltration barrier (projects.ts): nothing from this session to anyone its projects don't share.
|
|
830
|
+
if (o.text !== "")
|
|
831
|
+
await assertMayReach(app, fromSession, userId, { person: o.person === true, address: to.address });
|
|
832
|
+
let d;
|
|
833
|
+
let outboxed;
|
|
834
|
+
// Receipts only from a session whose live status says it sends them: an older client rejects the
|
|
835
|
+
// whole message for `rcpt` (§4.3). Not when this device can't reach a relay either: the sealed copy
|
|
836
|
+
// may wait in the outbox for days, long past the status that advertised it (pre-release review R2).
|
|
837
|
+
const rcpt = o.text !== "" && !offline && offlineSince === undefined && (await asksReceipts(app, target.own, target.sid)) ? newReceiptId() : undefined;
|
|
838
|
+
if (o.text !== "") {
|
|
839
|
+
// Anything this device couldn't send earlier goes first (order, and it may be the same peer).
|
|
840
|
+
if (!offline)
|
|
841
|
+
await flushOutbox(app).catch(() => undefined);
|
|
842
|
+
const rosterJws = await rosterFor(app, target);
|
|
843
|
+
const plaintext = { text: o.text, ...(rcpt ? { rcpt } : {}), ...(rosterJws ? { roster: rosterJws } : {}), ...(o.person ? {} : await ownBound(app, fromSession, target, userId)) };
|
|
844
|
+
if (rcpt)
|
|
845
|
+
await rememberWanted(app, rcpt, { to: userId, own: target.own, ref: to.ref, fromSession });
|
|
846
|
+
d = await app.deliver(userId, "msg", target, plaintext, userId === app.userId && target.did ? { onlyDevices: [target.did] } : {});
|
|
847
|
+
const unsent = d.unsent ?? [];
|
|
848
|
+
if (d.relays.length === 0 && !retryable(unsent)) {
|
|
849
|
+
throw new CliError("undelivered", `delivered via 0 relays${d.errors?.length ? ` (${[...new Set(d.errors.map((e) => e.code))].join(", ")})` : ""}`, { delivered: false, to });
|
|
850
|
+
}
|
|
851
|
+
// Copies no relay took, for reasons a retry gets past: kept, sealed, for watch to send. When
|
|
852
|
+
// other copies did go out the message is delivered already; these reach the other devices.
|
|
853
|
+
const later = d.relays.length === 0 ? unsent : unsent.filter((u) => u.codes.every((c) => OUTBOX_RETRYABLE.has(c)));
|
|
854
|
+
if (later.length > 0)
|
|
855
|
+
outboxed = await enqueue(app, later, { kind: "msg", dest: to, fromSession });
|
|
856
|
+
}
|
|
857
|
+
if (target.own !== app.userId) {
|
|
858
|
+
await app.state.update("spoke", (cur = {}) => ({ next: { ...cur, [sessKey(target.own, target.sid)]: fromSession }, result: undefined }));
|
|
859
|
+
}
|
|
860
|
+
if (o.notifyWhenIdle) {
|
|
861
|
+
const sub = { own: target.own, sid: target.sid, toSession: fromSession, at: Date.now() };
|
|
862
|
+
await app.state.update("subs", (cur = []) => ({ next: [...cur.filter((s) => !(s.own === sub.own && s.sid === sub.sid && s.toSession === sub.toSession)), sub], result: undefined }));
|
|
863
|
+
}
|
|
864
|
+
const relays = d?.relays.length ?? 0;
|
|
865
|
+
const queued = d && relays === 0 && outboxed
|
|
866
|
+
? { queued: true, state: "outbox", expiresAt: outboxed.expiresAt, ...(offlineSince !== undefined ? { lastSeen: offlineSince } : {}) }
|
|
867
|
+
: d && offlineSince !== undefined
|
|
868
|
+
? { queued: true, state: "offline", lastSeen: offlineSince, expiresAt: Date.now() + OUTBOX_TTL_MS }
|
|
869
|
+
: {};
|
|
870
|
+
return {
|
|
871
|
+
...(o.person ? {} : { bound: true }),
|
|
872
|
+
// Accepted by a relay (it stores ciphertext for its session for 7 days), or not yet.
|
|
873
|
+
delivered: d !== undefined && relays > 0,
|
|
874
|
+
to,
|
|
875
|
+
relays,
|
|
876
|
+
devices: d?.devices ?? 0,
|
|
877
|
+
...(d ? { messageId: `m${Date.now().toString(36)}` } : {}),
|
|
878
|
+
...(o.notifyWhenIdle ? { notifyWhenIdle: true } : {}),
|
|
879
|
+
...queued,
|
|
880
|
+
...(d ? (rcpt ? { receipts: "requested", receiptId: rcpt } : { receipts: "unsupported" }) : {}),
|
|
881
|
+
};
|
|
882
|
+
}
|
|
883
|
+
/**
|
|
884
|
+
* The budget for `{v, body}`: the same as a message's text, which leaves room in the 64 KiB
|
|
885
|
+
* envelope (§4.1) for the roster, the certificate and two layers of base64.
|
|
886
|
+
*/
|
|
887
|
+
export const MAX_EXT_PLAINTEXT_BYTES = MAX_TEXT_BYTES;
|
|
888
|
+
export async function sendExtension(app, o) {
|
|
889
|
+
const fromSession = checkSid(o.fromSession, "--from-session");
|
|
890
|
+
if (!isExtensionKind(o.kind))
|
|
891
|
+
throw new CliError("usage", `${o.kind} is not an extension kind (x:<ns>.<type>)`);
|
|
892
|
+
if (!Number.isSafeInteger(o.v) || o.v < 0)
|
|
893
|
+
throw new CliError("usage", "ext.v must be a non-negative integer");
|
|
894
|
+
if (typeof o.fallback !== "string" || o.fallback.trim() === "" || [...o.fallback].length > FALLBACK_MAX) {
|
|
895
|
+
throw new CliError("usage", `an extension kind needs a plain-text fallback of 1-${FALLBACK_MAX} characters (§8.1)`);
|
|
896
|
+
}
|
|
897
|
+
const ext = { v: o.v, body: o.body };
|
|
898
|
+
const bytes = Buffer.byteLength(JSON.stringify(ext) ?? "", "utf8");
|
|
899
|
+
if (bytes > MAX_EXT_PLAINTEXT_BYTES)
|
|
900
|
+
throw new CliError("too_large", `the extension body is ${bytes} bytes; at most ${MAX_EXT_PLAINTEXT_BYTES}`);
|
|
901
|
+
await bindFromEnv(app, fromSession, o.projectDirs ?? []);
|
|
902
|
+
await app.connectAndDrain();
|
|
903
|
+
const { userId, target, to } = await resolveTarget(app, fromSession, o.to);
|
|
904
|
+
await assertMayReach(app, fromSession, userId, { address: to.address });
|
|
905
|
+
const rosterJws = await rosterFor(app, target);
|
|
906
|
+
const plaintext = { ext, fallback: o.fallback, ...(rosterJws ? { roster: rosterJws } : {}), ...(await ownBound(app, fromSession, target, userId)) };
|
|
907
|
+
const d = await app.deliver(userId, o.kind, target, plaintext, userId === app.userId && target.did ? { onlyDevices: [target.did] } : {});
|
|
908
|
+
if (d.relays.length === 0) {
|
|
909
|
+
throw new CliError("undelivered", `delivered via 0 relays${d.errors?.length ? ` (${[...new Set(d.errors.map((e) => e.code))].join(", ")})` : ""}`, { delivered: false, to });
|
|
910
|
+
}
|
|
911
|
+
if (target.own !== app.userId) {
|
|
912
|
+
await app.state.update("spoke", (cur = {}) => ({ next: { ...cur, [sessKey(target.own, target.sid)]: fromSession }, result: undefined }));
|
|
913
|
+
}
|
|
914
|
+
return { delivered: true, to, relays: d.relays.length, devices: d.devices, kind: o.kind, bytes, bound: true };
|
|
915
|
+
}
|
|
916
|
+
// ---------------------------------------------------------------------------
|
|
917
|
+
// Inbound session kinds
|
|
918
|
+
export async function onSessionEnvelope(app, env, r) {
|
|
919
|
+
const accepted = r;
|
|
920
|
+
const e = r.envelope;
|
|
921
|
+
const from = await fromOf(app, r);
|
|
922
|
+
const ref = sessionRef(e.own, e.sid);
|
|
923
|
+
const spoke = (await app.state.get("spoke")) ?? {};
|
|
924
|
+
let toSession = e.own === app.userId ? e.sid : spoke[sessKey(e.own, e.sid)];
|
|
925
|
+
const pt = r.plaintext;
|
|
926
|
+
// A reply into a session of ours that spoke to theirs: only while that session may still reach
|
|
927
|
+
// the sender (projects.ts). Otherwise it is a message to this user, routed by `routable` below.
|
|
928
|
+
const carries = pt.kind === "msg" || ("ext" in pt && !isStateEnvelope(app.extensions, pt));
|
|
929
|
+
if (carries && toSession !== undefined && e.own !== app.userId && !from.self && !(await mayReach(app, toSession, e.from)))
|
|
930
|
+
toSession = undefined;
|
|
931
|
+
// Into a session of ours from someone its projects don't reach: dropped here, whatever roster came
|
|
932
|
+
// with it (one signed by another device of ours, an older client's, can't widen this one's).
|
|
933
|
+
if (carries && e.own === app.userId && !from.self && !(await mayReach(app, e.sid, e.from)))
|
|
934
|
+
return [];
|
|
935
|
+
// From another session of ours: whatever bounded it now bounds the session it went into.
|
|
936
|
+
const bound = pt.bound;
|
|
937
|
+
if (carries && from.self && bound !== undefined && toSession !== undefined && toSession !== PERSON_SESSION) {
|
|
938
|
+
await bindSession(app, toSession, [], { constraint: bound, inbound: true });
|
|
939
|
+
}
|
|
940
|
+
const sess = { own: e.own, sid: e.sid, ref, rule: r.rule, ...(r.viewerRule ? { viewerRule: r.viewerRule } : {}) };
|
|
941
|
+
const extra = { own: e.own, sid: e.sid, ...(toSession ? { toSession } : {}) };
|
|
942
|
+
// Named for no session of ours: which local sessions may hold it (watch shows it only to those).
|
|
943
|
+
const routable = carries && toSession === undefined && !from.self ? { routable: await routableSessions(app, e.from) } : {};
|
|
944
|
+
switch (pt.kind) {
|
|
945
|
+
case "msg": {
|
|
946
|
+
// §4.3 "Delivery receipts": the sender asked. Remembered for `p2p receipt` (receipts.ts), which
|
|
947
|
+
// decides what goes back; the event says only that one may (`receipt: true`), never the id.
|
|
948
|
+
const asks = typeof pt.rcpt === "string" && receiptsEnabled(app.env, app.home);
|
|
949
|
+
const main = makeEvent(env, "p2p.message", e.ts, { from, ...sess, text: pt.text, ...(asks ? { receipt: true } : {}), ...routable }, extra);
|
|
950
|
+
const out = [main];
|
|
951
|
+
if (asks)
|
|
952
|
+
await rememberAsked(app, main.id, { id: pt.rcpt, from: e.from, did: e.fdid, ...(toSession !== undefined ? { toSession } : {}) });
|
|
953
|
+
// For a session of this device that has ended (its watch stopped: /exit, or replaced after
|
|
954
|
+
// /clear): also logged as a message for no session, so the user's current session holds it
|
|
955
|
+
// for Deliver (the mod's rule for those) instead of it waiting for a session that won't come
|
|
956
|
+
// back. Same sender, same text, same hold and screen rules; if the session does resume, it
|
|
957
|
+
// still gets the message itself (and this copy isn't shown there).
|
|
958
|
+
if (toSession !== undefined && sessionEnded(app, toSession)) {
|
|
959
|
+
// From another session of ours with a bound: only sessions already within it may hold it, and the
|
|
960
|
+
// one that does takes the bound on (the front end binds it on Deliver: `bound` rides with it).
|
|
961
|
+
const held = from.self ? (bound !== undefined ? { routable: await sessionsWithin(app, bound), bound } : {}) : { routable: await routableSessions(app, e.from) };
|
|
962
|
+
const copy = makeEvent(env, "p2p.message", e.ts, { from, ...sess, text: pt.text, unclaimedFor: toSession, ...(asks ? { receipt: true } : {}), ...held }, {}, "unclaimed");
|
|
963
|
+
out.push(copy);
|
|
964
|
+
if (asks)
|
|
965
|
+
await rememberAsked(app, copy.id, { id: pt.rcpt, from: e.from, did: e.fdid, unclaimedFor: toSession });
|
|
966
|
+
}
|
|
967
|
+
return out;
|
|
968
|
+
}
|
|
969
|
+
case "idle": {
|
|
970
|
+
const reason = pt.reason === "exited" ? "exited" : "idle";
|
|
971
|
+
const subs = await takeSubs(app, e.own, e.sid);
|
|
972
|
+
const out = [makeEvent(env, "p2p.idle", e.ts, { from, ...sess, reason }, extra)];
|
|
973
|
+
for (const s of subs)
|
|
974
|
+
out.push(makeEvent(env, "p2p.idle", e.ts, { from, ...sess, reason }, { own: e.own, sid: e.sid, toSession: s.toSession }, s.toSession));
|
|
975
|
+
return out;
|
|
976
|
+
}
|
|
977
|
+
case "status": {
|
|
978
|
+
const key = sessKey(e.own, e.sid);
|
|
979
|
+
const prev = await app.state.update("peers", (cur = {}) => {
|
|
980
|
+
const old = cur[key];
|
|
981
|
+
if (old && old.ts >= e.ts)
|
|
982
|
+
return { result: { old, newer: false } };
|
|
983
|
+
const rec = { own: e.own, sid: e.sid, did: e.fdid, ts: e.ts, status: pt.status, rule: r.rule, ...(r.viewerRule ? { viewerRule: r.viewerRule } : {}), ...(e.own === app.userId ? { self: true } : {}) };
|
|
984
|
+
return { next: { ...cur, [key]: rec }, result: { old, newer: true } };
|
|
985
|
+
});
|
|
986
|
+
if (!prev.newer)
|
|
987
|
+
return [];
|
|
988
|
+
const out = [makeEvent(env, "p2p.status", e.ts, { from, ...sess, status: displayStatus(pt.status), live: isLive(e.ts, Date.now()) }, extra)];
|
|
989
|
+
if (pt.status.state === "idle" && prev.old?.status.state === "busy") {
|
|
990
|
+
for (const s of await takeSubs(app, e.own, e.sid)) {
|
|
991
|
+
out.push(makeEvent(env, "p2p.idle", e.ts, { from, ...sess, reason: "idle" }, { own: e.own, sid: e.sid, toSession: s.toSession }, s.toSession));
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
return out;
|
|
995
|
+
}
|
|
996
|
+
case "roster":
|
|
997
|
+
return [makeEvent(env, "p2p.roster", e.ts, { from, ...sess }, extra)];
|
|
998
|
+
default: {
|
|
999
|
+
if ("ext" in pt) {
|
|
1000
|
+
// A state kind (§4.3 "Extension state kinds") is stored latest-wins, and is never an event:
|
|
1001
|
+
// not logged, not printed by watch, never toasted or shown to a model.
|
|
1002
|
+
if (isStateEnvelope(app.extensions, pt)) {
|
|
1003
|
+
await onStateEnvelope(app, accepted, pt, from);
|
|
1004
|
+
return [];
|
|
1005
|
+
}
|
|
1006
|
+
const fallback = extensionFallbackText(from.address, pt.fallback);
|
|
1007
|
+
// §4.3: the extension, when installed, validates and renders; it never acts. Without one,
|
|
1008
|
+
// the body is never interpreted (nor kept) and the fallback stands.
|
|
1009
|
+
const r = renderExtension(app.extensions, {
|
|
1010
|
+
kind: pt.kind,
|
|
1011
|
+
v: pt.ext.v,
|
|
1012
|
+
body: pt.ext.body,
|
|
1013
|
+
fallback,
|
|
1014
|
+
from: { userId: from.userId, address: from.address, self: from.self },
|
|
1015
|
+
session: { own: e.own, sid: e.sid, ref },
|
|
1016
|
+
});
|
|
1017
|
+
const data = { from, ...sess, ext: pt.kind, fallback, ...routable };
|
|
1018
|
+
if (r.rendered)
|
|
1019
|
+
data.rendered = r.rendered;
|
|
1020
|
+
if (r.extError)
|
|
1021
|
+
data.extError = r.extError;
|
|
1022
|
+
// Underscore fields stay in the local log for user-initiated actions; `watch` never prints them.
|
|
1023
|
+
if (r.kept)
|
|
1024
|
+
data._kept = r.kept;
|
|
1025
|
+
return [makeEvent(env, "p2p.ext", e.ts, data, extra)];
|
|
1026
|
+
}
|
|
1027
|
+
return [];
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
/**
|
|
1032
|
+
* Binds `sid` to the folders its front end reports (projects.ts sessionDirs: P2P_WORKDIR,
|
|
1033
|
+
* P2P_PROJECT_DIRS, past its cap private) and any more the caller names.
|
|
1034
|
+
*/
|
|
1035
|
+
export async function bindFromEnv(app, sid, extra = [], o = {}) {
|
|
1036
|
+
const { dirs, over } = sessionDirs(app.env);
|
|
1037
|
+
// Past the cap in folders named on the command line too: private, never the first N.
|
|
1038
|
+
const tooMany = extra.length > MAX_SESSION_DIRS;
|
|
1039
|
+
await bindSession(app, sid, [...dirs, ...extra.slice(0, MAX_SESSION_DIRS)], { ...(o.person ? { person: true } : {}), ...(over || tooMany || o.over ? { over: true } : {}) });
|
|
1040
|
+
}
|
|
1041
|
+
/** Whether a ceiling is within a bound (narrower or equal): private always is. */
|
|
1042
|
+
function within(c, b) {
|
|
1043
|
+
if (c.kind === "private")
|
|
1044
|
+
return true;
|
|
1045
|
+
if (c.kind === "none" || b === "private")
|
|
1046
|
+
return false;
|
|
1047
|
+
return c.circles.every((x) => b.circles.includes(x)) && c.people.every((x) => b.people.includes(x));
|
|
1048
|
+
}
|
|
1049
|
+
/** This device's live sessions already within a bound (and the person's own terminal session): who may hold an own-session message that carries it. */
|
|
1050
|
+
export async function sessionsWithin(app, b, now = Date.now()) {
|
|
1051
|
+
const peers = (await app.state.get("peers")) ?? {};
|
|
1052
|
+
const out = new Set([PERSON_SESSION]);
|
|
1053
|
+
for (const p of Object.values(peers)) {
|
|
1054
|
+
if (p.own !== app.userId || p.did !== app.did || !isLive(p.ts, now) || out.has(p.sid))
|
|
1055
|
+
continue;
|
|
1056
|
+
if (within(await sessionCeiling(app, p.sid), b))
|
|
1057
|
+
out.add(p.sid);
|
|
1058
|
+
}
|
|
1059
|
+
return [...out].sort();
|
|
1060
|
+
}
|
|
1061
|
+
/** `p2p session bound`: a front end binds the session that took an own-session message to that message's bound (sticky). */
|
|
1062
|
+
export async function bindBound(app, sid, bound) {
|
|
1063
|
+
checkSid(sid, "sid");
|
|
1064
|
+
let b;
|
|
1065
|
+
try {
|
|
1066
|
+
b = parseBound(bound, "bound");
|
|
1067
|
+
}
|
|
1068
|
+
catch {
|
|
1069
|
+
throw new CliError("usage", 'bound must be "private" or {circles, people}');
|
|
1070
|
+
}
|
|
1071
|
+
await bindSession(app, sid, [], { constraint: b });
|
|
1072
|
+
return sessionProjectView(app, sid);
|
|
1073
|
+
}
|
|
1074
|
+
/**
|
|
1075
|
+
* What a session of ours may reach, for a message to another session of ours (`bound`, cap
|
|
1076
|
+
* projects.v1): undefined when it has no ceiling (the person's own session, one never bound).
|
|
1077
|
+
*/
|
|
1078
|
+
async function boundOf(app, sid) {
|
|
1079
|
+
const c = await sessionCeiling(app, sid);
|
|
1080
|
+
if (c.kind === "none")
|
|
1081
|
+
return undefined;
|
|
1082
|
+
return c.kind === "private" ? "private" : { circles: c.circles, people: c.people };
|
|
1083
|
+
}
|
|
1084
|
+
/**
|
|
1085
|
+
* A message from a bounded session to another session of ours carries its bound (laundering
|
|
1086
|
+
* through your own sessions, projects.ts). One on another device whose client can't honour it
|
|
1087
|
+
* (its live status doesn't advertise projects.v1) is refused here; the field is critical, so an
|
|
1088
|
+
* older client that gets one anyway rejects it.
|
|
1089
|
+
*/
|
|
1090
|
+
async function ownBound(app, fromSession, target, userId) {
|
|
1091
|
+
if (userId !== app.userId || target.own !== app.userId)
|
|
1092
|
+
return {};
|
|
1093
|
+
const bound = await boundOf(app, fromSession);
|
|
1094
|
+
if (bound === undefined)
|
|
1095
|
+
return {};
|
|
1096
|
+
if (target.did && target.did !== app.did) {
|
|
1097
|
+
const rec = (await app.state.get("peers"))?.[sessKey(target.own, target.sid)];
|
|
1098
|
+
const caps = rec ? (displayStatus(rec.status).caps ?? []) : [];
|
|
1099
|
+
if (!caps.includes(CAP_PROJECTS)) {
|
|
1100
|
+
throw new CliError("not_shared", `session ${fromSession} works in a project with limits, and your session ${target.sid} runs on another device whose client doesn't keep project boundaries: update Peer2Peer there first (docs/compatibility.md)`, { delivered: false });
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
return { bound, crit: ["bound"] };
|
|
1104
|
+
}
|
|
1105
|
+
/** Whether a session of ours may reach `user` (projects.ts): the same rule its sends follow. */
|
|
1106
|
+
export async function mayReach(app, sid, user) {
|
|
1107
|
+
return assertMayReach(app, sid, user).then(() => true, () => false);
|
|
1108
|
+
}
|
|
1109
|
+
/**
|
|
1110
|
+
* The local sessions a message for no session may be held in: this device's live sessions whose
|
|
1111
|
+
* projects reach the sender, and the person's own terminal session. Every other session's watch
|
|
1112
|
+
* never shows it (watch.ts eventFor), and the mod picks its holder among these.
|
|
1113
|
+
*/
|
|
1114
|
+
export async function routableSessions(app, sender, now = Date.now()) {
|
|
1115
|
+
const peers = (await app.state.get("peers")) ?? {};
|
|
1116
|
+
const out = new Set([PERSON_SESSION]);
|
|
1117
|
+
for (const p of Object.values(peers)) {
|
|
1118
|
+
if (p.own !== app.userId || p.did !== app.did || !isLive(p.ts, now) || out.has(p.sid))
|
|
1119
|
+
continue;
|
|
1120
|
+
if ((await sessionCeiling(app, p.sid)).kind === "none")
|
|
1121
|
+
continue;
|
|
1122
|
+
if (await mayReach(app, p.sid, sender))
|
|
1123
|
+
out.add(p.sid);
|
|
1124
|
+
}
|
|
1125
|
+
return [...out].sort();
|
|
1126
|
+
}
|
|
1127
|
+
async function takeSubs(app, own, sid) {
|
|
1128
|
+
return app.state.update("subs", (cur = []) => {
|
|
1129
|
+
const hit = cur.filter((s) => s.own === own && s.sid === sid);
|
|
1130
|
+
return hit.length === 0 ? { result: [] } : { next: cur.filter((s) => !(s.own === own && s.sid === sid)), result: hit };
|
|
1131
|
+
});
|
|
1132
|
+
}
|
|
1133
|
+
/** Subscriptions older than an hour end with `p2p.idle {reason: "expired"}` (v1 semantics). */
|
|
1134
|
+
export async function expireSubs(app, now = Date.now()) {
|
|
1135
|
+
const gone = await app.state.update("subs", (cur = []) => {
|
|
1136
|
+
const old = cur.filter((s) => now - s.at > IDLE_SUB_TTL_MS);
|
|
1137
|
+
return old.length === 0 ? { result: [] } : { next: cur.filter((s) => now - s.at <= IDLE_SUB_TTL_MS), result: old };
|
|
1138
|
+
});
|
|
1139
|
+
const events = [];
|
|
1140
|
+
for (const s of gone) {
|
|
1141
|
+
events.push({
|
|
1142
|
+
id: `p2p.idle:exp:${s.own}:${s.sid}:${s.toSession}:${s.at}`,
|
|
1143
|
+
at: now,
|
|
1144
|
+
kind: "p2p.idle",
|
|
1145
|
+
own: s.own,
|
|
1146
|
+
sid: s.sid,
|
|
1147
|
+
toSession: s.toSession,
|
|
1148
|
+
data: { from: { userId: s.own, did: "", address: await app.addressOf(s.own), self: s.own === app.userId }, own: s.own, sid: s.sid, ref: sessionRef(s.own, s.sid), reason: "expired" },
|
|
1149
|
+
});
|
|
1150
|
+
}
|
|
1151
|
+
await app.state.addEvents(events);
|
|
1152
|
+
}
|