@peer2peer/ext-ix 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,203 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // Who listens on the local Ix endpoint's port. "Local" is a loopback port, and on a machine other
4
+ // people log in to, another user can listen on it while this user's backend is down: they would
5
+ // receive what `ix note` / `ix session` send (session labels, repos, branches, statuses, edited
6
+ // files, a peer's imported note) and the local token Ix sends to loopback. Ix's backend has no
7
+ // identity it can prove (only /v1/health and the opt-in local token, which a listener would just
8
+ // accept), so before ext-ix writes there it asks the operating system who owns every socket
9
+ // listening on that port on a loopback or wildcard address:
10
+ // - Linux: /proc/net/tcp and /proc/net/tcp6 (state 0A = LISTEN, with the owner's uid);
11
+ // - macOS: `netstat -an` lists every user's listening sockets (without owners), and
12
+ // `lsof -iTCP:<port> -sTCP:LISTEN` lists the ones this user's processes hold (a non-root lsof
13
+ // can't see other users'). Every listener netstat shows must be matched by one of this user's.
14
+ // Every such listener must be this user's, and there must be at least one. A root-owned one
15
+ // (Docker's port proxy on Linux runs as root whoever started the container, so on a machine whose
16
+ // Docker others use it may be a teammate's backend) counts only when the person said so:
17
+ // `ixTrustRootListener: true` in p2p's config.json (the host passes it on the graph target). Anything else, or an
18
+ // answer that can't be read, or another platform, means "no": graph writes stay off. This narrows
19
+ // the window; it can't close it (a listener can appear between the check and the write).
20
+ import { execFile } from "node:child_process";
21
+ import { readFile } from "node:fs/promises";
22
+ /** What the person can do about a root-owned listener. */
23
+ export const ROOT_HINT = 'root holds it: on Linux that is Docker\'s port proxy, whoever started the container. If this machine\'s Docker is only yours, set "ixTrustRootListener": true in p2p\'s config.json';
24
+ /** The port of an http(s) endpoint, or undefined. */
25
+ export function endpointPort(endpoint) {
26
+ try {
27
+ const u = new URL(endpoint);
28
+ if (u.protocol !== "http:" && u.protocol !== "https:")
29
+ return undefined;
30
+ const p = u.port ? Number(u.port) : u.protocol === "https:" ? 443 : 80;
31
+ return Number.isInteger(p) && p > 0 && p < 65536 ? p : undefined;
32
+ }
33
+ catch {
34
+ return undefined;
35
+ }
36
+ }
37
+ /** Whether a connection to a loopback address could reach a socket bound to `addr`. */
38
+ export function reachesLoopback(addr) {
39
+ const a = addr.toLowerCase();
40
+ if (a === "*" || a === "0.0.0.0" || a === "::" || a === "0:0:0:0:0:0:0:0" || a === "::1" || a === "0:0:0:0:0:0:0:1")
41
+ return true;
42
+ if (/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(a))
43
+ return true;
44
+ const mapped = /^(?:0:0:0:0:0:ffff|::ffff):(.+)$/.exec(a)?.[1];
45
+ if (mapped)
46
+ return mapped === "0.0.0.0" || /^127\./.test(mapped) || /^7f[0-9a-f]{2}:[0-9a-f]{1,4}$/.test(mapped) || mapped === "0:0";
47
+ return false;
48
+ }
49
+ /** One /proc/net/tcp{,6} address (hex, little-endian 32-bit words) as text. */
50
+ export function procAddr(hex) {
51
+ if (/^[0-9A-Fa-f]{8}$/.test(hex)) {
52
+ const b = hex.match(/../g).map((x) => parseInt(x, 16)).reverse();
53
+ return b.join(".");
54
+ }
55
+ if (/^[0-9A-Fa-f]{32}$/.test(hex)) {
56
+ const bytes = [];
57
+ for (const w of hex.match(/.{8}/g))
58
+ bytes.push(...w.match(/../g).map((x) => parseInt(x, 16)).reverse());
59
+ const groups = [];
60
+ for (let i = 0; i < 16; i += 2)
61
+ groups.push(((bytes[i] << 8) | bytes[i + 1]).toString(16));
62
+ // ::ffff:a.b.c.d keeps its IPv4 tail readable.
63
+ if (groups.slice(0, 5).every((g) => g === "0") && groups[5] === "ffff")
64
+ return `::ffff:${bytes.slice(12).join(".")}`;
65
+ return groups.join(":");
66
+ }
67
+ return undefined;
68
+ }
69
+ /** LISTEN sockets from /proc/net/tcp or tcp6 text. */
70
+ export function parseProcNet(text) {
71
+ const out = [];
72
+ for (const line of text.split("\n").slice(1)) {
73
+ const f = line.trim().split(/\s+/);
74
+ if (f.length < 10 || f[3] !== "0A")
75
+ continue;
76
+ const [addrHex, portHex] = f[1].split(":");
77
+ const addr = procAddr(addrHex ?? "");
78
+ const port = parseInt(portHex ?? "", 16);
79
+ const uid = Number(f[7]);
80
+ if (addr === undefined || !Number.isInteger(port) || !Number.isInteger(uid))
81
+ continue;
82
+ out.push({ addr, port, uid });
83
+ }
84
+ return out;
85
+ }
86
+ /** An address as netstat (`127.0.0.1`, `::1`, `*`) or lsof (`[::1]`, `*`) prints it, normalized. */
87
+ function normAddr(a) {
88
+ const x = a.replace(/^\[|\]$/g, "").replace(/%.*$/, "").toLowerCase();
89
+ return x === "*" || x === "0.0.0.0" || x === "::" ? "*" : x;
90
+ }
91
+ /** LISTEN sockets from macOS `netstat -an` (no owners). Undefined when the output isn't that. */
92
+ export function parseNetstat(text) {
93
+ const lines = text.split("\n");
94
+ if (!lines.some((l) => /^Proto\s+Recv-Q\s+Send-Q\s+Local Address/.test(l)))
95
+ return undefined;
96
+ const out = [];
97
+ for (const line of lines) {
98
+ if (!/^tcp[46]{1,2}\s/.test(line) || !/\sLISTEN\s*$/.test(line))
99
+ continue;
100
+ const local = line.trim().split(/\s+/)[3] ?? "";
101
+ const dot = local.lastIndexOf(".");
102
+ const port = Number(local.slice(dot + 1));
103
+ if (dot < 0 || !Number.isInteger(port))
104
+ return undefined;
105
+ out.push({ addr: normAddr(local.slice(0, dot)), port });
106
+ }
107
+ return out;
108
+ }
109
+ /** This user's LISTEN sockets from `lsof -nP -iTCP:<port> -sTCP:LISTEN -Fpun` (a `p`, `u`, then `n` per socket). */
110
+ export function parseLsof(text) {
111
+ const out = [];
112
+ let pid;
113
+ let uid;
114
+ for (const line of text.split("\n")) {
115
+ const k = line[0];
116
+ const v = line.slice(1);
117
+ if (k === "p") {
118
+ pid = Number(v);
119
+ uid = undefined;
120
+ }
121
+ else if (k === "u")
122
+ uid = Number(v);
123
+ else if (k === "n") {
124
+ const colon = v.lastIndexOf(":");
125
+ const port = Number(v.slice(colon + 1));
126
+ if (colon < 0 || !Number.isInteger(port))
127
+ continue;
128
+ out.push({ addr: normAddr(v.slice(0, colon)), port, ...(Number.isInteger(pid) ? { pid } : {}), ...(Number.isInteger(uid) ? { uid } : {}) });
129
+ }
130
+ }
131
+ return out;
132
+ }
133
+ /**
134
+ * macOS: every listener on `port` that netstat shows (all users) must be matched, address for
135
+ * address, by one this user's lsof shows (root's too, with trustRoot); one left over belongs to someone lsof can't see.
136
+ */
137
+ export function judgeDarwin(all, mine, port, uid, trustRoot = false) {
138
+ const want = all.filter((l) => l.port === port && reachesLoopback(l.addr));
139
+ if (want.length === 0)
140
+ return { ok: false, why: `nothing listens on port ${port} (is the Ix backend running?)` };
141
+ const have = mine.filter((l) => l.port === port && (l.uid === uid || (l.uid === 0 && trustRoot)));
142
+ const left = new Map();
143
+ for (const l of have)
144
+ left.set(l.addr, (left.get(l.addr) ?? 0) + 1);
145
+ for (const l of want) {
146
+ const n = left.get(l.addr) ?? 0;
147
+ if (n === 0)
148
+ return { ok: false, why: `port ${port} (${l.addr}) is held by a process that isn't yours, not your Ix backend` };
149
+ left.set(l.addr, n - 1);
150
+ }
151
+ return { ok: true };
152
+ }
153
+ /** The verdict for the listeners on `port`: all owned by `uid` (or root, with `trustRoot`), and at least one. */
154
+ export function judgeListeners(listeners, port, uid, trustRoot = false) {
155
+ const mine = listeners.filter((l) => l.port === port && reachesLoopback(l.addr));
156
+ if (mine.length === 0)
157
+ return { ok: false, why: `nothing listens on port ${port} (is the Ix backend running?)` };
158
+ for (const l of mine) {
159
+ if (typeof l.uid !== "number")
160
+ return { ok: false, why: `couldn't tell who listens on port ${port}` };
161
+ if (l.uid === 0 && uid !== 0 && !trustRoot)
162
+ return { ok: false, why: `port ${port}: ${ROOT_HINT}` };
163
+ if (l.uid !== uid && !(l.uid === 0 && trustRoot))
164
+ return { ok: false, why: `port ${port} is held by another user (uid ${l.uid}), not your Ix backend` };
165
+ }
166
+ return { ok: true };
167
+ }
168
+ const run = (cmd, args) => new Promise((resolve, reject) => {
169
+ execFile(cmd, args, { timeout: 10_000, maxBuffer: 8 * 1024 * 1024, env: { PATH: "/usr/sbin:/usr/bin:/bin:/sbin", LANG: "C" }, windowsHide: true }, (err, stdout) => (err ? reject(err) : resolve(String(stdout))));
170
+ });
171
+ /** The real check (see the top of this file). */
172
+ export async function checkLoopbackListener(endpoint, d = {}) {
173
+ const trustRoot = d.trustRoot === true;
174
+ const port = endpointPort(endpoint);
175
+ if (port === undefined)
176
+ return { ok: false, why: "the local endpoint has no port" };
177
+ const platform = d.platform ?? process.platform;
178
+ const uid = d.uid ?? (typeof process.getuid === "function" ? process.getuid() : undefined);
179
+ if (uid === undefined)
180
+ return { ok: false, why: "this platform can't tell who listens on a port" };
181
+ const read = d.readFile ?? ((p) => readFile(p, "utf8"));
182
+ const exec = d.exec ?? run;
183
+ try {
184
+ if (platform === "linux") {
185
+ const texts = await Promise.all(["/proc/net/tcp", "/proc/net/tcp6"].map((p) => read(p).catch(() => "")));
186
+ if (texts.every((t) => t === ""))
187
+ return { ok: false, why: "couldn't read /proc/net/tcp" };
188
+ return judgeListeners(texts.flatMap(parseProcNet), port, uid, trustRoot);
189
+ }
190
+ if (platform === "darwin") {
191
+ const all = parseNetstat(await exec("/usr/sbin/netstat", ["-an"]));
192
+ if (!all)
193
+ return { ok: false, why: "couldn't read netstat's sockets" };
194
+ // lsof exits 1 when it finds nothing: no socket of this user's.
195
+ const mine = parseLsof(await exec("/usr/sbin/lsof", ["-nP", "-a", `-iTCP:${port}`, "-sTCP:LISTEN", "-Fpun"]).catch(() => ""));
196
+ return judgeDarwin(all, mine, port, uid, trustRoot);
197
+ }
198
+ }
199
+ catch {
200
+ return { ok: false, why: `couldn't tell who listens on port ${port}` };
201
+ }
202
+ return { ok: false, why: `can't tell who listens on a port on ${platform}` };
203
+ }
@@ -0,0 +1,50 @@
1
+ import type { ExtContext, ExtMemory, ExtMemoryItem } from "@peer2peer/cli";
2
+ import { type IxRunner } from "./ix.js";
3
+ import { type ListenerCheck } from "./listener.js";
4
+ /** How long Ix keeps a session record: 30 days. */
5
+ export declare const MEMORY_TTL_HOURS = 720;
6
+ /** At most this many sessions' Ix ids are remembered (ExtContext.kv is 64 KiB). */
7
+ export declare const MAX_MEMORY_SESSIONS = 50;
8
+ /** Longest one-line text written per item (characters). */
9
+ export declare const MAX_MEMORY_LINE = 300;
10
+ /** At most this many files named per note. */
11
+ export declare const MAX_MEMORY_FILES = 50;
12
+ /** Longest file name written (characters). */
13
+ export declare const MAX_MEMORY_PATH = 200;
14
+ /** Bound on one `ix` call made for memory. */
15
+ export declare const MEMORY_IX_TIMEOUT_MS = 15000;
16
+ /** The tag of every record (the person's own notes are usually `note`). */
17
+ export declare const MEMORY_TAG = "finding";
18
+ /** The first line of every record: what it is, and that it isn't instructions. */
19
+ export declare const MEMORY_PREFIX = "Recorded by Peer2Peer (agent-generated, untrusted)";
20
+ /** One line: control and format characters dropped, whitespace collapsed, capped. */
21
+ export declare function oneLine(s: unknown, max?: number): string;
22
+ /** The Ix session name of Peer2Peer session `sid`: `p2p-<sid>`, or `p2p-` and its hash when the id doesn't fit. */
23
+ export declare function memorySessionName(sid: string): string;
24
+ /** `--actor=`: `p2p:<address>` when the address is a plain one, else `p2p`. */
25
+ export declare function memoryActor(address: string | undefined): string;
26
+ /** The session record's purpose (one line, at most MAX_PURPOSE characters). */
27
+ export declare function memoryPurpose(i: Pick<ExtMemoryItem, "label" | "repo" | "branch">): string;
28
+ /** A file name a record may carry: repo-relative, no `.`/`..`, no whitespace or control character, capped. */
29
+ export declare function memoryPath(f: unknown): f is string;
30
+ /** The note text of one item; undefined when there is nothing to write (an empty status, no valid file). */
31
+ export declare function memoryText(i: ExtMemoryItem): string | undefined;
32
+ /**
33
+ * The Peer2Peer session a note was recorded for, when it is one of graph memory's records: its
34
+ * Ix session is one this extension created (by id), or is named `p2p-<sid>`, or its text starts
35
+ * with MEMORY_PREFIX. `{sid: undefined}` for a record whose session can't be told (a hashed name,
36
+ * no session): the caller must refuse it. Undefined for any other note.
37
+ */
38
+ export declare function recordOf(ctx: ExtContext, note: {
39
+ sessionId?: unknown;
40
+ sessionName?: unknown;
41
+ text?: unknown;
42
+ }): Promise<{
43
+ sid: string | undefined;
44
+ } | undefined>;
45
+ /**
46
+ * The memory writer. `runner(ctx, sid)` is the guarded runner of a call made for session `sid`
47
+ * (extension.ts runner: pinned to that session's graph target, OSS-only for note and session, the
48
+ * port's listener checked). `listener` is the same check, for available().
49
+ */
50
+ export declare function ixMemory(runner: (ctx: ExtContext, sid?: string) => IxRunner, listener?: ListenerCheck): ExtMemory;
package/dist/memory.js ADDED
@@ -0,0 +1,315 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // Local graph as memory (epic #41 piece 2; SPEC.md §10): the context of this device's own sessions,
4
+ // written into the person's local Ix graph as it happens. `p2p watch` gathers it from the statuses
5
+ // the session posted (packages/p2p/src/graph-memory.ts; only sessions whose project ceiling is
6
+ // shared: a private project's sessions are never recorded), queues it, and hands it here in
7
+ // batches, off the hook path. Per session:
8
+ //
9
+ // ix session --json create p2p-<sid> --purpose=<label, repo, branch> --actor=p2p:<address> --ttl=720
10
+ // ix note --tag=finding --session=<its id> --actor=p2p:<address> --json
11
+ // < "Recorded by Peer2Peer (agent-generated, untrusted)\nSession started …" (and Status, Edited, Session ended)
12
+ //
13
+ // Every call goes through the guarded runner (ix.ts guardRunner): the graph target of the session
14
+ // (p2p's chokepoint) must be local, the port must be held by this user (listener.ts), the `ix` that
15
+ // answers must have the OSS `ix note` / `ix session` (never Ix Pro's, which write to the cloud org),
16
+ // and each write must say on stderr that it reached the local endpoint. Text goes on stdin only.
17
+ // Records are framed as untrusted (agent-generated) and tagged `finding`, so a reader can tell them
18
+ // from the person's own notes.
19
+ import { createHash } from "node:crypto";
20
+ import { isSafeRelativePath } from "@peer2peer/core/v3";
21
+ import { checkedTarget, IX_ACTOR_RE, IX_SESSION_NAME_RE, IX_SESSION_REF_RE, ixAvailable, MAX_PURPOSE, memoryRefusal, memorySupport } from "./ix.js";
22
+ import { checkLoopbackListener } from "./listener.js";
23
+ import { IxExtError } from "./text.js";
24
+ /** How long Ix keeps a session record: 30 days. */
25
+ export const MEMORY_TTL_HOURS = 720;
26
+ /** At most this many sessions' Ix ids are remembered (ExtContext.kv is 64 KiB). */
27
+ export const MAX_MEMORY_SESSIONS = 50;
28
+ /** Longest one-line text written per item (characters). */
29
+ export const MAX_MEMORY_LINE = 300;
30
+ /** At most this many files named per note. */
31
+ export const MAX_MEMORY_FILES = 50;
32
+ /** Longest file name written (characters). */
33
+ export const MAX_MEMORY_PATH = 200;
34
+ /** Bound on one `ix` call made for memory. */
35
+ export const MEMORY_IX_TIMEOUT_MS = 15_000;
36
+ /** The tag of every record (the person's own notes are usually `note`). */
37
+ export const MEMORY_TAG = "finding";
38
+ /** The first line of every record: what it is, and that it isn't instructions. */
39
+ export const MEMORY_PREFIX = "Recorded by Peer2Peer (agent-generated, untrusted)";
40
+ const KV_KEY = "memory";
41
+ /** One line: control and format characters dropped, whitespace collapsed, capped. */
42
+ export function oneLine(s, max = MAX_MEMORY_LINE) {
43
+ if (typeof s !== "string")
44
+ return "";
45
+ const t = s
46
+ .replace(/[\p{Cc}\p{Cf}\u2028\u2029]+/gu, " ")
47
+ .replace(/\s+/g, " ")
48
+ .trim();
49
+ const cps = [...t];
50
+ return cps.length > max ? `${cps.slice(0, max - 1).join("")}…` : t;
51
+ }
52
+ /** The Ix session name of Peer2Peer session `sid`: `p2p-<sid>`, or `p2p-` and its hash when the id doesn't fit. */
53
+ export function memorySessionName(sid) {
54
+ const name = `p2p-${sid}`;
55
+ return IX_SESSION_NAME_RE.test(name) ? name : `p2p-${createHash("sha256").update(sid).digest("hex").slice(0, 32)}`;
56
+ }
57
+ /** `--actor=`: `p2p:<address>` when the address is a plain one, else `p2p`. */
58
+ export function memoryActor(address) {
59
+ const a = `p2p:${address ?? ""}`;
60
+ return IX_ACTOR_RE.test(a) ? a : "p2p";
61
+ }
62
+ const iso = (ms) => (Number.isFinite(ms) && ms > 0 ? new Date(ms).toISOString() : new Date().toISOString());
63
+ /** Where a session runs, in words: `label (repo widgets, branch main)`. */
64
+ function where(i) {
65
+ const label = oneLine(i.label, 64) || "session";
66
+ const bits = [i.repo ? `repo ${oneLine(i.repo, 100)}` : "", i.branch ? `branch ${oneLine(i.branch, 100)}` : ""].filter(Boolean);
67
+ return bits.length ? `${label} (${bits.join(", ")})` : label;
68
+ }
69
+ /** The session record's purpose (one line, at most MAX_PURPOSE characters). */
70
+ export function memoryPurpose(i) {
71
+ return oneLine(`Peer2Peer session ${where(i)}`, MAX_PURPOSE);
72
+ }
73
+ /** A file name a record may carry: repo-relative, no `.`/`..`, no whitespace or control character, capped. */
74
+ export function memoryPath(f) {
75
+ return typeof f === "string" && f.length > 0 && [...f].length <= MAX_MEMORY_PATH && isSafeRelativePath(f) && !/[\s\p{Cc}\p{Cf}\u2028\u2029]/u.test(f);
76
+ }
77
+ /** The note text of one item; undefined when there is nothing to write (an empty status, no valid file). */
78
+ export function memoryText(i) {
79
+ let body;
80
+ switch (i.kind) {
81
+ case "start":
82
+ body = `Session started ${iso(i.at)}: ${where(i)}.`;
83
+ break;
84
+ case "status": {
85
+ const s = oneLine(i.summary);
86
+ body = s ? `Status (${iso(i.at)}): ${s}` : undefined;
87
+ break;
88
+ }
89
+ case "files": {
90
+ const files = [...new Set((i.files ?? []).filter(memoryPath))];
91
+ if (files.length === 0)
92
+ return undefined;
93
+ const shown = files.slice(0, MAX_MEMORY_FILES);
94
+ body = `Edited (${iso(i.at)}): ${shown.join(", ")}${files.length > shown.length ? ` and ${files.length - shown.length} more` : ""}`;
95
+ break;
96
+ }
97
+ case "end":
98
+ body = `Session ended ${iso(i.at)}.`;
99
+ break;
100
+ default:
101
+ return undefined;
102
+ }
103
+ return body === undefined ? undefined : `${MEMORY_PREFIX}\n${body}`;
104
+ }
105
+ /** The store's sessions in one canonical form, for its MAC. */
106
+ function canon(sessions) {
107
+ return JSON.stringify(Object.keys(sessions)
108
+ .sort()
109
+ .map((k) => [k, sessions[k].id, sessions[k].endpoint, sessions[k].at]));
110
+ }
111
+ /**
112
+ * The store (`<home>/ext/ix.json`, key `memory`), MACed with the device's key when the host offers
113
+ * one (ExtContext.localMac): anything that can write files in P2P_HOME without the keys (a model's
114
+ * file tools) can't plant a mapping from a session to another Ix session. A MAC that doesn't verify
115
+ * means no record at all: sessions are made again, and recordOf traces nothing through it.
116
+ */
117
+ async function loadKv(ctx) {
118
+ const v = (await ctx.kv.get(KV_KEY));
119
+ const sessions = {};
120
+ if (v && typeof v.sessions === "object" && v.sessions !== null) {
121
+ for (const [sid, s] of Object.entries(v.sessions)) {
122
+ if (s && typeof s.id === "string" && IX_SESSION_REF_RE.test(s.id) && typeof s.endpoint === "string" && typeof s.at === "number")
123
+ sessions[sid] = { id: s.id, endpoint: s.endpoint, at: s.at };
124
+ }
125
+ }
126
+ if (typeof ctx.localMac === "function") {
127
+ let ok;
128
+ try {
129
+ ok = typeof v?.mac === "string" && v.mac === ctx.localMac(canon(sessions));
130
+ }
131
+ catch {
132
+ ok = false;
133
+ }
134
+ if (!ok)
135
+ return { sessions: {} };
136
+ }
137
+ return { sessions };
138
+ }
139
+ async function saveKv(ctx, kv) {
140
+ const kept = Object.entries(kv.sessions)
141
+ .sort((a, b) => a[1].at - b[1].at)
142
+ .slice(-MAX_MEMORY_SESSIONS);
143
+ const sessions = Object.fromEntries(kept);
144
+ let mac;
145
+ try {
146
+ mac = typeof ctx.localMac === "function" ? ctx.localMac(canon(sessions)) : undefined;
147
+ }
148
+ catch {
149
+ mac = undefined;
150
+ }
151
+ await ctx.kv.set(KV_KEY, { sessions, ...(mac ? { mac } : {}) });
152
+ }
153
+ /**
154
+ * The Peer2Peer session a note was recorded for, when it is one of graph memory's records: its
155
+ * Ix session is one this extension created (by id), or is named `p2p-<sid>`, or its text starts
156
+ * with MEMORY_PREFIX. `{sid: undefined}` for a record whose session can't be told (a hashed name,
157
+ * no session): the caller must refuse it. Undefined for any other note.
158
+ */
159
+ export async function recordOf(ctx, note) {
160
+ const kv = await loadKv(ctx);
161
+ if (typeof note.sessionId === "string") {
162
+ const hit = Object.entries(kv.sessions).find(([, s]) => s.id === note.sessionId);
163
+ if (hit)
164
+ return { sid: hit[0] };
165
+ }
166
+ if (typeof note.sessionName === "string" && note.sessionName.startsWith("p2p-")) {
167
+ const rest = note.sessionName.slice(4);
168
+ // A hashed name (an id that didn't fit) can't be traced back.
169
+ return { sid: /^[0-9a-f]{32}$/.test(rest) ? undefined : rest };
170
+ }
171
+ if (typeof note.text === "string" && note.text.startsWith(MEMORY_PREFIX))
172
+ return { sid: undefined };
173
+ return undefined;
174
+ }
175
+ /** An error's reason code (IxExtError's, else ix_failed). */
176
+ const reasonOf = (e) => (e instanceof IxExtError ? e.code : "ix_failed");
177
+ /** Reasons that stop a batch and turn memory off until available() says otherwise. */
178
+ const STOPS = new Set(["graph_target", "ix_unconfirmed", "ix_missing", "ix_listener", "aborted"]);
179
+ /** What available() reports for a support answer that isn't "oss". */
180
+ function unavailable(support, installed) {
181
+ if (!installed)
182
+ return { ok: false, reason: "ix_missing", message: "Ix isn't installed: graph memory is off (https://github.com/ix-infrastructure/Ix)" };
183
+ const e = memoryRefusal(support, { kind: "local", endpoint: "" });
184
+ return { ok: false, reason: support === "pro" ? "ix_pro" : "ix_upgrade", message: e.message };
185
+ }
186
+ /** The local target of `sid` (checked again here), or undefined when it isn't local. */
187
+ async function localOf(ctx, sid) {
188
+ let t;
189
+ try {
190
+ t = ctx.graphTarget ? checkedTarget(await ctx.graphTarget(sid ? { sid } : {})) : checkedTarget(undefined);
191
+ }
192
+ catch {
193
+ t = checkedTarget(undefined);
194
+ }
195
+ return t.kind === "local" ? t : undefined;
196
+ }
197
+ /**
198
+ * The memory writer. `runner(ctx, sid)` is the guarded runner of a call made for session `sid`
199
+ * (extension.ts runner: pinned to that session's graph target, OSS-only for note and session, the
200
+ * port's listener checked). `listener` is the same check, for available().
201
+ */
202
+ export function ixMemory(runner, listener = (e, o) => checkLoopbackListener(e, { trustRoot: o?.trustRoot === true })) {
203
+ return {
204
+ v: 1,
205
+ available: async (ctx) => {
206
+ const ix = runner(ctx);
207
+ if (!(await ixAvailable(ix)))
208
+ return unavailable("none", false);
209
+ const s = await memorySupport(ix);
210
+ if (s !== "oss")
211
+ return unavailable(s, true);
212
+ const t = await localOf(ctx);
213
+ if (!t)
214
+ return { ok: false, reason: "not_local", message: "graph memory goes to the local graph only" };
215
+ const v = await listener(t.endpoint, { trustRoot: t.trustRootListener === true }).catch(() => ({ ok: false, why: "couldn't tell who listens on its port" }));
216
+ return v.ok ? { ok: true } : { ok: false, reason: "ix_listener", message: `the local Ix endpoint ${t.endpoint} isn't one Peer2Peer can trust: ${v.why}` };
217
+ },
218
+ write: async (ctx, batch) => {
219
+ const items = Array.isArray(batch?.items) ? batch.items : [];
220
+ const sid = typeof batch?.sid === "string" ? batch.sid : "";
221
+ const signal = batch?.signal;
222
+ if (items.length === 0 || sid === "")
223
+ return { written: 0 };
224
+ // The chokepoint first, for the whole batch: anything but local is refused, before any `ix` runs.
225
+ const target = await localOf(ctx, sid);
226
+ if (!target) {
227
+ return { written: 0, failed: [{ reason: "not_local", n: items.length, message: "graph memory goes to the local graph only, and this session's target isn't local" }] };
228
+ }
229
+ const ix = runner(ctx, sid);
230
+ const actor = memoryActor((await ctx.self().catch(() => undefined))?.address);
231
+ const kv = await loadKv(ctx);
232
+ let written = 0;
233
+ const failed = new Map();
234
+ const fail = (reason, n, message) => {
235
+ const f = failed.get(reason) ?? { n: 0 };
236
+ failed.set(reason, { n: f.n + n, message: message ?? f.message });
237
+ };
238
+ const aborted = () => {
239
+ if (signal?.aborted)
240
+ throw new IxExtError("aborted", "the batch ran out of time");
241
+ };
242
+ let checked = false;
243
+ const sessionId = async (first) => {
244
+ const known = kv.sessions[sid];
245
+ // Remembered for this endpoint, and still there (checked once per batch): used. Gone (the
246
+ // backend was reset), or created at another endpoint: made again.
247
+ if (known && known.endpoint === target.endpoint) {
248
+ if (checked)
249
+ return known.id;
250
+ aborted();
251
+ const r = await ix.run(["session", "--json", "show", known.id], { timeoutMs: MEMORY_IX_TIMEOUT_MS });
252
+ let same;
253
+ try {
254
+ same = r.code === 0 && JSON.parse(r.stdout).sessionId === known.id;
255
+ }
256
+ catch {
257
+ same = false;
258
+ }
259
+ checked = true;
260
+ if (same)
261
+ return known.id;
262
+ }
263
+ delete kv.sessions[sid];
264
+ aborted();
265
+ const argv = ["session", "--json", "create", memorySessionName(sid), `--purpose=${memoryPurpose(first)}`, `--actor=${actor}`, `--ttl=${MEMORY_TTL_HOURS}`];
266
+ const r = await ix.run(argv, { timeoutMs: MEMORY_IX_TIMEOUT_MS });
267
+ if (r.code !== 0)
268
+ throw new IxExtError("ix_failed", `ix session create failed (exit ${r.code})`);
269
+ let id;
270
+ try {
271
+ id = JSON.parse(r.stdout).sessionId;
272
+ }
273
+ catch {
274
+ id = undefined;
275
+ }
276
+ if (typeof id !== "string" || !IX_SESSION_REF_RE.test(id))
277
+ throw new IxExtError("ix_failed", "ix session create printed no session id");
278
+ kv.sessions[sid] = { id, endpoint: target.endpoint, at: Date.now() };
279
+ checked = true;
280
+ await saveKv(ctx, kv);
281
+ return id;
282
+ };
283
+ for (let i = 0; i < items.length; i++) {
284
+ const item = items[i];
285
+ const text = memoryText(item);
286
+ if (text === undefined)
287
+ continue;
288
+ try {
289
+ aborted();
290
+ const ixSession = await sessionId(item);
291
+ aborted();
292
+ const r = await ix.run(["note", `--tag=${MEMORY_TAG}`, `--session=${ixSession}`, `--actor=${actor}`, "--json"], { stdin: text, timeoutMs: MEMORY_IX_TIMEOUT_MS });
293
+ if (r.code !== 0)
294
+ throw new IxExtError("ix_failed", `ix note failed (exit ${r.code})`);
295
+ written++;
296
+ }
297
+ catch (e) {
298
+ const reason = reasonOf(e);
299
+ const message = e instanceof Error ? e.message : undefined;
300
+ if (STOPS.has(reason)) {
301
+ fail(reason, items.length - i, message);
302
+ const support = e.extra?.ix;
303
+ return {
304
+ written,
305
+ failed: [...failed].map(([r, f]) => ({ reason: r, ...f })),
306
+ ...(reason === "aborted" ? {} : { unavailable: { ok: false, reason: support === "pro" ? "ix_pro" : support === "upgrade" ? "ix_upgrade" : reason, message: message ?? reason } }),
307
+ };
308
+ }
309
+ fail(reason, 1, message);
310
+ }
311
+ }
312
+ return { written, ...(failed.size ? { failed: [...failed].map(([reason, f]) => ({ reason, ...f })) } : {}) };
313
+ },
314
+ };
315
+ }
package/dist/note.d.ts ADDED
@@ -0,0 +1,40 @@
1
+ import { type RepoRef } from "./repo.js";
2
+ import { type NoteTag, type Roots } from "./text.js";
3
+ export declare const NOTE_KIND: "x:ix.note";
4
+ export interface NoteBody {
5
+ tag: NoteTag;
6
+ text: string;
7
+ title?: string;
8
+ /** The sender's Ix session name (a label; nothing on the receiver resolves it). */
9
+ session?: string;
10
+ repo?: RepoRef;
11
+ /** Repo-relative paths the note is about. */
12
+ refs?: string[];
13
+ /** When the note was written (ISO 8601). */
14
+ at?: string;
15
+ }
16
+ /** Validates a received (or about-to-be-sent) note body. Unknown fields are dropped. */
17
+ export declare function parseNoteBody(v: unknown): NoteBody;
18
+ export declare function noteFallback(b: Pick<NoteBody, "tag">): string;
19
+ export interface NoteInput {
20
+ text: string;
21
+ tag?: string;
22
+ title?: string;
23
+ session?: string;
24
+ refs?: string[];
25
+ repo?: RepoRef;
26
+ at?: string;
27
+ /** For scrubbing: the repo root and home directory (never sent). */
28
+ root?: Roots;
29
+ home?: string;
30
+ hostname?: string;
31
+ }
32
+ /** Sending: a validated body and its fallback, with local paths scrubbed and refs made repo-relative. */
33
+ export declare function buildNote(i: NoteInput): {
34
+ body: NoteBody;
35
+ fallback: string;
36
+ };
37
+ /** Receiving: the model-safe digest, framed as data from the named peer. */
38
+ export declare function renderNote(b: NoteBody, from: {
39
+ address: string;
40
+ }): Record<string, unknown>;