@peer2peer/cli 0.1.0 → 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.
package/dist/receipts.js CHANGED
@@ -125,12 +125,14 @@ export async function sendReceipt(app, o) {
125
125
  return { sent: false, reason: "not-yours" };
126
126
  // A private session (shared with nobody) sends none: one would tell the sender it exists. Nor does
127
127
  // the copy of a private ended session's message. A session with no roster here counts as private.
128
+ // Except to this user's own sessions (another device, or this one): they list it anyway, and the
129
+ // receipt is how one of them learns its message waits for Deliver.
128
130
  const sessions = (await app.state.get("sessions")) ?? {};
129
131
  const isPrivate = (sid) => {
130
132
  const doc = sessions[sid];
131
133
  return !doc || (doc.vis === "private" && doc.parts.length === 0);
132
134
  };
133
- if (isPrivate(o.fromSession) || (asked.unclaimedFor !== undefined && isPrivate(asked.unclaimedFor)))
135
+ if (asked.from !== app.userId && (isPrivate(o.fromSession) || (asked.unclaimedFor !== undefined && isPrivate(asked.unclaimedFor))))
134
136
  return { sent: false, reason: "private" };
135
137
  const key = `${asked.from}|${asked.id}`;
136
138
  const verdict = await withDoc(app, (d, now) => {
@@ -1,6 +1,6 @@
1
1
  import { type AcceptedMessageV3, type ProjectBound, type StatusAgent, type StatusBody } from "@peer2peer/core/v3";
2
2
  import type { App, Delivery } from "./app.js";
3
- import { type SessionProjectView } from "./projects.js";
3
+ import { type OverWhy, type SessionProjectView } from "./projects.js";
4
4
  import { type ExtSendResult } from "./extensions.js";
5
5
  import { type NewEvent } from "./inbound.js";
6
6
  import { type PeerStatusRec, type SessionDoc } from "./state.js";
@@ -120,8 +120,12 @@ export interface StatusOpts {
120
120
  * project for the rest of its life (projects.ts), which can only narrow who sees it.
121
121
  */
122
122
  projectDirs?: string[];
123
- /** The front end dropped folders past its cap (`--project-dirs-over`): private. */
124
- projectDirsOver?: boolean;
123
+ /**
124
+ * The front end dropped folders past its cap, or couldn't resolve a path (`--project-dirs-over`):
125
+ * private. A list says why (projects.ts OverWhy: `--project-dirs-over=unresolved,folders`); `true`
126
+ * is an older front end's bare flag.
127
+ */
128
+ projectDirsOver?: boolean | string[];
125
129
  /**
126
130
  * The session's subagents (`--agents-json`), as the caller has them: entries
127
131
  * are normalized (sanitized, capped, ordered, trimmed), never trusted as is.
@@ -231,7 +235,7 @@ export interface SendOpts {
231
235
  /** Directories the sending session works in besides its working directory (see StatusOpts.projectDirs). */
232
236
  projectDirs?: string[];
233
237
  /** See StatusOpts.projectDirsOver. */
234
- projectDirsOver?: boolean;
238
+ projectDirsOver?: boolean | string[];
235
239
  /**
236
240
  * The person at their own terminal (`p2p send` typed with no --from-session, `p2p tui`): their
237
241
  * session is theirs, never bound to a project. Set only by those two paths, never from a flag.
@@ -285,6 +289,17 @@ export declare function parseTarget(to: string): {
285
289
  * refused as before (not_found), so a sender never queues into one long gone.
286
290
  */
287
291
  export declare const OFFLINE_TARGET_MS: number;
292
+ /** How long a same-device send's record (Docs.localSends) is kept: as long as a relay keeps the envelope. */
293
+ export declare const LOCAL_SEND_TTL_MS: number;
294
+ /** At most this many same-device send records; the oldest go first. */
295
+ export declare const LOCAL_SENDS_MAX = 4096;
296
+ /** How long after a bounded session's text reached `tui` a send from there to someone else is warned about. */
297
+ export declare const TUI_TAINT_MS: number;
298
+ /**
299
+ * A warning (never a refusal) for the person sending from their own session `tui` to someone else
300
+ * after a message from a bounded session of theirs reached it: they may be passing its text on.
301
+ */
302
+ export declare function tuiTaintNote(app: App, toUserId: string, now?: number): Promise<string | undefined>;
288
303
  /**
289
304
  * A send by a person at a terminal (the `tui` session: `p2p send` with no --from-session, or `p2p tui`):
290
305
  * a recipient who isn't in the session's audience is added to its roster first, so the message can
@@ -322,7 +337,7 @@ export declare function onSessionEnvelope(app: App, env: string, r: AcceptedMess
322
337
  */
323
338
  export declare function bindFromEnv(app: App, sid: string, extra?: readonly string[], o?: {
324
339
  person?: boolean;
325
- over?: boolean;
340
+ over?: OverWhy[];
326
341
  }): Promise<void>;
327
342
  /** 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. */
328
343
  export declare function sessionsWithin(app: App, b: ProjectBound, now?: number): Promise<string[]>;
package/dist/sessions.js CHANGED
@@ -21,12 +21,13 @@ import { enqueue, flushOutbox, OUTBOX_RETRYABLE, OUTBOX_TTL_MS, retryable } from
21
21
  import { basename, dirname, resolve as resolvePath } from "node:path";
22
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
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";
24
+ import { assertMayReach, bindSession, ceilingAudience, defaultCircleNotice, friendIds, PERSON_SESSION, sessionBinding, agentContext, sessionCeiling, sessionProjectView, sessionDirs, sessionWorkdir, MAX_SESSION_DIRS, overWhys, privateRemedy, shareHint, } from "./projects.js";
25
25
  import { renderExtension } from "./extensions.js";
26
26
  import { fromOf, makeEvent } from "./inbound.js";
27
27
  import { receiptsEnabled, statusCapsEnabled } from "./config.js";
28
28
  import { CAP_PROJECTS, CLI_CAPS, protoMinor, supportsIn } from "./features.js";
29
29
  import { asksReceipts, newReceiptId, rememberAsked, rememberWanted } from "./receipts.js";
30
+ import { recordSent } from "./history.js";
30
31
  import { sessKey } from "./state.js";
31
32
  import { isStateEnvelope, liveStates, onStateEnvelope, stateKindCaps, stateSummaries } from "./xstate.js";
32
33
  /** Session ids: what Claude Code and Codex use (UUIDs and the like). */
@@ -261,7 +262,10 @@ export async function roster(app, sid, opts) {
261
262
  const names = Object.values((await sessionBinding(app, sid))?.projects ?? {}).map((p) => p.name);
262
263
  const ceiling = ctx.ceiling;
263
264
  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
+ const remedy = ceiling.kind === "private" ? privateRemedy(ceiling.causes, ceiling.blocking?.length ? ceiling.blocking : names) : shareHint(names);
266
+ 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}: ${remedy}`, {
267
+ project: { names, policy: ceiling.kind, ...(ceiling.kind === "private" ? { causes: ceiling.causes } : {}) },
268
+ });
265
269
  };
266
270
  if (opts.circle !== undefined && circle !== undefined && (ceiling.kind !== "shared" || !ceiling.circles.includes(circle)))
267
271
  deny(`with circle ${circle}`);
@@ -560,7 +564,7 @@ export async function sendStatus(app, o) {
560
564
  // a path through a symlink): each binds its project.
561
565
  const work = sessionWorkdir(app.env);
562
566
  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 } : {}) });
567
+ await bindFromEnv(app, sid, [...(o.projectDirs ?? []), ...fileDirs], { ...(o.projectDirsOver !== undefined && o.projectDirsOver !== false ? { over: overOf(o.projectDirsOver) } : {}) });
564
568
  const prev = (await app.state.get("peers"))?.[sessKey(app.userId, sid)];
565
569
  const before = (await app.state.get("sessions"))?.[sid];
566
570
  const warnings = [];
@@ -622,6 +626,10 @@ export async function sendStatus(app, o) {
622
626
  // This device keeps the full status: its own `ls` and ExtContext.ownStatus see the agents.
623
627
  const rec = { own: app.userId, sid, did: app.did, ts: Date.now(), status, self: true };
624
628
  await app.state.update("peers", (cur = {}) => ({ next: { ...cur, [sessKey(app.userId, sid)]: rec }, result: undefined }));
629
+ // Another session here asked to hear when this one next goes idle (`send --notify-when-idle` to a
630
+ // session on this device): its statuses never come back here as envelopes, so it is noticed here.
631
+ if (status.state === "idle" && prev?.status.state === "busy")
632
+ await localIdle(app, sid, rec.ts);
625
633
  // `bound`: the folders the front end passed are bound for good (it can stop sending them).
626
634
  return { status, roster: await rosterView(app, sess), delivered, failed, ...(warnings.length > 0 ? { warnings } : {}), project: await sessionProjectView(app, sid), bound: true };
627
635
  }
@@ -724,15 +732,27 @@ export const OFFLINE_TARGET_MS = 24 * 3600 * 1000;
724
732
  /**
725
733
  * Where a message to `toArg` goes: one of their live sessions, or our own
726
734
  * session `fromSession` when its roster lets them in (see the header).
735
+ *
736
+ * Our own sessions on this device are reached only by name (`<you> [ref]`, `<you>/<sid>`), never
737
+ * by a bare `--to <you>`, and never `fromSession` itself (`self_send`). The message is sealed to
738
+ * this device and goes through a relay like one to our other devices, so the receive side applies
739
+ * the same checks: signature, replay, the receiving session's roster and project bound.
727
740
  */
728
741
  async function resolveTarget(app, fromSession, toArg) {
729
742
  const { user, pick } = parseTarget(toArg);
730
743
  const userId = await app.resolveUser(user);
731
744
  if (await app.store.isBlocked(userId))
732
745
  throw new CliError("blocked", "you blocked that user");
746
+ // A session never messages itself (a loop with nothing in between): refused, never "not found".
747
+ if (userId === app.userId && pick !== undefined && (pick === fromSession || pick === sessionRef(app.userId, fromSession))) {
748
+ throw new CliError("self_send", `that is session ${fromSession} itself: a session can't send to itself`, { delivered: false });
749
+ }
733
750
  const peers = (await app.state.get("peers")) ?? {};
734
751
  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));
752
+ // Our own sessions on this device are candidates only when one is named (`[ref]` or `/sid`): a bare
753
+ // `--to <you>` still means your other devices' sessions, never every session here at once.
754
+ const eligible = (p) => p.own === userId && !(p.own === app.userId && (p.sid === fromSession || (p.did === app.did && pick === undefined))) && (!pick || p.sid === pick || sessionRef(p.own, p.sid) === pick);
755
+ const live = Object.values(peers).filter((p) => eligible(p) && isLive(p.ts, now));
736
756
  let target;
737
757
  let offlineSince;
738
758
  // Not live now, but seen recently (a dropped connection, a laptop asleep): the same sessions a
@@ -740,10 +760,7 @@ async function resolveTarget(app, fromSession, toArg) {
740
760
  const recent = live.length > 0
741
761
  ? []
742
762
  : 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))
763
+ .filter((p) => eligible(p) && now - p.ts <= OFFLINE_TARGET_MS)
747
764
  .sort((a, b) => b.ts - a.ts);
748
765
  if (live.length === 1)
749
766
  target = { own: userId, sid: live[0].sid, did: live[0].did };
@@ -783,6 +800,57 @@ async function rosterFor(app, target) {
783
800
  const here = target.own === app.userId && (target.did === undefined || target.did === app.did);
784
801
  return here ? (await getSession(app, target.sid)).jws : (await app.store.getRoster(target.own, target.sid))?.jws;
785
802
  }
803
+ /** How long a same-device send's record (Docs.localSends) is kept: as long as a relay keeps the envelope. */
804
+ export const LOCAL_SEND_TTL_MS = 7 * 86_400_000 + 600_000;
805
+ /** At most this many same-device send records; the oldest go first. */
806
+ export const LOCAL_SENDS_MAX = 4096;
807
+ /**
808
+ * For a message to another session on this device: before the copy goes out, this device notes which
809
+ * session sent it and whether the person did (Docs.localSends). Local only: nothing changes on the
810
+ * wire, and the receive side (this same device) reads it by the envelope's (sid, seq).
811
+ */
812
+ function localSend(app, target, fromSession, person) {
813
+ if (target.own !== app.userId || target.did !== app.did)
814
+ return {};
815
+ const via = person || fromSession === PERSON_SESSION ? "person" : "agent";
816
+ return {
817
+ beforeSend: async (copies) => {
818
+ const now = Date.now();
819
+ await app.state.update("localSends", (cur = {}) => {
820
+ const kept = Object.entries(cur).filter(([, v]) => now - v.at < LOCAL_SEND_TTL_MS);
821
+ for (const c of copies)
822
+ if (c.did === app.did)
823
+ kept.push([`${target.sid}|${c.seq}`, { from: fromSession, via, at: now }]);
824
+ return { next: Object.fromEntries(kept.sort((a, b) => a[1].at - b[1].at).slice(-LOCAL_SENDS_MAX)), result: undefined };
825
+ });
826
+ },
827
+ };
828
+ }
829
+ /**
830
+ * What an own-session message's event says about where it came from (sessions on this device only):
831
+ * `via` "person" for the person's own terminal session, else "agent" (also for every other device
832
+ * of yours, which this device can't tell apart: fail closed); `fromRef` names the sending session
833
+ * here. Whether `p2p own-agents` lets it through is never stamped here: the front end asks at
834
+ * delivery time (`p2p own-agents check <did>`).
835
+ */
836
+ async function ownOrigin(app, e) {
837
+ const local = e.fdid === app.did ? (await app.state.get("localSends"))?.[`${e.sid}|${e.seq}`] : undefined;
838
+ return { via: local?.via ?? "agent", ...(local ? { fromRef: sessionRef(app.userId, local.from) } : {}) };
839
+ }
840
+ /** How long after a bounded session's text reached `tui` a send from there to someone else is warned about. */
841
+ export const TUI_TAINT_MS = 24 * 3600 * 1000;
842
+ /**
843
+ * A warning (never a refusal) for the person sending from their own session `tui` to someone else
844
+ * after a message from a bounded session of theirs reached it: they may be passing its text on.
845
+ */
846
+ export async function tuiTaintNote(app, toUserId, now = Date.now()) {
847
+ if (toUserId === app.userId)
848
+ return undefined;
849
+ const t = await app.state.get("tuiTaint");
850
+ if (!t || now - t.at > TUI_TAINT_MS)
851
+ return undefined;
852
+ return `a ${t.bound === "private" ? "private" : "project-bounded"} session of yours sent text to this terminal session lately: check you aren't passing it on`;
853
+ }
786
854
  /**
787
855
  * A send by a person at a terminal (the `tui` session: `p2p send` with no --from-session, or `p2p tui`):
788
856
  * a recipient who isn't in the session's audience is added to its roster first, so the message can
@@ -815,7 +883,7 @@ export async function sendMessage(app, o) {
815
883
  if (o.text === "" && !o.notifyWhenIdle)
816
884
  throw new CliError("usage", "nothing to send (give text, or --notify-when-idle)");
817
885
  // 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 } : {}) });
886
+ await bindFromEnv(app, fromSession, o.projectDirs ?? [], { person: o.person === true, ...(o.projectDirsOver !== undefined && o.projectDirsOver !== false ? { over: overOf(o.projectDirsOver) } : {}) });
819
887
  // This device can't reach any of its relays: the message can still be sealed and kept in the
820
888
  // outbox (outbox.ts) for `watch` to send once it can.
821
889
  let offline = false;
@@ -843,7 +911,7 @@ export async function sendMessage(app, o) {
843
911
  const plaintext = { text: o.text, ...(rcpt ? { rcpt } : {}), ...(rosterJws ? { roster: rosterJws } : {}), ...(o.person ? {} : await ownBound(app, fromSession, target, userId)) };
844
912
  if (rcpt)
845
913
  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] } : {});
914
+ d = await app.deliver(userId, "msg", target, plaintext, userId === app.userId && target.did ? { onlyDevices: [target.did], ...localSend(app, target, fromSession, o.person === true) } : {});
847
915
  const unsent = d.unsent ?? [];
848
916
  if (d.relays.length === 0 && !retryable(unsent)) {
849
917
  throw new CliError("undelivered", `delivered via 0 relays${d.errors?.length ? ` (${[...new Set(d.errors.map((e) => e.code))].join(", ")})` : ""}`, { delivered: false, to });
@@ -867,6 +935,9 @@ export async function sendMessage(app, o) {
867
935
  : d && offlineSince !== undefined
868
936
  ? { queued: true, state: "offline", lastSeen: offlineSince, expiresAt: Date.now() + OUTBOX_TTL_MS }
869
937
  : {};
938
+ // Message history (history.ts): what this session sent, kept on this device only.
939
+ if (d)
940
+ await recordSent(app, { fromSession, to, text: o.text, state: "state" in queued ? queued.state : "sent" });
870
941
  return {
871
942
  ...(o.person ? {} : { bound: true }),
872
943
  // Accepted by a relay (it stores ciphertext for its session for 7 days), or not yet.
@@ -904,13 +975,15 @@ export async function sendExtension(app, o) {
904
975
  await assertMayReach(app, fromSession, userId, { address: to.address });
905
976
  const rosterJws = await rosterFor(app, target);
906
977
  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] } : {});
978
+ const d = await app.deliver(userId, o.kind, target, plaintext, userId === app.userId && target.did ? { onlyDevices: [target.did], ...localSend(app, target, fromSession, false) } : {});
908
979
  if (d.relays.length === 0) {
909
980
  throw new CliError("undelivered", `delivered via 0 relays${d.errors?.length ? ` (${[...new Set(d.errors.map((e) => e.code))].join(", ")})` : ""}`, { delivered: false, to });
910
981
  }
911
982
  if (target.own !== app.userId) {
912
983
  await app.state.update("spoke", (cur = {}) => ({ next: { ...cur, [sessKey(target.own, target.sid)]: fromSession }, result: undefined }));
913
984
  }
985
+ // Message history: an extension kind as its one-line fallback, never its body.
986
+ await recordSent(app, { fromSession, to, text: o.fallback, ext: o.kind });
914
987
  return { delivered: true, to, relays: d.relays.length, devices: d.devices, kind: o.kind, bytes, bound: true };
915
988
  }
916
989
  // ---------------------------------------------------------------------------
@@ -937,6 +1010,12 @@ export async function onSessionEnvelope(app, env, r) {
937
1010
  if (carries && from.self && bound !== undefined && toSession !== undefined && toSession !== PERSON_SESSION) {
938
1011
  await bindSession(app, toSession, [], { constraint: bound, inbound: true });
939
1012
  }
1013
+ // The person's own session is never bound: it only remembers that a bounded session's text reached it,
1014
+ // so `p2p tui` can warn before the person passes it on.
1015
+ if (carries && from.self && bound !== undefined && toSession === PERSON_SESSION) {
1016
+ await app.state.update("tuiTaint", () => ({ next: { at: Date.now(), bound: bound === "private" ? "private" : "shared" }, result: undefined }));
1017
+ }
1018
+ const origin = carries && from.self ? await ownOrigin(app, e) : {};
940
1019
  const sess = { own: e.own, sid: e.sid, ref, rule: r.rule, ...(r.viewerRule ? { viewerRule: r.viewerRule } : {}) };
941
1020
  const extra = { own: e.own, sid: e.sid, ...(toSession ? { toSession } : {}) };
942
1021
  // Named for no session of ours: which local sessions may hold it (watch shows it only to those).
@@ -946,7 +1025,7 @@ export async function onSessionEnvelope(app, env, r) {
946
1025
  // §4.3 "Delivery receipts": the sender asked. Remembered for `p2p receipt` (receipts.ts), which
947
1026
  // decides what goes back; the event says only that one may (`receipt: true`), never the id.
948
1027
  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);
1028
+ const main = makeEvent(env, "p2p.message", e.ts, { from, ...sess, ...origin, text: pt.text, ...(asks ? { receipt: true } : {}), ...routable }, extra);
950
1029
  const out = [main];
951
1030
  if (asks)
952
1031
  await rememberAsked(app, main.id, { id: pt.rcpt, from: e.from, did: e.fdid, ...(toSession !== undefined ? { toSession } : {}) });
@@ -959,7 +1038,7 @@ export async function onSessionEnvelope(app, env, r) {
959
1038
  // From another session of ours with a bound: only sessions already within it may hold it, and the
960
1039
  // one that does takes the bound on (the front end binds it on Deliver: `bound` rides with it).
961
1040
  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");
1041
+ const copy = makeEvent(env, "p2p.message", e.ts, { from, ...sess, ...origin, text: pt.text, unclaimedFor: toSession, ...(asks ? { receipt: true } : {}), ...held }, {}, "unclaimed");
963
1042
  out.push(copy);
964
1043
  if (asks)
965
1044
  await rememberAsked(app, copy.id, { id: pt.rcpt, from: e.from, did: e.fdid, unclaimedFor: toSession });
@@ -1014,7 +1093,7 @@ export async function onSessionEnvelope(app, env, r) {
1014
1093
  from: { userId: from.userId, address: from.address, self: from.self },
1015
1094
  session: { own: e.own, sid: e.sid, ref },
1016
1095
  });
1017
- const data = { from, ...sess, ext: pt.kind, fallback, ...routable };
1096
+ const data = { from, ...sess, ...origin, ext: pt.kind, fallback, ...routable };
1018
1097
  if (r.rendered)
1019
1098
  data.rendered = r.rendered;
1020
1099
  if (r.extError)
@@ -1033,10 +1112,17 @@ export async function onSessionEnvelope(app, env, r) {
1033
1112
  * P2P_PROJECT_DIRS, past its cap private) and any more the caller names.
1034
1113
  */
1035
1114
  export async function bindFromEnv(app, sid, extra = [], o = {}) {
1036
- const { dirs, over } = sessionDirs(app.env);
1115
+ const { dirs, why } = sessionDirs(app.env);
1037
1116
  // 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 } : {}) });
1117
+ const over = new Set([...why, ...(o.over ?? [])]);
1118
+ if (extra.length > MAX_SESSION_DIRS)
1119
+ over.add("folders");
1120
+ await bindSession(app, sid, [...dirs, ...extra.slice(0, MAX_SESSION_DIRS)], { ...(o.person ? { person: true } : {}), ...(over.size > 0 ? { over: [...over] } : {}) });
1121
+ }
1122
+ /** A front end's `--project-dirs-over` as reasons: a bare flag (an older front end) is `front`. */
1123
+ function overOf(v) {
1124
+ const out = v === true ? ["front"] : overWhys(Array.isArray(v) ? v.flatMap((x) => String(x).split(",")) : []);
1125
+ return out.length > 0 ? out : ["front"];
1040
1126
  }
1041
1127
  /** Whether a ceiling is within a bound (narrower or equal): private always is. */
1042
1128
  function within(c, b) {
@@ -1124,6 +1210,15 @@ export async function routableSessions(app, sender, now = Date.now()) {
1124
1210
  }
1125
1211
  return [...out].sort();
1126
1212
  }
1213
+ /** `p2p.idle` for the subscriptions of this device's sessions to `sid`, another session on this device. */
1214
+ async function localIdle(app, sid, ts) {
1215
+ const subs = await takeSubs(app, app.userId, sid);
1216
+ if (subs.length === 0)
1217
+ return;
1218
+ const from = { userId: app.userId, did: app.did, address: await app.addressOf(app.userId), self: true };
1219
+ const ref = sessionRef(app.userId, sid);
1220
+ await app.state.addEvents(subs.map((s) => ({ id: `p2p.idle:local:${sid}:${s.toSession}:${ts}`, at: ts, kind: "p2p.idle", own: app.userId, sid, toSession: s.toSession, data: { from, own: app.userId, sid, ref, reason: "idle" } })));
1221
+ }
1127
1222
  async function takeSubs(app, own, sid) {
1128
1223
  return app.state.update("subs", (cur = []) => {
1129
1224
  const hit = cur.filter((s) => s.own === own && s.sid === sid);
package/dist/state.d.ts CHANGED
@@ -2,6 +2,7 @@ import type { OutboxDoc } from "./outbox.js";
2
2
  import type { ReceiptsDoc } from "./receipts.js";
3
3
  import type { RelayInfoRec } from "./relay-info.js";
4
4
  import type { ProjectsDoc, SessionProjectsDoc } from "./projects.js";
5
+ import type { GraphMemoryDoc } from "./graph-memory.js";
5
6
  import { type LockOptions } from "@peer2peer/core/v3/node";
6
7
  import type { DocBackend, RotationStatement, StatusBody } from "@peer2peer/core/v3";
7
8
  import { type Progress } from "./progress.js";
@@ -101,6 +102,14 @@ export interface XStateSenderDoc {
101
102
  n: number;
102
103
  };
103
104
  }
105
+ /** One same-device send (Docs.localSends). */
106
+ export interface LocalSend {
107
+ /** The sending session. */
108
+ from: string;
109
+ /** `person`: the person's own terminal session (`tui`, or a send as them); `agent`: any other session. */
110
+ via: "person" | "agent";
111
+ at: number;
112
+ }
104
113
  export interface PeerStatusRec {
105
114
  own: string;
106
115
  sid: string;
@@ -380,6 +389,17 @@ type Docs = {
380
389
  xstateSent: Record<string, number>;
381
390
  /** Sealed messages no relay accepted yet, retried by `watch` (outbox.ts). */
382
391
  outbox: OutboxDoc;
392
+ /**
393
+ * Messages one session of this device sent to another session of this device, by `<target sid>|<seq>`:
394
+ * which session sent it and whether the person did (sessions.ts). Local only, never on the wire: the
395
+ * receiving side (this same device) reads it to frame the message and to apply the hold rule.
396
+ */
397
+ localSends: Record<string, LocalSend>;
398
+ /** When a message from a bounded session of yours last reached the person's own session (`tui`): for a warning there. */
399
+ tuiTaint: {
400
+ at: number;
401
+ bound: "private" | "shared";
402
+ };
383
403
  /** Delivery receipts (receipts.ts, §4.3). */
384
404
  receipts: ReceiptsDoc;
385
405
  /** When each (sender, kind) of an envelope this version doesn't know was last noticed (unknown-kinds.ts). */
@@ -390,6 +410,12 @@ type Docs = {
390
410
  projects: ProjectsDoc;
391
411
  /** Which projects each session has worked in (projects.ts), by sid: sticky until the session ends. */
392
412
  sessionProjects: SessionProjectsDoc;
413
+ /** When this device showed the one-time notice that new installs turn the Ix extension on (ix-local.ts). */
414
+ ixNotice: {
415
+ at: number;
416
+ };
417
+ /** Graph memory (graph-memory.ts): this device's sessions' context waiting for the local Ix graph, and counters. */
418
+ graphMemory: GraphMemoryDoc;
393
419
  };
394
420
  export declare const sessKey: (own: string, sid: string) => string;
395
421
  /** Events older than this, or beyond the count cap, are pruned. */
package/dist/state.js CHANGED
@@ -34,6 +34,9 @@
34
34
  // relayInfo the relays' /.well-known/p2p-relay.json (features and frames), as last fetched
35
35
  // projects project policies (projects.ts): shared with circles and people, or private (the default)
36
36
  // sessionProjects the projects each session worked in (projects.ts), by sid
37
+ // ixNotice when the one-time "Ix on by default" notice was shown (ix-local.ts)
38
+ // graphMemory graph memory (graph-memory.ts): what was recorded of each own session, the bounded queue, counters
39
+ // history, history-<n> message history (history.ts): sealed with the key in history.key, never plaintext
37
40
  import { join } from "node:path";
38
41
  import { FileDocBackend } from "@peer2peer/core/v3/node";
39
42
  import { debug, step } from "./progress.js";
@@ -62,6 +62,10 @@ export interface MessageRow {
62
62
  lastSeen?: number;
63
63
  receiptId?: string;
64
64
  note?: string;
65
+ /** From the message history (history.ts): kept past this run, up to its retention. */
66
+ fromHistory?: true;
67
+ /** The person's own inbox (this TUI's session, or no session) rather than one of their agent sessions'. */
68
+ inbox?: boolean;
65
69
  }
66
70
  export interface RelayRow {
67
71
  url: string;
@@ -153,6 +157,8 @@ export interface Ui {
153
157
  error?: boolean;
154
158
  };
155
159
  busy?: string;
160
+ /** Messages screen: only your inbox (this TUI's session, or none), not your agent sessions' too. */
161
+ inboxOnly?: boolean;
156
162
  }
157
163
  export type Effect = {
158
164
  kind: "quit";
@@ -206,7 +212,7 @@ export type PeopleItem = {
206
212
  export declare function peopleItems(d: Data): PeopleItem[];
207
213
  /** Send targets: live sessions first (not this TUI's own), then each person (their one session, or our session). */
208
214
  export declare function sendTargets(d: Data): SendTarget[];
209
- export declare function messagesSorted(d: Data): MessageRow[];
215
+ export declare function messagesSorted(d: Data, ui?: Pick<Ui, "inboxOnly">): MessageRow[];
210
216
  export declare function clampSel(ui: Ui, d: Data): Ui;
211
217
  /** One key press. Returns the next ui and, at most, one effect. */
212
218
  export declare function onKey(ui0: Ui, d: Data, key: Key, page?: number): {
package/dist/tui/model.js CHANGED
@@ -34,8 +34,8 @@ export function sendTargets(d) {
34
34
  }
35
35
  return [...sessions, ...people];
36
36
  }
37
- export function messagesSorted(d) {
38
- return [...d.messages].sort((a, b) => b.at - a.at);
37
+ export function messagesSorted(d, ui) {
38
+ return d.messages.filter((m) => !ui?.inboxOnly || m.inbox !== false).sort((a, b) => b.at - a.at);
39
39
  }
40
40
  function count(ui, d) {
41
41
  switch (ui.screen) {
@@ -44,7 +44,7 @@ function count(ui, d) {
44
44
  case "held":
45
45
  return d.held.length;
46
46
  case "messages":
47
- return d.messages.length;
47
+ return messagesSorted(d, ui).length;
48
48
  case "send":
49
49
  return sendTargets(d).length;
50
50
  case "health":
@@ -227,7 +227,11 @@ export function onKey(ui0, d, key, page = 10) {
227
227
  return { ui };
228
228
  }
229
229
  case "messages": {
230
- const msg = messagesSorted(d)[sel];
230
+ if (key.ch === "h") {
231
+ const next = clampSel({ ...ui, inboxOnly: !ui.inboxOnly }, d);
232
+ return { ui: flash(next, next.inboxOnly ? "Your inbox only: messages to you and this window's session." : "Every session on this device: your inbox and your agent sessions' messages.") };
233
+ }
234
+ const msg = messagesSorted(d, ui)[sel];
231
235
  if (!msg)
232
236
  return { ui };
233
237
  if (key.name === "return" || key.name === "space") {
package/dist/tui/tui.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { App } from "../app.js";
2
- import { onKey, type Data, type Effect, type Ui } from "./model.js";
2
+ import { type HistoryRec } from "../history.js";
3
+ import { onKey, type Data, type Effect, type MessageRow, type Ui } from "./model.js";
3
4
  import type { Terminal } from "./terminal.js";
4
5
  export declare const TUI_SESSION = "tui";
5
6
  /** A relay's `/.well-known/p2p-relay.json` read at most this far (it is a few hundred bytes). */
@@ -51,7 +52,11 @@ export declare class Tui {
51
52
  loadAll(): Promise<void>;
52
53
  loadPeople(): Promise<void>;
53
54
  loadHeld(): Promise<void>;
54
- /** Received messages from the event log, and sent ones: this run's, receipts asked for, the outbox. */
55
+ /**
56
+ * Received messages from the event log, and sent ones: this run's, receipts asked for, the outbox;
57
+ * then the message history (history.ts) for what is older or was sent elsewhere. The TUI runs
58
+ * only on the person's own terminal (command.ts tuiRefusal), so it reads the person's view.
59
+ */
55
60
  loadMessages(): Promise<void>;
56
61
  /** Keeps the newest MESSAGES_MAX messages (this run's sends are capped the same way). */
57
62
  private capMessages;
@@ -69,3 +74,5 @@ export declare class Tui {
69
74
  /** For tests: resolves once the TUI stopped. */
70
75
  done(): Promise<void>;
71
76
  }
77
+ /** A message history record as a row of the Messages screen (peer text cleaned for the terminal). */
78
+ export declare function historyRow(r: HistoryRec, session: string): MessageRow;
package/dist/tui/tui.js CHANGED
@@ -22,7 +22,8 @@ import { RECEIPT_OUTCOMES } from "@peer2peer/core/v3";
22
22
  import { approveJoinRequest, circleMembers, joinFromHeld, listCircles } from "../circle-ops.js";
23
23
  import { doctor } from "../doctor.js";
24
24
  import { CliError, toErrorJson } from "../errors.js";
25
- import { listPeers, sendSharing } from "../sessions.js";
25
+ import { listPeers, sendSharing, tuiTaintNote } from "../sessions.js";
26
+ import { isPersonRecord, readHistory } from "../history.js";
26
27
  import { sessionWorkdir, showProject } from "../projects.js";
27
28
  import { accept, dropHeld, friends, getHeld, listHeld } from "../social.js";
28
29
  import { trustAdd } from "../trust.js";
@@ -225,6 +226,7 @@ export class Tui {
225
226
  ...(typeof e.sid === "string" ? { sid: e.sid } : {}),
226
227
  ...(typeof e.ref === "string" ? { ref: e.ref } : {}),
227
228
  text: clean(e.text),
229
+ inbox: forUs,
228
230
  ...(!forUs && typeof e.toSession === "string" ? { note: `for your session ${clean(e.toSession)}` } : {}),
229
231
  };
230
232
  }
@@ -306,7 +308,11 @@ export class Tui {
306
308
  this.data.held = rows;
307
309
  this.draw();
308
310
  }
309
- /** Received messages from the event log, and sent ones: this run's, receipts asked for, the outbox. */
311
+ /**
312
+ * Received messages from the event log, and sent ones: this run's, receipts asked for, the outbox;
313
+ * then the message history (history.ts) for what is older or was sent elsewhere. The TUI runs
314
+ * only on the person's own terminal (command.ts tuiRefusal), so it reads the person's view.
315
+ */
310
316
  async loadMessages() {
311
317
  const app = this.app;
312
318
  const cutoff = this.now() - 7 * 86_400_000;
@@ -328,10 +334,26 @@ export class Tui {
328
334
  for (const [id, w] of Object.entries(receipts)) {
329
335
  if (w.at < cutoff || out.some((m) => m.receiptId === id))
330
336
  continue;
331
- out.push({ id: `r:${id}`, dir: "out", at: w.at, who: await app.addressOf(w.to), userId: w.to, own: w.own, ref: w.ref, text: `(sent from session ${w.fromSession}; text not kept)`, state: "sent", receiptId: id, outcomes: w.outcomes.map((x) => x.outcome) });
337
+ out.push({ id: `r:${id}`, dir: "out", at: w.at, who: await app.addressOf(w.to), userId: w.to, own: w.own, ref: w.ref, text: `(sent from session ${w.fromSession}; text not kept)`, state: "sent", receiptId: id, outcomes: w.outcomes.map((x) => x.outcome), inbox: w.fromSession === this.data.session, ...(w.fromSession !== this.data.session ? { note: `from your session ${clean(w.fromSession)}` } : {}) });
332
338
  }
333
339
  for (const i of outbox) {
334
- out.push({ id: `o:${i.id}`, dir: "out", at: i.queuedAt, who: i.dest.address, userId: i.dest.userId, own: i.dest.own, ref: i.dest.ref, text: `(sealed in the outbox, from session ${i.fromSession})`, state: "outbox" });
340
+ out.push({ id: `o:${i.id}`, dir: "out", at: i.queuedAt, who: i.dest.address, userId: i.dest.userId, own: i.dest.own, ref: i.dest.ref, text: `(sealed in the outbox, from session ${i.fromSession})`, state: "outbox", inbox: i.fromSession === this.data.session });
341
+ }
342
+ const hist = await readHistory(app, { person: true }, { limit: MESSAGES_MAX }, this.now()).catch(() => undefined);
343
+ for (const r of hist?.messages ?? []) {
344
+ if (r.dir === "in") {
345
+ if (!received.some((m) => m.id === r.id))
346
+ received.push(historyRow(r, this.data.session));
347
+ continue;
348
+ }
349
+ // A send already listed (this run's, a receipt's, the outbox's): the history fills in its text.
350
+ const same = out.find((m) => m.userId === r.peer.userId && Math.abs(m.at - r.at) < 60_000 && (m.text === r.text || m.text.startsWith("(")));
351
+ if (same) {
352
+ if (same.text.startsWith("("))
353
+ same.text = clean(r.text);
354
+ continue;
355
+ }
356
+ out.push(historyRow(r, this.data.session));
335
357
  }
336
358
  this.data.messages = [...received, ...out];
337
359
  this.capMessages();
@@ -528,7 +550,7 @@ export class Tui {
528
550
  case "send":
529
551
  await this.busy("sending", async () => {
530
552
  const at = this.now();
531
- const row = { id: `s:${at}:${this.sent.length}`, dir: "out", at, who: e.label, text: e.text, state: "sent" };
553
+ const row = { id: `s:${at}:${this.sent.length}`, dir: "out", at, who: e.label, text: e.text, state: "sent", inbox: true };
532
554
  try {
533
555
  // As `p2p send` on a terminal: someone this session isn't shared with is added with the send
534
556
  // (undone if it fails), so it lands and their replies come here; and it says so.
@@ -547,7 +569,8 @@ export class Tui {
547
569
  // Your own send crosses no project boundary; it says which one this folder has (projects.ts).
548
570
  const here = await showProject(this.app, sessionWorkdir(this.app.env)).catch(() => undefined);
549
571
  const boundary = here ? ` Project ${clean(here.name)} here is ${here.policy}: this send was yours.` : "";
550
- this.flash(`${r.queued ? `Queued for ${clean(r.to.address)} [${r.to.ref}]: it goes out or waits until they're back.` : `Sent to ${clean(r.to.address)} [${r.to.ref}].`}${note}${boundary}`);
572
+ const taint = await tuiTaintNote(this.app, r.to.userId).catch(() => undefined);
573
+ this.flash(`${r.queued ? `Queued for ${clean(r.to.address)} [${r.to.ref}]: it goes out or waits until they're back.` : `Sent to ${clean(r.to.address)} [${r.to.ref}].`}${note}${boundary}${taint ? ` Note: ${taint}.` : ""}`);
551
574
  }
552
575
  catch (err) {
553
576
  Object.assign(row, { state: "failed", note: clean(toErrorJson(err).reason) });
@@ -569,3 +592,21 @@ export class Tui {
569
592
  return (this.closed ??= new Promise((r) => (this.stop.signal.aborted ? r() : this.stop.signal.addEventListener("abort", () => r()))));
570
593
  }
571
594
  }
595
+ /** A message history record as a row of the Messages screen (peer text cleaned for the terminal). */
596
+ export function historyRow(r, session) {
597
+ const mine = isPersonRecord(r) || r.session === session;
598
+ const where = r.session === undefined ? "" : clean(r.session);
599
+ return {
600
+ id: r.id,
601
+ dir: r.dir,
602
+ at: r.at,
603
+ who: clean(r.peer.address) || "?",
604
+ userId: r.peer.userId,
605
+ ...(r.peerSession ? { own: r.peerSession.own, sid: r.peerSession.sid, ref: r.peerSession.ref } : {}),
606
+ text: clean(r.type === "ext" ? `${r.ext ?? "extension"}: ${r.text}` : r.text),
607
+ ...(r.dir === "out" ? { state: r.state === "outbox" ? "outbox" : r.state === "offline" ? "offline" : "sent" } : {}),
608
+ fromHistory: true,
609
+ inbox: mine,
610
+ ...(!mine ? { note: r.dir === "in" ? `for your session ${where}` : `from your session ${where}` } : {}),
611
+ };
612
+ }
package/dist/tui/view.js CHANGED
@@ -23,7 +23,7 @@ export function ago(sec) {
23
23
  const HELP = {
24
24
  people: "↑↓ move · m message · d doctor · 1-5 screens · ? help · q quit",
25
25
  held: "↑↓ move · a accept/deliver · x decline · t always deliver · ? help · q quit",
26
- messages: "↑↓ move · Enter open · r reply · 1-5 screens · ? help · q quit",
26
+ messages: "↑↓ move · Enter open · r reply · h inbox/all · 1-5 screens · ? help · q quit",
27
27
  send: "↑↓ pick · Enter write · then Enter send, Esc cancel, Ctrl-U clear · q quit",
28
28
  health: "r run doctor · d on People: one person · 1-5 screens · ? help · q quit",
29
29
  };
@@ -190,9 +190,9 @@ function outcomeText(m, now) {
190
190
  return { text: m.receiptId ? "sent, no receipt yet" : "sent", style: DIM };
191
191
  }
192
192
  function messages(ui, d, cols, h, out, now) {
193
- const list = messagesSorted(d);
193
+ const list = messagesSorted(d, ui);
194
194
  if (list.length === 0) {
195
- out.push(new Line(cols).add("No messages yet. Messages to this TUI's session, replies and your sends appear here.", DIM));
195
+ out.push(new Line(cols).add(ui.inboxOnly ? "Nothing in your inbox yet (h shows every session's messages)." : "No messages yet. Messages to this TUI's session, replies and your sends appear here.", DIM));
196
196
  return;
197
197
  }
198
198
  const [a, b] = window(list.length, ui.sel.messages, Math.floor(h / 2));
@@ -208,6 +208,8 @@ function messages(ui, d, cols, h, out, now) {
208
208
  if (m.dir === "out") {
209
209
  const o = outcomeText(m, now);
210
210
  l.add(o.text, o.style);
211
+ if (m.note)
212
+ l.gap(2).add(m.note, DIM);
211
213
  }
212
214
  else {
213
215
  if (m.note)
@@ -297,7 +299,7 @@ function overlay(f, ui, cols, rows) {
297
299
  "↑/↓ or j/k move, PgUp/PgDn, g/G first/last",
298
300
  "People: m or Enter message a person or session; d doctor for them",
299
301
  "Held: a accept (invites, joins) or deliver (held messages); x decline; t always deliver from the sender (asks first)",
300
- "Messages: Enter opens one; r replies (this window sends no read receipts)",
302
+ "Messages: Enter opens one; r replies (this window sends no read receipts); h your inbox only or every session (history: kept encrypted on this device, 30 days by default)",
301
303
  "Send: pick, write, Enter sends; Esc cancels",
302
304
  "Health: r runs the doctor again",
303
305
  "q or Ctrl-C quits. Nothing is accepted, sent or trusted except on your key press.",