vine-context 0.0.1 → 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/LICENSE +202 -0
- package/README.md +279 -3
- package/dist/apps/shell.html +149 -0
- package/dist/apps/views.html +144 -0
- package/dist/cli.js +7825 -0
- package/dist/cli.js.map +1 -0
- package/examples/data/graphs/party/.cypherlite/schema/schema.cypher +5 -0
- package/examples/data/graphs/party/.cypherlite.lock +1 -0
- package/examples/data/graphs/party/.cypherlite.writer +0 -0
- package/examples/data/graphs/party/manifest.json +215 -0
- package/examples/data/graphs/party/nodes/0-262144-7987dd27c85668d4810609133f705907.parquet +0 -0
- package/examples/data/graphs/party/wal/.cypherlite.lock +1 -0
- package/examples/data/graphs/party/wal/.cypherlite.writer +0 -0
- package/examples/data/graphs/party/wal/00000002.log +0 -0
- package/examples/data/hosts/party/changes.jsonl +19 -0
- package/examples/data/hosts/party/group.json +5 -0
- package/examples/data/hosts/party/sharing.json +1 -0
- package/examples/data/identity.json +4 -0
- package/models/temporal-claims/instructions.md +78 -0
- package/models/temporal-claims/model.yaml +99 -0
- package/models/temporal-claims/tools.yaml +344 -0
- package/package.json +71 -3
- package/plugin/.claude-plugin/plugin.json +8 -0
- package/plugin/.codex-plugin/plugin.json +17 -0
- package/plugin/.mcp.json +8 -0
- package/plugin/codex/hooks.json +11 -0
- package/plugin/commands/join.md +22 -0
- package/plugin/hooks/hooks.json +11 -0
- package/plugin/hooks/register.tsx +2310 -0
- package/plugin/hooks/vine-hook.mjs +25 -0
- package/plugin/skills/join-context-graph/SKILL.md +36 -0
- package/plugin/skills/vine-context/SKILL.md +235 -0
- package/plugin/tests/context-graph.test.tsx +830 -0
- package/plugin/types/index.d.ts +165 -0
package/dist/cli.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/package-root.ts","../src/p2p/link.ts","../src/core/identity.ts","../src/core/changes.ts","../src/core/embed.ts","../src/core/pack.ts","../src/core/relate.ts","../src/core/paths.ts","../src/core/values.ts","../src/core/graph.ts","../src/p2p/protocol.ts","../src/host/state.ts","../src/host/client.ts","../src/core/log.ts","../src/core/members.ts","../src/p2p/channel.ts","../src/core/secret.ts","../src/p2p/cloudflare.ts","../src/p2p/ice.ts","../src/p2p/invites.ts","../src/p2p/mesh.ts","../src/p2p/advice.ts","../src/p2p/nostr.ts","../src/p2p/signal.ts","../src/host/digest.ts","../src/host/news.ts","../src/host/host.ts","../src/p2p/join.ts","../src/mcp/apps.ts","../src/mcp/links.ts","../src/core/catalogue.ts","../src/mcp/server.ts","../src/ui/server.ts","../src/demo/scenario.ts","../src/demo/live.ts","../src/cli/prompt.ts","../src/cli/cloudflare-setup.ts","../src/p2p/netcheck.ts","../src/cli/doctor.ts","../src/cli/setup.ts","../src/cli/hook.ts","../src/cli/index.ts"],"sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\n// The source (src/…) and the bundle (dist/) sit at different depths, so walk\n// up to this package's own package.json.\nlet root: string | undefined;\n\nexport function packageRoot(): string {\n if (root) return root;\n let dir = dirname(fileURLToPath(import.meta.url));\n for (;;) {\n const file = join(dir, \"package.json\");\n if (existsSync(file) && JSON.parse(readFileSync(file, \"utf8\")).name === \"vine-context\") return (root = dir);\n const parent = dirname(dir);\n if (parent === dir) throw new Error(\"vine-context's package.json not found\");\n dir = parent;\n }\n}\n\nexport function packageInfo(): { name: string; version: string } {\n return JSON.parse(readFileSync(join(packageRoot(), \"package.json\"), \"utf8\"));\n}\n","// Join codes and the cryptography around them.\n//\n// vine1_<room>.<secret>\n//\n// Each invite has its own code. The room (16 random bytes) names the\n// signalling topic and tells the host which invite is being used. The secret\n// (32 random bytes) never leaves the two machines: signalling is encrypted with\n// a key derived from it, and a peer proves it holds it with an HMAC over the\n// host's challenge before any other message is accepted. The \"1\" is the format\n// version; \"vine2_\" is kept for a later format (short code words).\n\nimport { createCipheriv, createDecipheriv, createHash, createHmac, hkdfSync, randomBytes, timingSafeEqual } from \"node:crypto\";\n\nexport const b64u = (b: Buffer) => b.toString(\"base64url\");\nexport const unb64u = (s: string) => Buffer.from(s, \"base64url\");\n\nexport interface Link {\n room: string;\n secret: Buffer;\n}\n\nexport function newLink(): Link {\n return { room: b64u(randomBytes(16)), secret: randomBytes(32) };\n}\n\nexport const CODE_PREFIX = \"vine1_\";\n\nexport function formatCode(l: Link): string {\n return `${CODE_PREFIX}${l.room}.${b64u(l.secret)}`;\n}\n\nconst CODE_RE = /(?<![A-Za-z0-9_-])vine1_([A-Za-z0-9_-]{22})\\.([A-Za-z0-9_-]{43})(?![A-Za-z0-9_-])/;\nconst DAMAGED_RE = /vine1_[A-Za-z0-9_.-]*/;\n\n/** Finds a join code in text (it may be pasted with other words around it). */\nexport function parseCode(text: string): Link {\n const t = text.trim();\n const m = CODE_RE.exec(t);\n if (m) {\n const secret = unb64u(m[2]!);\n if (b64u(unb64u(m[1]!)) === m[1] && unb64u(m[1]!).length === 16 && secret.length === 32 && b64u(secret) === m[2]) return { room: m[1]!, secret };\n }\n if (m || DAMAGED_RE.test(t)) throw new Error(\"That join code is damaged or cut short: copy the whole code (vine1_ then two parts joined by a dot) again.\");\n throw new Error(\"That is not a Vine Context join code. It looks like vine1_<room>.<secret>.\");\n}\n\nexport function roomKeys(l: Link): { tag: string; key: Buffer } {\n const tag = createHash(\"sha256\").update(`vine-room:${l.room}`).digest(\"hex\").slice(0, 32);\n const key = Buffer.from(hkdfSync(\"sha256\", l.secret, l.room, \"vine-signal-v1\", 32));\n return { tag, key };\n}\n\nexport function seal(key: Buffer, obj: unknown): string {\n const iv = randomBytes(12);\n const c = createCipheriv(\"aes-256-gcm\", key, iv);\n const body = Buffer.concat([c.update(JSON.stringify(obj)), c.final()]);\n return b64u(Buffer.concat([iv, c.getAuthTag(), body]));\n}\n\n/** Decrypts a sealed message, or returns null for anything not sealed with this key. */\nexport function unseal(key: Buffer, s: string): any | null {\n try {\n const raw = unb64u(s);\n const d = createDecipheriv(\"aes-256-gcm\", key, raw.subarray(0, 12));\n d.setAuthTag(raw.subarray(12, 28));\n return JSON.parse(Buffer.concat([d.update(raw.subarray(28)), d.final()]).toString());\n } catch {\n return null;\n }\n}\n\nexport function proof(secret: Buffer, nonce: string, peer: string): string {\n return b64u(createHmac(\"sha256\", secret).update(`vine-join-v1:${nonce}:${peer}`).digest());\n}\n\nexport function checkProof(secret: Buffer, nonce: string, peer: string, given: unknown): boolean {\n if (typeof given !== \"string\") return false;\n const want = unb64u(proof(secret, nonce, peer));\n const got = unb64u(given);\n return got.length === want.length && timingSafeEqual(got, want);\n}\n","// This install's identity: a display name and an Ed25519 key pair. Peers send\n// their public key and sign the host's challenge with it, so a host that\n// approved a key recognises it again in later sessions.\n\nimport { createHash, createPrivateKey, createPublicKey, generateKeyPairSync, sign, verify } from \"node:crypto\";\nimport { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { execFileSync } from \"node:child_process\";\nimport { platform, userInfo } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { b64u, unb64u } from \"../p2p/link.js\";\n\nexport interface Identity {\n name: string;\n /** Raw 32-byte Ed25519 public key, base64url. */\n publicKey: string;\n sign(message: string): string;\n}\n\n/** What a display name may be: 1–40 letters, digits, spaces, dots, dashes or underscores. */\nexport const NAME_RE = /^[\\p{L}\\p{N}][\\p{L}\\p{N} ._-]{0,39}$/u;\n\nconst identityFile = (dataDir: string) => join(dataDir, \"identity.json\");\n\nfunction storedName(dataDir: string): string | undefined {\n try {\n const n = JSON.parse(readFileSync(identityFile(dataDir), \"utf8\")).name;\n return typeof n === \"string\" && NAME_RE.test(n) ? n : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Where a display name came from, strongest first. */\nexport type NameSource = \"VINE_USER\" | \"chosen\" | \"git\" | \"os\" | \"login\" | \"generated\";\n\n/**\n * Sources that are a guess rather than the person's own name: ask them for a\n * name instead of only offering to change it.\n */\nexport const isGuessedName = (source: NameSource): boolean => source === \"login\" || source === \"generated\";\n\n/** The raw places a name can be found on this machine. Tests pass their own. */\nexport interface NameProbes {\n /** git's global user.name. */\n git(): string | undefined;\n /** The full name on the computer account. */\n os(): string | undefined;\n /** The login name. */\n login(): string | undefined;\n}\n\nconst run = (cmd: string, args: string[]): string | undefined => {\n try {\n return execFileSync(cmd, args, { encoding: \"utf8\", stdio: [\"ignore\", \"pipe\", \"ignore\"], timeout: 2000 }).trim() || undefined;\n } catch {\n return undefined;\n }\n};\n\nconst login = (): string | undefined => {\n try {\n return userInfo().username || undefined;\n } catch {\n return undefined; // no passwd entry, as in some containers\n }\n};\n\nexport const systemProbes: NameProbes = {\n git: () => run(\"git\", [\"config\", \"--global\", \"user.name\"]),\n os: () => {\n if (platform() === \"darwin\") return run(\"id\", [\"-F\"]);\n if (platform() === \"win32\") return undefined;\n const user = login();\n // The passwd entry's fifth field, up to its first comma, is the full name.\n return user ? run(\"getent\", [\"passwd\", user])?.split(\":\")[4]?.split(\",\")[0] : undefined;\n },\n login,\n};\n\n/** Account names that say nothing about who someone is, and collide between machines. */\nconst GENERIC = new Set([\n \"root\", \"admin\", \"administrator\", \"system administrator\", \"user\", \"guest\", \"owner\", \"default\", \"home\", \"dev\", \"developer\", \"test\",\n \"ubuntu\", \"debian\", \"fedora\", \"centos\", \"ec2-user\", \"ec2 default user\", \"cloud user\", \"azureuser\", \"runner\", \"codespace\", \"gitpod\",\n \"vscode\", \"node\", \"pi\", \"docker\", \"vagrant\",\n]);\n\n/** A found name, cleaned to a valid display name; nothing if it is unusable or generic. */\nfunction usable(raw: string | undefined): string | undefined {\n if (!raw) return undefined;\n const n = raw.replace(/[^\\p{L}\\p{N} ._-]/gu, \"\").replace(/^[^\\p{L}\\p{N}]+/u, \"\").slice(0, 40).trim();\n return NAME_RE.test(n) && !GENERIC.has(n.toLowerCase()) ? n : undefined;\n}\n\nconst ADJECTIVES = [\n \"Amber\", \"Brisk\", \"Calm\", \"Clever\", \"Copper\", \"Dusty\", \"Early\", \"Fern\", \"Gentle\", \"Golden\", \"Hazel\", \"Ivory\", \"Jolly\", \"Keen\", \"Lively\", \"Mellow\",\n \"Misty\", \"Nimble\", \"Olive\", \"Plucky\", \"Quiet\", \"Rustic\", \"Sandy\", \"Silver\", \"Spry\", \"Steady\", \"Sunny\", \"Tidy\", \"Velvet\", \"Warm\", \"Wild\", \"Zesty\",\n];\nconst ANIMALS = [\n \"Badger\", \"Bison\", \"Crane\", \"Dingo\", \"Egret\", \"Falcon\", \"Gecko\", \"Heron\", \"Ibis\", \"Jackal\", \"Kestrel\", \"Lemur\", \"Lynx\", \"Marten\", \"Newt\", \"Ocelot\",\n \"Osprey\", \"Otter\", \"Panda\", \"Puffin\", \"Quail\", \"Raven\", \"Robin\", \"Stoat\", \"Swift\", \"Tapir\", \"Thrush\", \"Vole\", \"Walrus\", \"Wombat\", \"Wren\", \"Yak\",\n];\n\n/** A made-up name that is always the same for a key, for when nothing better is found. */\nexport function generatedName(publicKey: string): string {\n const h = createHash(\"sha256\").update(\"vine-name-v1:\").update(unb64u(publicKey)).digest();\n return `${ADJECTIVES[h[0]! % ADJECTIVES.length]} ${ANIMALS[h[1]! % ANIMALS.length]}`;\n}\n\n/**\n * Your display name in graphs and where it came from: VINE_USER, else the name\n * you set (update_context, or `vine setup`), else git's user.name, else the full name on your\n * computer account, else your login name, else a name made up from your key.\n */\nexport function resolveName(dataDir: string, probes: NameProbes = systemProbes): { name: string; source: NameSource } {\n if (process.env.VINE_USER) return { name: process.env.VINE_USER, source: \"VINE_USER\" };\n const stored = storedName(dataDir);\n if (stored) return { name: stored, source: \"chosen\" };\n for (const source of [\"git\", \"os\", \"login\"] as const) {\n const name = usable(probes[source]());\n if (name) return { name, source };\n }\n return { name: generatedName(storedKeys(dataDir).publicKey), source: \"generated\" };\n}\n\nexport function defaultName(dataDir: string): string {\n return resolveName(dataDir).name;\n}\n\n/** Where the name comes from, for telling people how to change it. */\nexport function nameSource(dataDir: string): NameSource {\n return resolveName(dataDir).source;\n}\n\n/** Saves your display name with your key. */\nexport function setName(dataDir: string, name: string): string {\n const n = name.trim();\n if (!NAME_RE.test(n)) throw new Error(\"Names are 1–40 letters, digits, spaces, dots, dashes or underscores, starting with a letter or digit.\");\n loadIdentity(dataDir, n); // creates the key if this is the first use\n const file = identityFile(dataDir);\n const stored = JSON.parse(readFileSync(file, \"utf8\"));\n writeFileSync(file, JSON.stringify({ ...stored, name: n }, null, 1) + \"\\n\", { mode: 0o600 });\n return n;\n}\n\n/** A short, readable form of a public key, for people comparing keys. */\nexport function fingerprint(publicKey: string): string {\n return createHash(\"sha256\").update(unb64u(publicKey)).digest(\"hex\").slice(0, 12).replace(/(.{4})(?!$)/g, \"$1-\");\n}\n\nconst SPKI_PREFIX = Buffer.from(\"302a300506032b6570032100\", \"hex\");\n\nexport function verifySignature(publicKey: string, message: string, signature: unknown): boolean {\n if (typeof signature !== \"string\") return false;\n try {\n const raw = unb64u(publicKey);\n if (raw.length !== 32) return false;\n const key = createPublicKey({ key: Buffer.concat([SPKI_PREFIX, raw]), format: \"der\", type: \"spki\" });\n return verify(null, Buffer.from(message), key, unb64u(signature));\n } catch {\n return false;\n }\n}\n\n/** This install's key pair from <dataDir>/identity.json, created on first use. */\nfunction storedKeys(dataDir: string): { publicKey: string; privateKey: string } {\n const file = identityFile(dataDir);\n if (existsSync(file)) return JSON.parse(readFileSync(file, \"utf8\"));\n const { publicKey, privateKey } = generateKeyPairSync(\"ed25519\");\n const raw = publicKey.export({ format: \"der\", type: \"spki\" }).subarray(SPKI_PREFIX.length);\n const stored = { publicKey: b64u(raw), privateKey: privateKey.export({ format: \"der\", type: \"pkcs8\" }).toString(\"base64\") };\n mkdirSync(dirname(file), { recursive: true, mode: 0o700 });\n writeFileSync(file, JSON.stringify(stored, null, 1) + \"\\n\", { mode: 0o600 });\n chmodSync(file, 0o600);\n return stored;\n}\n\n/** Loads this install's identity from <dataDir>/identity.json, creating it on first use. */\nexport function loadIdentity(dataDir: string, name = defaultName(dataDir)): Identity {\n const stored = storedKeys(dataDir);\n const key = createPrivateKey({ key: Buffer.from(stored.privateKey, \"base64\"), format: \"der\", type: \"pkcs8\" });\n return {\n name,\n publicKey: stored.publicKey,\n sign: (message) => b64u(sign(null, Buffer.from(message), key)),\n };\n}\n","// Changes: the unit of replication. Every write to a graph, and every change\n// to who is in it, is one change, signed by its author's key. Each machine\n// keeps every change it has seen (the log) and builds its Relate store from\n// them; two machines with the same changes end up with the same graph.\n//\n// A change is made, applied locally at once, and (for writes) held on its\n// author's machine for a few seconds so it can be taken back; only then is it\n// numbered (`seq`), signed and sent. Each author numbers their own changes 1,\n// 2, 3 … with no gaps, so \"what I have\" is one number per author.\n\nimport { randomBytes } from \"node:crypto\";\nimport type { Identity } from \"./identity.js\";\nimport { verifySignature } from \"./identity.js\";\n\nexport type Role = \"reader\" | \"contributor\" | \"admin\";\nexport const RANK: Record<Role, number> = { reader: 0, contributor: 1, admin: 2 };\nexport const ROLES: Role[] = [\"reader\", \"contributor\", \"admin\"];\n\n/** Writes to the graph's content. */\nexport type DataKind = \"claim\" | \"question\" | \"reply\" | \"link\" | \"withdraw\";\n/** Changes to who is in the graph. */\nexport type MemberKind = \"create\" | \"add_member\" | \"set_role\" | \"remove_member\" | \"rename\" | \"describe\";\nexport type Kind = DataKind | MemberKind;\nexport const DATA_KINDS = new Set<Kind>([\"claim\", \"question\", \"reply\", \"link\", \"withdraw\"]);\nexport const MEMBER_KINDS = new Set<Kind>([\"create\", \"add_member\", \"set_role\", \"remove_member\", \"rename\", \"describe\"]);\n\nexport interface Change {\n /** UUIDv7: unique, and roughly time-ordered. */\n id: string;\n /** The graph's id: the id of its `create` change. Equal to `id` for the create change itself. */\n graph: string;\n kind: Kind;\n /** The author's Ed25519 public key (base64url). */\n author: string;\n /** The author's own counter, 1, 2, 3 … with no gaps. */\n seq: number;\n /** When it was made, ISO 8601. Machine clocks are assumed to be in sync. */\n at: string;\n body: Record<string, any>;\n /** Ed25519 signature over everything above (canonical JSON). */\n sig: string;\n}\n\nexport type Unsigned = Omit<Change, \"seq\" | \"sig\">;\n\n/** A time-ordered UUID (version 7). */\nexport function uuidv7(now = Date.now()): string {\n const b = randomBytes(16);\n b.writeUIntBE(now, 0, 6);\n b[6] = (b[6]! & 0x0f) | 0x70;\n b[8] = (b[8]! & 0x3f) | 0x80;\n const h = b.toString(\"hex\");\n return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;\n}\n\n/** JSON with object keys sorted at every level, so the same change always signs the same way. */\nexport function canonical(v: unknown): string {\n if (v === null || typeof v !== \"object\") return JSON.stringify(v ?? null);\n if (Array.isArray(v)) return `[${v.map(canonical).join(\",\")}]`;\n const o = v as Record<string, unknown>;\n return `{${Object.keys(o)\n .filter((k) => o[k] !== undefined)\n .sort()\n .map((k) => `${JSON.stringify(k)}:${canonical(o[k])}`)\n .join(\",\")}}`;\n}\n\nconst signedText = (c: Omit<Change, \"sig\">) => `vine-change-v1:${canonical({ ...c })}`;\n\nexport function signChange(c: Omit<Change, \"sig\">, identity: Identity): Change {\n if (c.author !== identity.publicKey) throw new Error(\"A change can only be signed by its author.\");\n return { ...c, sig: identity.sign(signedText(c)) };\n}\n\nconst ISO = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(Z|[+-]\\d{2}:\\d{2})$/;\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;\nconst KINDS = new Set<Kind>([...DATA_KINDS, ...MEMBER_KINDS]);\n\n/** The shape and signature of a change, before anything about the graph is checked. */\nexport function wellFormed(c: unknown): c is Change {\n if (!c || typeof c !== \"object\") return false;\n const x = c as Change;\n if (typeof x.id !== \"string\" || !UUID.test(x.id)) return false;\n if (typeof x.graph !== \"string\" || !UUID.test(x.graph)) return false;\n if (!KINDS.has(x.kind)) return false;\n if (typeof x.author !== \"string\" || x.author.length !== 43) return false;\n if (!Number.isInteger(x.seq) || x.seq < 1) return false;\n if (typeof x.at !== \"string\" || !ISO.test(x.at) || Number.isNaN(Date.parse(x.at))) return false;\n if (!x.body || typeof x.body !== \"object\" || Array.isArray(x.body)) return false;\n const { sig, ...rest } = x;\n return verifySignature(x.author, signedText(rest), sig);\n}\n\n/** The order every machine applies changes in: time, then author, then the author's counter. */\nexport function compareChanges(a: Pick<Change, \"at\" | \"author\" | \"seq\">, b: Pick<Change, \"at\" | \"author\" | \"seq\">): number {\n const t = Date.parse(a.at) - Date.parse(b.at);\n if (t) return t;\n if (a.author !== b.author) return a.author < b.author ? -1 : 1;\n return a.seq - b.seq;\n}\n\n/** How many changes from each author a machine has: what it tells the other side when they sync. */\nexport type Have = Record<string, number>;\n","// Text embedders for the model's vector index.\n//\n// Every machine embeds its own copy of a graph from the text, so vectors never\n// travel between peers and two members may use different embedders. The graph\n// records which one made its vectors; opening it with another rebuilds them.\n\nimport { createHash } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join } from \"node:path\";\nimport { packageRoot } from \"./package-root.js\";\n\n// Words too common to help a search. Without this, \"when is the release?\"\n// matches every text that contains \"is\" or \"the\".\nconst STOP_WORDS = new Set(\n (\n \"a an and are as at be but by did do does for from had has have how in is it its of on or \" +\n \"that the their this to was were what when where which who whom why will with\"\n ).split(\" \"),\n);\n\n/** The lower-case words of a text, without the common ones. Falls back to all words. */\nexport function contentWords(text: string): string[] {\n const words = text.toLowerCase().match(/[\\p{L}\\p{N}]+/gu) ?? [];\n const kept = words.filter((w) => !STOP_WORDS.has(w));\n return kept.length ? kept : words;\n}\n\nexport interface Embedder {\n readonly name: string;\n readonly dim: number;\n /** A unit-length vector, or null when the text has nothing to embed. */\n embed(text: string): number[] | null;\n}\n\n/**\n * Hashes words and three-letter fragments into a fixed-size vector. Needs no\n * model download and works offline, but matches shared words and fragments,\n * not meaning.\n */\nexport class HashEmbedder implements Embedder {\n readonly name = \"hash-256\";\n readonly dim = 256;\n\n embed(text: string): number[] | null {\n const vec = new Array<number>(this.dim).fill(0);\n for (const word of contentWords(text)) {\n this.add(vec, \"w:\" + word, 1.0);\n const padded = `^${word}$`;\n for (let i = 0; i < padded.length - 2; i++) this.add(vec, \"t:\" + padded.slice(i, i + 3), 0.3);\n }\n const norm = Math.sqrt(vec.reduce((sum, v) => sum + v * v, 0));\n if (norm === 0) return null;\n return vec.map((v) => v / norm);\n }\n\n private add(vec: number[], feature: string, weight: number): void {\n const n = createHash(\"sha256\").update(feature).digest().readBigUInt64BE(0);\n const sign = n & 1n ? 1.0 : -1.0;\n const i = Number((n >> 1n) % BigInt(this.dim));\n vec[i] = (vec[i] ?? 0) + sign * weight;\n }\n}\n\ninterface ModelSpec {\n /** The name recorded in the graph. It changes whenever the vectors would. */\n name: string;\n dim: number;\n dir: string;\n file: string;\n pooling: \"cls\" | \"mean\";\n}\n\n/** The sentence models the native embedder can run, by the short name used in VINE_EMBEDDER. */\nexport const MODELS: Record<string, ModelSpec> = {\n \"bge-small\": { name: \"bge-small-en-v1.5-int8\", dim: 384, dir: \"bge-small-en-v1.5\", file: \"model_quantized.onnx\", pooling: \"cls\" },\n minilm: { name: \"all-MiniLM-L6-v2-int8\", dim: 384, dir: \"all-MiniLM-L6-v2\", file: \"model_quantized.onnx\", pooling: \"mean\" },\n};\n\n/** Texts longer than this many tokens are cut; claims and questions are far shorter. */\nconst MAX_TOKENS = 256;\n\ninterface NativeModel {\n embed(text: string): Float32Array;\n}\n\n/** The npm package that holds the prebuilt addon and model for this machine. */\nexport function platformPackage(): string {\n return `vine-context-embedder-${process.platform}-${process.arch}`;\n}\n\n/**\n * Where the native addon and its models are. In order: VINE_EMBEDDER_DIR, the\n * platform package if it is installed beside vine-context, then the folder\n * `npm run build:embedder` fills in a checkout.\n */\nexport function embedderDir(): string {\n if (process.env.VINE_EMBEDDER_DIR) return process.env.VINE_EMBEDDER_DIR;\n try {\n return dirname(createRequire(join(packageRoot(), \"package.json\")).resolve(`${platformPackage()}/package.json`));\n } catch {\n return join(packageRoot(), \"native\", \"embedder\", \"dist\");\n }\n}\n\n/**\n * A small sentence model run on the CPU by the Rust addon in native/embedder.\n * It matches meaning, not only shared words. Optional: it needs the addon\n * built for this machine and the model's files beside it.\n */\nexport class ModelEmbedder implements Embedder {\n readonly name: string;\n readonly dim: number;\n private model?: NativeModel;\n\n constructor(\n private readonly spec: ModelSpec,\n private readonly dir = embedderDir(),\n ) {\n this.name = spec.name;\n this.dim = spec.dim;\n const missing = [join(dir, \"embedder.node\"), join(dir, \"models\", spec.dir, spec.file), join(dir, \"models\", spec.dir, \"tokenizer.json\")].filter(\n (f) => !existsSync(f),\n );\n if (missing.length)\n throw new Error(\n `The '${spec.name}' embedder is not installed on this machine (missing ${missing[0]}). ` +\n `Install ${platformPackage()} beside vine-context, or build it with \\`npm run build:embedder\\` in a vine-context checkout, ` +\n \"or unset VINE_EMBEDDER to use the built-in one.\",\n );\n }\n\n embed(text: string): number[] | null {\n if (!contentWords(text).length) return null;\n // Loading takes a few hundred milliseconds, so it waits for the first text.\n this.model ??= this.load();\n return Array.from(this.model.embed(text));\n }\n\n private load(): NativeModel {\n const addon = createRequire(import.meta.url)(join(this.dir, \"embedder.node\")) as {\n Model: new (dir: string, file: string, pooling: string, maxTokens: number) => NativeModel;\n };\n return new addon.Model(join(this.dir, \"models\", this.spec.dir), this.spec.file, this.spec.pooling, MAX_TOKENS);\n }\n}\n\n/** The model `auto` picks when its package is installed. */\nexport const DEFAULT_MODEL = \"bge-small\";\n\nexport interface EmbedderChoice {\n embedder: Embedder;\n /** Why this one, when it wasn't named outright: the words `vine doctor` shows. */\n why?: string;\n}\n\n/**\n * The embedder named by VINE_EMBEDDER: `auto` (the default) takes the sentence\n * model when its package is installed and works here, else the built-in hash;\n * `hash`, or a model's short or recorded name, takes that one and nothing else.\n */\nexport function chooseEmbedder(name = process.env.VINE_EMBEDDER): EmbedderChoice {\n if (!name || name === \"auto\") {\n const spec = MODELS[DEFAULT_MODEL]!;\n const dir = embedderDir();\n let model: ModelEmbedder;\n try {\n model = new ModelEmbedder(spec, dir);\n } catch {\n return { embedder: new HashEmbedder(), why: `the ${platformPackage()} package isn't installed, so search matches words, not meaning` };\n }\n // Loads the addon now, so a build that doesn't run on this machine is found here, not on the first write.\n try {\n const v = model.embed(\"hello graph\");\n if (v?.length !== spec.dim) throw new Error(`gave ${v?.length ?? \"no\"} numbers, not ${spec.dim}`);\n } catch (e) {\n return { embedder: new HashEmbedder(), why: `the ${platformPackage()} package is installed but doesn't run here (${(e as Error).message}), so search matches words, not meaning` };\n }\n return { embedder: model, why: `${spec.name}, installed with vine: search matches meaning` };\n }\n if (name === \"hash\" || name === \"hash-256\") return { embedder: new HashEmbedder() };\n const spec = MODELS[name] ?? Object.values(MODELS).find((m) => m.name === name);\n if (spec) return { embedder: new ModelEmbedder(spec) };\n throw new Error(`Unknown embedder '${name}'. Available: auto, hash, ${Object.keys(MODELS).join(\", \")}.`);\n}\n\n/** The embedder named by VINE_EMBEDDER (see chooseEmbedder). `warn` hears why `auto` fell back to the hash. */\nexport function makeEmbedder(name = process.env.VINE_EMBEDDER, warn?: (why: string) => void): Embedder {\n const c = chooseEmbedder(name);\n if (c.why && c.embedder instanceof HashEmbedder) warn?.(`search embedder: ${c.why}`);\n return c.embedder;\n}\n","// The context model: a folder that defines a graph's shape, its tools and the\n// instructions agents follow. vine-context ships one, Claims and\n// Questions (models/temporal-claims), and every graph uses it.\n//\n// Read tools are Cypher in tools.yaml. Write tools in tools.yaml only check\n// the input against the graph (their steps return `_error`); the write itself\n// becomes a signed change (`apply` names its kind), applied by src/core/graph.ts\n// the same way on every member's machine.\n//\n// model.yaml nodes, relationships, the searchable set\n// tools.yaml named operations: input schema, derived params, Cypher steps\n// instructions.md what to record and how to query, for the agent\n// migrations/*.cypher optional, applied once each, in name order\n\nimport { existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport { parse as parseYaml } from \"yaml\";\nimport { z } from \"zod\";\nimport { packageRoot } from \"./package-root.js\";\n\nconst identifier = z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/, \"must be a Cypher identifier\");\nconst toolName = z.string().regex(/^[a-z][a-z0-9_]{0,47}$/, \"must be snake_case, up to 48 characters\");\n\nconst PropertySpec = z.object({\n type: z.enum([\"string\", \"integer\", \"number\", \"boolean\", \"date\", \"datetime\", \"id\", \"list\"]),\n description: z.string().optional(),\n required: z.boolean().default(false),\n});\n\nconst NodeSpec = z.object({\n description: z.string(),\n key: identifier.optional(),\n /** The property shown as the node's label in views. Default: the search text, else the key. */\n title: identifier.optional(),\n properties: z.record(identifier, PropertySpec).default({}),\n});\n\nconst RelSpec = z.object({\n description: z.string(),\n from: z.array(identifier).min(1),\n to: z.array(identifier).min(1),\n});\n\nexport const ModelSchema = z\n .object({\n name: z.string().regex(/^[a-z][a-z0-9-]*$/),\n version: z.number().int().positive(),\n title: z.string(),\n description: z.string(),\n nodes: z.record(identifier, NodeSpec),\n relationships: z.record(identifier, RelSpec).default({}),\n search: z\n .object({\n labels: z.array(identifier).min(1),\n text: identifier,\n })\n .optional(),\n /**\n * Which properties hold time, so views can show the graph as it stood at\n * any moment. `recorded` is on nodes and relationships; `ended`, if set, is\n * when a node stopped being current.\n */\n time: z.object({ recorded: identifier, ended: identifier.optional() }).optional(),\n })\n .superRefine((m, ctx) => {\n const labels = new Set(Object.keys(m.nodes));\n for (const [type, rel] of Object.entries(m.relationships))\n for (const l of [...rel.from, ...rel.to])\n if (!labels.has(l)) ctx.addIssue({ code: \"custom\", path: [\"relationships\", type], message: `unknown node label ${l}` });\n for (const l of m.search?.labels ?? [])\n if (!labels.has(l)) ctx.addIssue({ code: \"custom\", path: [\"search\", \"labels\"], message: `unknown node label ${l}` });\n for (const [label, node] of Object.entries(m.nodes))\n for (const p of [node.key, node.title])\n if (p && !(p in node.properties)) ctx.addIssue({ code: \"custom\", path: [\"nodes\", label], message: `${p} is not one of its properties` });\n });\n\ntype InputType = z.infer<typeof InputBase>[\"type\"];\nconst InputBase = z.object({\n type: z.enum([\"string\", \"integer\", \"number\", \"boolean\", \"date\", \"datetime\", \"id\", \"enum\", \"array\"]),\n description: z.string(),\n required: z.boolean().default(false),\n default: z.unknown().optional(),\n values: z.array(z.string()).optional(),\n items: z.enum([\"string\", \"integer\", \"number\", \"boolean\", \"date\", \"datetime\", \"id\"]).optional(),\n max_length: z.number().int().positive().optional(),\n max: z.number().optional(),\n min: z.number().optional(),\n});\nconst InputSpec = InputBase.superRefine((s, ctx) => {\n if (s.type === \"enum\" && !s.values?.length) ctx.addIssue({ code: \"custom\", message: \"enum needs values\" });\n if (s.type === \"array\" && !s.items) ctx.addIssue({ code: \"custom\", message: \"array needs items\" });\n});\n\n/** Parameters the server computes. Callers can never set these. */\nconst Derive = z.union([\n z.object({ embed: identifier }).strict(), // a vector of an input's text\n z.object({ terms: identifier }).strict(), // an input's text as plain search words\n z.object({ new_id: z.string().regex(/^[a-z]{1,8}$/) }).strict(), // a fresh id with this prefix\n]);\n\nconst Step = z.object({\n cypher: z.string().min(1),\n /** Key for this step's rows in the result. Unnamed steps return nothing, except the last. */\n name: identifier.optional(),\n single: z.boolean().default(false),\n});\n\nexport const ToolSchema = z.object({\n name: toolName,\n title: z.string().optional(),\n description: z.string().min(10),\n kind: z.enum([\"read\", \"write\"]),\n role: z.enum([\"reader\", \"contributor\", \"admin\"]).optional(),\n input: z.record(identifier, InputSpec).default({}),\n derive: z.record(identifier, Derive).default({}),\n steps: z.array(Step).min(1),\n /** A built-in view that shows this tool's result: receipt (for writes) or conflicts (pairs of items). */\n view: z.enum([\"receipt\", \"conflicts\"]).optional(),\n /** For write tools: the kind of change it makes. Its steps only check the input. */\n apply: z.enum([\"claim\", \"question\", \"reply\", \"link\", \"withdraw\"]).optional(),\n /** How to undo a write from its receipt: call `tool` with { [arg]: result[field] }. */\n undo: z.object({ tool: toolName, arg: identifier.default(\"id\"), field: identifier.default(\"id\") }).optional(),\n});\n\n/** Parameter names the server sets on every call. */\nexport const SERVER_PARAMS = [\"now\", \"by\", \"key\", \"role\"] as const;\n\n/** Tool names the server provides itself. */\nexport const RESERVED_TOOL_NAMES = [\n \"context_info\",\n \"find_context\",\n \"model_guide\",\n \"update_context\",\n \"share_context\",\n \"sharing\",\n \"manage_member\",\n \"join_context\",\n \"use_context\",\n \"delete_context\",\n \"turn_server\",\n \"link_folder\",\n \"open_view\",\n] as const;\n\nexport const ToolsFileSchema = z.object({\n fragments: z.record(identifier, z.string()).default({}),\n tools: z.array(ToolSchema).min(1),\n});\n\nexport type Model = z.infer<typeof ModelSchema>;\nexport type ToolSpec = z.infer<typeof ToolSchema> & { role: \"reader\" | \"contributor\" | \"admin\" };\nexport type InputSpecT = z.infer<typeof InputSpec>;\n\nexport interface Pack {\n dir: string;\n model: Model;\n tools: ToolSpec[];\n instructions: string;\n migrations: { name: string; cypher: string }[];\n}\n\nexport class PackError extends Error {}\n\n/** Expands {{fragment arg1 arg2}}: the fragment's text with %1, %2 … replaced by the arguments. */\nexport function expandFragments(text: string, fragments: Record<string, string>, depth = 0): string {\n if (depth > 5) throw new PackError(\"fragments nest more than 5 deep\");\n return text.replace(/\\{\\{\\s*([A-Za-z_]\\w*)((?:\\s+[A-Za-z_$][\\w.$]*)*)\\s*\\}\\}/g, (_, name: string, args: string) => {\n const body = fragments[name];\n if (body === undefined) throw new PackError(`unknown fragment {{${name}}}`);\n const list = args.trim() ? args.trim().split(/\\s+/) : [];\n const filled = body.replace(/%(\\d)/g, (m, i: string) => list[Number(i) - 1] ?? m);\n return `(${expandFragments(filled, fragments, depth + 1).trim()})`;\n });\n}\n\nfunction readYaml(file: string): unknown {\n try {\n return parseYaml(readFileSync(file, \"utf8\"));\n } catch (e) {\n throw new PackError(`${file}: ${(e as Error).message}`);\n }\n}\n\nfunction formatIssues(file: string, error: z.ZodError): string {\n return `${file}:\\n` + error.issues.map((i) => ` - ${i.path.join(\".\") || \"(root)\"}: ${i.message}`).join(\"\\n\");\n}\n\nexport function loadPack(dir: string): Pack {\n const abs = resolve(dir);\n if (!existsSync(join(abs, \"model.yaml\"))) throw new PackError(`${abs} has no model.yaml`);\n const modelResult = ModelSchema.safeParse(readYaml(join(abs, \"model.yaml\")));\n if (!modelResult.success) throw new PackError(formatIssues(\"model.yaml\", modelResult.error));\n const toolsResult = ToolsFileSchema.safeParse(readYaml(join(abs, \"tools.yaml\")));\n if (!toolsResult.success) throw new PackError(formatIssues(\"tools.yaml\", toolsResult.error));\n const { fragments, tools } = toolsResult.data;\n\n const seen = new Set<string>();\n const problems: string[] = [];\n const expanded: ToolSpec[] = tools.map((t) => {\n if (seen.has(t.name)) problems.push(`tool ${t.name} is defined twice`);\n if ((RESERVED_TOOL_NAMES as readonly string[]).includes(t.name)) problems.push(`${t.name} is a built-in tool name`);\n seen.add(t.name);\n for (const p of Object.keys(t.derive)) {\n if (p in t.input) problems.push(`${t.name}: derived parameter ${p} is also an input`);\n const d = t.derive[p]!;\n const source = \"embed\" in d ? d.embed : \"terms\" in d ? d.terms : undefined;\n if (source && !(source in t.input)) problems.push(`${t.name}: ${p} derives from unknown input ${source}`);\n if (\"embed\" in d && !modelResult.data.search) problems.push(`${t.name}: embeds text but model.yaml has no search section`);\n }\n for (const p of SERVER_PARAMS)\n if (p in t.input || p in t.derive) problems.push(`${t.name}: ${p} is set by the server and cannot be an input`);\n let steps = t.steps;\n try {\n steps = t.steps.map((s) => ({ ...s, cypher: expandFragments(s.cypher, fragments) }));\n } catch (e) {\n problems.push(`${t.name}: ${(e as Error).message}`);\n }\n return { ...t, steps, role: t.role ?? (t.kind === \"read\" ? \"reader\" : \"contributor\") };\n });\n for (const t of expanded) {\n if (t.kind === \"write\" && !t.apply) problems.push(`${t.name}: write tools name the change they make (apply)`);\n if (t.undo && !seen.has(t.undo.tool)) problems.push(`${t.name}: undo tool ${t.undo.tool} is not defined`);\n if (t.undo && t.kind !== \"write\") problems.push(`${t.name}: only write tools can be undone`);\n }\n if (problems.length) throw new PackError(\"tools.yaml:\\n\" + problems.map((p) => ` - ${p}`).join(\"\\n\"));\n\n const instructionsFile = join(abs, \"instructions.md\");\n const instructions = existsSync(instructionsFile) ? readFileSync(instructionsFile, \"utf8\") : \"\";\n const migDir = join(abs, \"migrations\");\n const migrations = existsSync(migDir)\n ? readdirSync(migDir)\n .filter((f) => f.endsWith(\".cypher\"))\n .sort()\n .map((name) => ({ name, cypher: readFileSync(join(migDir, name), \"utf8\") }))\n : [];\n return { dir: abs, model: modelResult.data, tools: expanded, instructions, migrations };\n}\n\n/** The packs that ship with vine-context. */\nexport function builtinPacksDir(): string {\n return join(packageRoot(), \"models\");\n}\n\nlet claims: Pack | undefined;\n/** The one model every graph uses: Claims and Questions. */\nexport function claimsPack(): Pack {\n return (claims ??= loadPack(join(builtinPacksDir(), \"temporal-claims\")));\n}\n\nexport type { InputType };\n","// Loads @relate/relate with the preview features we need.\n//\n// COMBINE (hybrid vector + full-text search) is behind a preview gate in\n// Relate 1.0, and the gate is read when the native library loads. So nothing\n// may import \"@relate/relate\" statically: use loadRelate().\n\nexport type RelateModule = Awaited<typeof import(\"@relate/relate\")>;\n\nlet loaded: Promise<RelateModule> | undefined;\n\nexport function loadRelate(): Promise<RelateModule> {\n if (!loaded) {\n const previews = new Set((process.env.RELATE_PREVIEW ?? \"\").split(\",\").filter(Boolean));\n previews.add(\"hybrid-search\");\n process.env.RELATE_PREVIEW = [...previews].sort().join(\",\");\n loaded = import(\"@relate/relate\");\n }\n return loaded;\n}\n\nexport type { Connection, Database } from \"@relate/relate\";\n","import { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\n/** Where graphs, their change logs and this machine's identity live. */\nexport function defaultDataDir(): string {\n return process.env.VINE_DATA_DIR ?? join(process.env.XDG_DATA_HOME ?? join(homedir(), \".local\", \"share\"), \"vine-context\");\n}\n\n/** Graphs are shared by default (that's the point); VINE_AUTO_SHARE=off turns the default off. */\nexport const autoShare = () => !/^(0|off|false|no)$/i.test(process.env.VINE_AUTO_SHARE ?? \"\");\n","// Turns Relate result values into plain JSON for tool results.\n\nimport type { RelateModule } from \"./relate.js\";\n\ntype Int = number | bigint;\nconst pad = (n: Int, w = 2) => String(Math.abs(Number(n))).padStart(w, \"0\");\nfunction offset(i: Int): string {\n const s = Number(i);\n if (s === 0) return \"Z\";\n const a = Math.abs(s);\n return `${s < 0 ? \"-\" : \"+\"}${pad(Math.floor(a / 3600))}:${pad(Math.floor((a % 3600) / 60))}`;\n}\nconst fraction = (ns: Int) => (Number(ns) ? \".\" + String(ns).padStart(9, \"0\").replace(/0+$/, \"\") : \"\");\n\n/** Property names never returned to agents: vectors are large and meaningless to read. */\nconst HIDDEN = new Set([\"embedding\"]);\n\nexport function toJson(value: unknown, R: RelateModule): unknown {\n if (value === null || value === undefined) return null;\n if (typeof value === \"bigint\") return Number.isSafeInteger(Number(value)) ? Number(value) : value.toString();\n if (typeof value !== \"object\") return value;\n if (Array.isArray(value)) return value.map((v) => toJson(v, R));\n if (value instanceof R.CypherDate) return `${value.year}-${pad(value.month)}-${pad(value.day)}`;\n if (value instanceof R.CypherDateTime)\n return `${value.year}-${pad(value.month)}-${pad(value.day)}T${pad(value.hour)}:${pad(value.minute)}:${pad(value.second)}${fraction(value.nanosecond)}${offset(value.offsetSeconds)}`;\n if (value instanceof R.CypherLocalDateTime)\n return `${value.year}-${pad(value.month)}-${pad(value.day)}T${pad(value.hour)}:${pad(value.minute)}:${pad(value.second)}${fraction(value.nanosecond)}`;\n if (value instanceof R.CypherFloat) return value.value;\n if (value instanceof R.CypherVector) return \"[vector]\";\n const v = value as Record<string, unknown>;\n if (v.kind === \"node\") return { labels: v.labels, ...(toJson(v.properties, R) as object) };\n if (v.kind === \"relationship\") return { type: v.type, ...(toJson(v.properties, R) as object) };\n const out: Record<string, unknown> = {};\n for (const [k, x] of Object.entries(v)) if (!HIDDEN.has(k)) out[k] = toJson(x, R);\n return out;\n}\n","// The graph on this machine: one Relate store, built from the graph's changes,\n// with the Claims and Questions model's tools.\n//\n// Read tools run the model's Cypher in one transaction. Write tools only\n// check their input here (prepare); the write itself is a change, applied by\n// apply() in the same way on every member's machine. apply() is idempotent\n// and order-independent: whatever order changes arrive in, the same set of\n// changes gives the same graph.\n// - A claim or question is created once (by its node id).\n// - A link waits until both ends exist (\"pending\"), and of two equal links\n// the earlier is kept.\n// - Of two withdrawals of one item, the earlier is kept.\n// - Checks that depend on what this machine has seen so far (\"that claim is\n// withdrawn\", \"that link already exists\") run only in prepare, on the\n// author's machine, never in apply.\n\nimport { mkdirSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { z } from \"zod\";\nimport type { Change } from \"./changes.js\";\nimport { uuidv7 } from \"./changes.js\";\nimport { contentWords, makeEmbedder, type Embedder } from \"./embed.js\";\nimport { claimsPack, type InputSpecT, type Model, type Pack, type ToolSpec } from \"./pack.js\";\nimport { loadRelate, type Connection, type Database, type RelateModule } from \"./relate.js\";\nimport { defaultDataDir } from \"./paths.js\";\nimport { toJson } from \"./values.js\";\nimport type { GraphDescription } from \"../p2p/protocol.js\";\n\nexport type { Role } from \"./changes.js\";\nimport { RANK, type Role } from \"./changes.js\";\n\nexport interface Caller {\n /** The caller's name: recorded as $by. */\n id: string;\n /** The caller's public key: recorded as `author`. */\n key?: string;\n role: Role;\n}\n\n/** A failure the agent should see and can act on. */\nexport class ToolError extends Error {}\n\n/** Relate refused a tool's Cypher: a bug in the model, not in the caller's input. */\nexport class QueryError extends ToolError {}\n\nexport { defaultDataDir } from \"./paths.js\";\n\n/** A node id: the kind's letter and a time-ordered UUID, e.g. c_0193…. Two machines never make the same one. */\nexport function newId(prefix: string): string {\n return `${prefix}_${uuidv7()}`;\n}\n\n/** What a write tool will do, once checked: a change's kind and body. */\nexport interface Prepared {\n kind: \"claim\" | \"question\" | \"reply\" | \"link\" | \"withdraw\";\n body: Record<string, unknown>;\n}\n\n/** Applying a change: done, waiting for something it refers to, or never (with why). */\nexport type Applied = { status: \"applied\"; result: Record<string, unknown> } | { status: \"pending\"; waiting: string[] } | { status: \"refused\"; reason: string };\n\n/** What apply needs to know about the change's author, from the membership. */\nexport interface ApplyContext {\n /** The name to record for a key. */\n name(key: string): string;\n /** Was this key an admin at that moment? */\n isAdmin(key: string, at: string): boolean;\n}\n\n/** A calendar day, checked strictly (a real date, YYYY-MM-DD). */\nexport const isoDay = () => z.iso.date({ error: \"must be a real calendar date as YYYY-MM-DD, for example 2026-03-01\" });\n/** A moment, checked strictly (ISO 8601 with seconds and a time zone). */\nexport const isoMoment = () => z.iso.datetime({ offset: true, error: \"must be an ISO 8601 date-time with a time zone, for example 2026-03-01T09:00:00Z\" });\n\n/**\n * `listing` is the shape a tool listing shows: dates are a plain string with a\n * JSON Schema `format`, not zod's long validation pattern. The strict check is\n * made where the call is handled, with the full shape.\n */\nfunction scalar(type: string, spec: Pick<InputSpecT, \"max_length\" | \"min\" | \"max\">, listing = false): z.ZodType {\n switch (type) {\n case \"string\":\n return z.string().max(spec.max_length ?? 20_000);\n case \"id\":\n return listing ? z.string() : z.string().min(1).max(64);\n case \"integer\": {\n let s = z.number().int();\n if (spec.min !== undefined) s = s.min(spec.min);\n if (spec.max !== undefined) s = s.max(spec.max);\n return s;\n }\n case \"number\": {\n let s = z.number();\n if (spec.min !== undefined) s = s.min(spec.min);\n if (spec.max !== undefined) s = s.max(spec.max);\n return s;\n }\n case \"boolean\":\n return z.boolean();\n case \"date\":\n return listing ? z.string().meta({ format: \"date\" }) : isoDay();\n case \"datetime\":\n return listing ? z.string().meta({ format: \"date-time\" }) : isoMoment();\n default:\n throw new Error(`unknown type ${type}`);\n }\n}\n\n/** The zod shape of a tool's input: for validation, or with `listing` for MCP tool listings (see scalar). */\nexport function inputShape(input: Record<string, InputSpecT>, listing = false): Record<string, z.ZodType> {\n const shape: Record<string, z.ZodType> = {};\n for (const [name, spec] of Object.entries(input)) {\n let s: z.ZodType =\n spec.type === \"enum\"\n ? z.enum(spec.values as [string, ...string[]])\n : spec.type === \"array\"\n ? z.array(scalar(spec.items!, spec, listing)).max(100)\n : scalar(spec.type, spec, listing);\n s = s.describe(spec.description);\n if (spec.default !== undefined) s = (s as z.ZodType & { default(v: unknown): z.ZodType }).default(spec.default);\n else if (!spec.required) s = s.optional();\n shape[name] = s;\n }\n return shape;\n}\n\ninterface Meta {\n model: string;\n model_version: number;\n embedder: string;\n embedding_dim: number;\n migrations: string[];\n /** A digest of the changes applied to this store, in order: tells the host whether the store matches its log. */\n applied?: string;\n}\n\n// @relate/relate 1.0.1 cannot close a store, and opening one twice in a\n// process fails, so each store stays open for the life of the process.\ninterface Store {\n db: Database;\n conn: Connection;\n /** Calls on one store run one at a time, whichever Graph makes them. */\n queue: Promise<unknown>;\n}\nconst openStores = new Map<string, Store>();\n\nconst CLAIM_RELS = new Set([\"SUPPORTS\", \"CONTRADICTS\", \"REPLACES\"]);\nconst REL_TYPES = new Set([\"SUPPORTS\", \"CONTRADICTS\", \"REPLACES\", \"ANSWERS\", \"ABOUT\", \"REPLIES_TO\"]);\nconst isArray = (v: unknown): string[] => (Array.isArray(v) ? v.filter((x): x is string => typeof x === \"string\" && x.length <= 64) : []);\nconst str = (v: unknown, max = 20_000): string | null => (typeof v === \"string\" ? v.slice(0, max) : null);\nconst day = (v: unknown): string | null => (typeof v === \"string\" && /^\\d{4}-\\d{2}-\\d{2}$/.test(v) ? v : null);\n\nexport interface SnapshotSchema {\n nodes: {\n label: string;\n description: string;\n key: string | null;\n title: string | null;\n properties: { name: string; type: string; required: boolean; description: string | null }[];\n }[];\n relationships: { type: string; description: string; from: string[]; to: string[] }[];\n time: { recorded: string; ended?: string } | null;\n}\nexport interface SnapshotNode {\n /** Label:key, unique across labels. */\n id: string;\n key: string;\n label: string;\n title: string;\n /** Ended (for example withdrawn) at or before the snapshot's time. */\n ended: boolean;\n props: Record<string, unknown>;\n}\nexport interface SnapshotEdge {\n type: string;\n source: string;\n target: string;\n props: Record<string, unknown>;\n}\nexport interface Snapshot {\n graph: string;\n model: string;\n at: string;\n schema: SnapshotSchema;\n nodes: SnapshotNode[];\n edges: SnapshotEdge[];\n truncated: boolean;\n}\n\nfunction recordedOf(n: SnapshotNode, time: Model[\"time\"]): number {\n const v = time ? n.props[time.recorded] : undefined;\n return typeof v === \"string\" ? Date.parse(v) : 0;\n}\n\nexport class Graph {\n private validators = new Map<string, z.ZodType>();\n\n private constructor(\n readonly name: string,\n readonly dir: string,\n readonly pack: Pack,\n readonly embedder: Embedder,\n private db: Database,\n private conn: Connection,\n private R: RelateModule,\n private store: Store,\n ) {\n for (const t of pack.tools) this.validators.set(t.name, z.object(inputShape(t.input)).strict());\n }\n\n get model(): Model {\n return this.pack.model;\n }\n\n get tools(): ToolSpec[] {\n return this.pack.tools;\n }\n\n /** Opens (or creates) a graph's store on this machine. Every graph uses the Claims and Questions model. */\n static async open(opts: { name?: string; dataDir?: string; embedder?: Embedder; log?(msg: string): void } = {}): Promise<Graph> {\n const name = opts.name ?? process.env.VINE_GRAPH ?? \"default\";\n if (!/^[a-z0-9][a-z0-9-]{0,62}$/.test(name)) throw new ToolError(`Graph names are lower-case letters, digits and dashes: '${name}'.`);\n const dir = join(opts.dataDir ?? defaultDataDir(), \"graphs\", name);\n mkdirSync(dir, { recursive: true });\n const R = await loadRelate();\n let store = openStores.get(dir);\n if (!store) {\n const db = R.Database.open(dir);\n store = { db, conn: db.connect(), queue: Promise.resolve() };\n openStores.set(dir, store);\n }\n const { db, conn } = store;\n const embedder = opts.embedder ?? makeEmbedder(undefined, opts.log);\n const found = conn.query(\"MATCH (m:_VineMeta {key: 'meta'}) RETURN m {.*} AS m\").rows[0]?.m as Meta | undefined;\n const pack = claimsPack();\n if (found && found.model !== pack.model.name)\n throw new ToolError(`Graph '${name}' uses the model '${found.model}', which this version of vine-context no longer supports (only '${pack.model.name}').`);\n const graph = new Graph(name, dir, pack, embedder, db, conn, R, store);\n if (found && found.embedder !== embedder.name) {\n opts.log?.(`graph '${name}': its vectors were made by ${found.embedder}; making them again with ${embedder.name}`);\n graph.reembed();\n }\n graph.applyModel(found);\n return graph;\n }\n\n /**\n * Replaces every search vector with this graph's embedder's, after the graph\n * was last written with another. Vectors are made from the text and are never\n * sent to peers, so this changes nothing a peer can see. The index is dropped\n * first because the new vectors may have another length; applyModel makes it again.\n */\n private reembed(): void {\n const { search, nodes } = this.pack.model;\n if (!search) return;\n this.conn.query(\"DROP INDEX search_embedding IF EXISTS\");\n this.conn.begin();\n try {\n for (const label of search.labels) {\n const key = nodes[label]?.key;\n if (!key) throw new Error(`'${label}' is searched but has no key to re-embed it by`);\n const rows = this.conn.query(`MATCH (n:${label}) RETURN n.${key} AS key, n.${search.text} AS text`).rows;\n for (const row of rows) {\n const text = typeof row.text === \"string\" ? row.text : \"\";\n const embedding = contentWords(text).length ? this.embedder.embed(text) : null;\n this.conn.query(`MATCH (n:${label} {${key}: $key}) SET n.embedding = $embedding`, { key: String(row.key), embedding });\n }\n }\n this.conn.commit();\n } catch (e) {\n this.conn.rollback();\n throw new Error(`re-embedding graph '${this.name}' with '${this.embedder.name}' failed: ${(e as Error).message}`);\n }\n }\n\n private applyModel(found: Meta | undefined): void {\n const { model } = this.pack;\n const q = (s: string) => this.conn.query(s);\n for (const [label, node] of Object.entries(model.nodes))\n if (node.key) q(`CREATE CONSTRAINT ${label.toLowerCase()}_${node.key}_key IF NOT EXISTS FOR (n:${label}) REQUIRE n.${node.key} IS UNIQUE`);\n if (model.search) {\n const labels = model.search.labels.join(\"|\");\n q(\n `CREATE VECTOR INDEX search_embedding IF NOT EXISTS FOR (n:${labels}) ON (n.embedding) ` +\n `OPTIONS {indexConfig: {\\`vector.dimensions\\`: ${this.embedder.dim}, \\`vector.similarity_function\\`: 'cosine'}}`,\n );\n q(`CREATE FULLTEXT INDEX search_text IF NOT EXISTS FOR (n:${labels}) ON EACH [n.${model.search.text}]`);\n }\n const applied = new Set(found?.migrations ?? []);\n for (const m of this.pack.migrations) {\n if (applied.has(m.name)) continue;\n this.conn.begin();\n try {\n for (const stmt of m.cypher.split(/;\\s*(?:\\n|$)/).map((s) => s.trim()).filter(Boolean)) q(stmt);\n this.conn.commit();\n } catch (e) {\n this.conn.rollback();\n throw new Error(`migration ${m.name} failed: ${(e as Error).message}`);\n }\n applied.add(m.name);\n }\n this.conn.query(\n \"MERGE (m:_VineMeta {key: 'meta'}) SET m.model = $model, m.model_version = $version, \" +\n \"m.embedder = $embedder, m.embedding_dim = $dim, m.migrations = $migrations\",\n {\n model: model.name,\n version: model.version,\n embedder: this.embedder.name,\n dim: this.embedder.dim,\n migrations: [...applied].sort(),\n },\n );\n this.db.checkpoint();\n }\n\n /** Runs calls one at a time, in order. */\n private serial<T>(fn: () => Promise<T>): Promise<T> {\n const run = this.store.queue.then(fn, fn);\n this.store.queue = run.catch(() => undefined);\n return run;\n }\n\n private async rows(cypher: string, params: Record<string, unknown> = {}): Promise<Record<string, unknown>[]> {\n try {\n const r = await this.conn.queryAsync(cypher, params as never);\n return r.rows.map((row) => toJson(row, this.R) as Record<string, unknown>);\n } catch (e) {\n if (e instanceof this.R.RelateError) throw new QueryError(`The graph refused the query: ${e.message}`);\n throw e;\n }\n }\n\n private tool(toolName: string, caller: Caller): { tool: ToolSpec; input: Record<string, unknown> } & { parse(args: unknown): Record<string, unknown> } {\n const tool = this.pack.tools.find((t) => t.name === toolName);\n if (!tool) throw new ToolError(`No tool '${toolName}' in the model '${this.model.name}'.`);\n if (RANK[caller.role] < RANK[tool.role]) throw new ToolError(`'${toolName}' needs the ${tool.role} role; you are a ${caller.role}.`);\n const validator = this.validators.get(tool.name)!;\n return {\n tool,\n input: {},\n parse(args: unknown) {\n const parsed = validator.safeParse(args ?? {});\n if (!parsed.success)\n throw new ToolError(\"Invalid input:\\n\" + parsed.error.issues.map((i) => `- ${i.path.join(\".\") || \"(input)\"}: ${i.message}`).join(\"\\n\"));\n return parsed.data as Record<string, unknown>;\n },\n };\n }\n\n /** The parameters a tool's Cypher sees: its input, the server's own, and the derived ones. */\n private params(tool: ToolSpec, input: Record<string, unknown>, caller: Caller, now: string, embed: boolean): Record<string, unknown> {\n const params: Record<string, unknown> = {};\n for (const name of Object.keys(tool.input)) params[name] = input[name] ?? null;\n params.now = now;\n params.by = caller.id;\n params.key = caller.key ?? null;\n params.role = caller.role;\n for (const [name, d] of Object.entries(tool.derive)) {\n if (\"new_id\" in d) params[name] = newId(d.new_id);\n else if (\"embed\" in d) {\n const text = input[d.embed];\n if (typeof text !== \"string\") params[name] = null;\n else if (!contentWords(text).length) throw new ToolError(`'${d.embed}' needs at least one letter or digit.`);\n else params[name] = embed ? this.embedder.embed(text) : null;\n } else if (\"terms\" in d) {\n const text = input[d.terms];\n params[name] = typeof text === \"string\" ? contentWords(text).join(\" \") || null : null;\n }\n }\n return params;\n }\n\n /** Runs a tool's steps; a row with `_error` fails the call. Read tools only change nothing; checks are rolled back. */\n private async runSteps(tool: ToolSpec, params: Record<string, unknown>, commit: boolean): Promise<unknown> {\n this.conn.begin();\n try {\n const out: Record<string, unknown> = {};\n let last: unknown = null;\n for (const [i, step] of tool.steps.entries()) {\n const used = Object.fromEntries(Object.entries(params).filter(([k]) => new RegExp(`\\\\$${k}\\\\b`).test(step.cypher)));\n const result = await this.conn.queryAsync(step.cypher, used as never);\n const failed = result.rows.find((r) => r._error !== null && r._error !== undefined);\n if (failed) throw new ToolError(String(failed._error));\n const rows = result.rows.map((r) => {\n const { _error, ...rest } = r;\n return toJson(rest, this.R) as Record<string, unknown>;\n });\n const value = step.single ? (rows[0] ?? null) : rows;\n if (step.name) out[step.name] = value;\n if (i === tool.steps.length - 1) last = value;\n }\n if (commit) this.conn.commit();\n else this.conn.rollback();\n return Object.keys(out).length ? out : last;\n } catch (e) {\n this.conn.rollback();\n if (e instanceof ToolError) throw e;\n if (e instanceof this.R.RelateError) throw new QueryError(`The graph refused the query: ${e.message}`);\n throw e;\n }\n }\n\n /** Runs one of the model's read tools. */\n async call(toolName: string, args: unknown, caller: Caller): Promise<unknown> {\n const t = this.tool(toolName, caller);\n if (t.tool.kind === \"write\") throw new ToolError(`'${toolName}' is a write: it goes through the change log (prepare, then apply).`);\n const input = t.parse(args);\n const params = this.params(t.tool, input, caller, new Date().toISOString(), true);\n return this.serial(() => this.runSteps(t.tool, params, false));\n }\n\n /** Checks a write tool's input against the graph as this machine has it, and says what change it makes. */\n async prepare(toolName: string, args: unknown, caller: Caller, now = new Date().toISOString()): Promise<Prepared> {\n const t = this.tool(toolName, caller);\n if (t.tool.kind !== \"write\" || !t.tool.apply) throw new ToolError(`'${toolName}' is not a write.`);\n const input = t.parse(args);\n const params = this.params(t.tool, input, caller, now, false);\n await this.serial(() => this.runSteps(t.tool, params, false));\n switch (t.tool.apply) {\n case \"claim\":\n return {\n kind: \"claim\",\n body: {\n node: params.id,\n text: input.text,\n source: input.source ?? null,\n about_from: input.about_from ?? null,\n about_to: input.about_to ?? null,\n supports: input.supports ?? [],\n contradicts: input.contradicts ?? [],\n replaces: input.replaces ?? [],\n answers: input.answers ?? [],\n },\n };\n case \"question\":\n return { kind: \"question\", body: { node: params.id, text: input.text, about: input.about ?? [] } };\n case \"reply\":\n return { kind: \"reply\", body: { node: params.id, text: input.text, question: input.question } };\n case \"link\":\n return { kind: \"link\", body: { from: input.from, relation: input.relation, to: input.to } };\n case \"withdraw\":\n return { kind: \"withdraw\", body: { node: input.id, reason: input.reason ?? null } };\n }\n }\n\n // ---- Applying changes -------------------------------------------------\n\n /**\n * Applies one data change to the store. Membership has already been\n * checked by the caller (the author could make this change at that time).\n */\n async apply(c: Pick<Change, \"id\" | \"kind\" | \"author\" | \"at\" | \"body\">, ctx: ApplyContext): Promise<Applied> {\n return this.serial(async () => {\n this.conn.begin();\n try {\n const out = await this.applyOne(c, ctx);\n if (out.status === \"applied\" && (c.kind === \"claim\" || c.kind === \"question\" || c.kind === \"reply\")) await this.retryPending(ctx);\n this.conn.commit();\n return out;\n } catch (e) {\n this.conn.rollback();\n if (e instanceof this.R.RelateError) throw new QueryError(`The graph refused a change: ${e.message}`);\n throw e;\n }\n });\n }\n\n private async applyOne(c: Pick<Change, \"id\" | \"kind\" | \"author\" | \"at\" | \"body\">, ctx: ApplyContext): Promise<Applied> {\n const b = c.body;\n const by = ctx.name(c.author);\n switch (c.kind) {\n case \"claim\":\n case \"question\": {\n const label = c.kind === \"claim\" ? \"Claim\" : \"Question\";\n const node = str(b.node, 64);\n const text = str(b.text, c.kind === \"claim\" ? 2000 : 1000);\n if (!node || !text || !node.startsWith(c.kind === \"claim\" ? \"c_\" : \"q_\")) return { status: \"refused\", reason: \"bad node or text\" };\n const exists = await this.rows(`OPTIONAL MATCH (n:Claim|Question {id: $node}) RETURN n.change AS change`, { node });\n if (exists[0]?.change !== null && exists[0]?.change !== undefined)\n return exists[0].change === c.id ? { status: \"applied\", result: { id: node, recorded_at: c.at } } : { status: \"refused\", reason: `${node} already exists` };\n const embedding = contentWords(text).length ? this.embedder.embed(text) : null;\n await this.rows(\n `CREATE (n:${label} {id: $node, text: $text, embedding: $embedding, recorded_at: datetime($at), recorded_by: $by, author: $author, change: $change})` +\n (c.kind === \"claim\"\n ? ` SET n.source = $source, n.about_from = CASE WHEN $about_from IS NULL THEN null ELSE date($about_from) END, n.about_to = CASE WHEN $about_to IS NULL THEN null ELSE date($about_to) END`\n : \"\"),\n { node, text, embedding, at: c.at, by, author: c.author, change: c.id, ...(c.kind === \"claim\" ? { source: str(b.source, 500), about_from: day(b.about_from), about_to: day(b.about_to) } : {}) },\n );\n const links: [string, string[]][] =\n c.kind === \"claim\"\n ? [\n [\"SUPPORTS\", isArray(b.supports)],\n [\"CONTRADICTS\", isArray(b.contradicts)],\n [\"REPLACES\", isArray(b.replaces)],\n [\"ANSWERS\", isArray(b.answers)],\n ]\n : [[\"ABOUT\", isArray(b.about)]];\n const counts: Record<string, number> = {};\n for (const [rel, targets] of links) {\n counts[rel.toLowerCase()] = 0;\n for (const to of targets) {\n const r = await this.link({ change: c.id, author: c.author, at: c.at, from: node, relation: rel, to }, ctx);\n if (r.status === \"applied\") counts[rel.toLowerCase()]!++;\n else if (r.status === \"pending\") await this.addPending(c.id, \"edge\", { change: c.id, author: c.author, at: c.at, from: node, relation: rel, to });\n }\n }\n return { status: \"applied\", result: { id: node, recorded_at: c.at, ...counts } };\n }\n case \"reply\": {\n const node = str(b.node, 64);\n const text = str(b.text, 2000);\n const question = str(b.question, 64);\n if (!node || !text || !question || !node.startsWith(\"r_\")) return { status: \"refused\", reason: \"bad reply\" };\n const exists = await this.rows(`OPTIONAL MATCH (n:Reply {id: $node}) RETURN n.change AS change`, { node });\n if (exists[0]?.change !== null && exists[0]?.change !== undefined)\n return exists[0].change === c.id ? { status: \"applied\", result: { id: node, recorded_at: c.at } } : { status: \"refused\", reason: `${node} already exists` };\n await this.rows(`CREATE (n:Reply {id: $node, text: $text, recorded_at: datetime($at), recorded_by: $by, author: $author, change: $change})`, { node, text, at: c.at, by, author: c.author, change: c.id });\n const e = { change: c.id, author: c.author, at: c.at, from: node, relation: \"REPLIES_TO\", to: question };\n const r = await this.link(e, ctx);\n if (r.status === \"pending\") await this.addPending(c.id, \"edge\", e);\n return { status: \"applied\", result: { id: node, question, recorded_at: c.at } };\n }\n case \"link\": {\n const from = str(b.from, 64);\n const to = str(b.to, 64);\n const relation = str(b.relation, 20);\n if (!from || !to || !relation || !REL_TYPES.has(relation) || relation === \"ABOUT\" || relation === \"REPLIES_TO\") return { status: \"refused\", reason: \"bad link\" };\n const r = await this.link({ change: c.id, author: c.author, at: c.at, from, relation, to }, ctx);\n if (r.status === \"pending\") await this.addPending(c.id, \"edge\", { change: c.id, author: c.author, at: c.at, from, relation, to });\n return r.status === \"applied\" ? { status: \"applied\", result: { from, relation, to } } : r;\n }\n case \"withdraw\": {\n const node = str(b.node, 64);\n if (!node) return { status: \"refused\", reason: \"bad withdraw\" };\n const r = await this.withdraw({ change: c.id, author: c.author, at: c.at, node, reason: str(b.reason, 500) }, ctx);\n if (r.status === \"pending\") await this.addPending(c.id, \"withdraw\", { change: c.id, author: c.author, at: c.at, node, reason: str(b.reason, 500) });\n return r;\n }\n }\n return { status: \"refused\", reason: `not a data change: ${c.kind}` };\n }\n\n /** Creates a link between two existing items, keeping the earlier of two equal links. */\n private async link(e: { change: string; author: string; at: string; from: string; relation: string; to: string }, ctx: ApplyContext): Promise<Applied> {\n if (e.from === e.to) return { status: \"refused\", reason: \"an item can't link to itself\" };\n const ends = await this.rows(\n `OPTIONAL MATCH (a:Claim|Question|Reply {id: $from}) OPTIONAL MATCH (b:Claim|Question {id: $to}) ` +\n `RETURN a IS NOT NULL AS a, b IS NOT NULL AS b, a:Claim AS a_claim, a:Reply AS a_reply, b:Claim AS b_claim, b:Question AS b_question`,\n { from: e.from, to: e.to },\n );\n const x = ends[0] ?? {};\n const waiting = [...(x.a ? [] : [e.from]), ...(x.b ? [] : [e.to])];\n if (waiting.length) return { status: \"pending\", waiting };\n const fromLabel = x.a_claim ? \"Claim\" : x.a_reply ? \"Reply\" : \"Question\";\n const toLabel = x.b_claim ? \"Claim\" : \"Question\";\n const ok =\n e.relation === \"REPLIES_TO\"\n ? fromLabel === \"Reply\" && toLabel === \"Question\"\n : fromLabel === \"Reply\"\n ? false\n : e.relation === \"ABOUT\"\n ? fromLabel === \"Question\"\n : fromLabel === \"Claim\" && (CLAIM_RELS.has(e.relation) ? toLabel === \"Claim\" : e.relation === \"ANSWERS\" && toLabel === \"Question\");\n if (!ok) return { status: \"refused\", reason: `${e.relation} can't link a ${fromLabel} to a ${toLabel}` };\n const existing = await this.rows(`MATCH (a:${fromLabel} {id: $from})-[r:${e.relation}]->(b:${toLabel} {id: $to}) RETURN r.recorded_at AS at, r.change AS change`, e);\n const by = ctx.name(e.author);\n if (!existing.length) {\n await this.rows(\n `MATCH (a:${fromLabel} {id: $from}), (b:${toLabel} {id: $to}) CREATE (a)-[:${e.relation} {recorded_at: datetime($at), recorded_by: $by, author: $author, change: $change}]->(b)`,\n { ...e, by },\n );\n } else if (existing[0]!.change !== e.change && Date.parse(e.at) < Date.parse(String(existing[0]!.at))) {\n await this.rows(\n `MATCH (a:${fromLabel} {id: $from})-[r:${e.relation}]->(b:${toLabel} {id: $to}) SET r.recorded_at = datetime($at), r.recorded_by = $by, r.author = $author, r.change = $change`,\n { ...e, by },\n );\n }\n return { status: \"applied\", result: { from: e.from, relation: e.relation, to: e.to } };\n }\n\n private async withdraw(w: { change: string; author: string; at: string; node: string; reason: string | null }, ctx: ApplyContext): Promise<Applied> {\n const found = await this.rows(`OPTIONAL MATCH (n:Claim|Question|Reply {id: $node}) RETURN n IS NOT NULL AS found, n.author AS author, n.recorded_by AS by, n.withdrawn_at AS w`, { node: w.node });\n const n = found[0] ?? {};\n if (!n.found) return { status: \"pending\", waiting: [w.node] };\n const own = n.author ? n.author === w.author : n.by === ctx.name(w.author);\n if (!own && !ctx.isAdmin(w.author, w.at)) return { status: \"refused\", reason: \"only its author or an admin can withdraw it\" };\n if (n.w === null || n.w === undefined || Date.parse(w.at) < Date.parse(String(n.w)))\n await this.rows(\n `MATCH (n:Claim|Question|Reply {id: $node}) SET n.withdrawn_at = datetime($at), n.withdrawn_by = $by, n.withdrawn_author = $author, n.withdraw_reason = $reason, n.withdraw_change = $change`,\n { ...w, by: ctx.name(w.author) },\n );\n return { status: \"applied\", result: { id: w.node, withdrawn_at: w.at } };\n }\n\n private async addPending(change: string, kind: \"edge\" | \"withdraw\", data: Record<string, unknown>) {\n await this.rows(`CREATE (:_VinePending {change: $change, kind: $kind, data: $data})`, { change, kind, data: JSON.stringify(data) });\n }\n\n /** Retries links and withdrawals that were waiting for an item that may now exist. */\n private async retryPending(ctx: ApplyContext) {\n for (let round = 0; round < 3; round++) {\n const pending = await this.rows(`MATCH (p:_VinePending) RETURN p.change AS change, p.kind AS kind, p.data AS data`);\n if (!pending.length) return;\n let progress = false;\n for (const p of pending) {\n const d = JSON.parse(String(p.data));\n const r = p.kind === \"edge\" ? await this.link(d, ctx) : await this.withdraw(d, ctx);\n if (r.status !== \"pending\") {\n await this.rows(`MATCH (p:_VinePending {change: $change, kind: $kind, data: $data}) DELETE p`, { change: p.change, kind: p.kind, data: p.data });\n progress = true;\n }\n }\n if (!progress) return;\n }\n }\n\n /** Takes back a claim or question this machine just made and hasn't sent: it was never shared. */\n async discard(changeId: string): Promise<boolean> {\n return this.serial(async () => {\n const found = await this.rows(`MATCH (n:Claim|Question|Reply {change: $change}) RETURN count(n) AS n`, { change: changeId });\n await this.rows(`MATCH (n:Claim|Question|Reply {change: $change}) DETACH DELETE n`, { change: changeId });\n await this.rows(`MATCH (p:_VinePending {change: $change}) DELETE p`, { change: changeId });\n return Number(found[0]?.n ?? 0) > 0;\n });\n }\n\n /** Empties the store (keeping the model's indexes), to build it again from the log. */\n async reset(): Promise<void> {\n await this.serial(async () => {\n await this.rows(`MATCH (n) WHERE NOT n:_VineMeta DETACH DELETE n`);\n await this.rows(`MATCH (m:_VineMeta {key: 'meta'}) SET m.applied = null`);\n });\n }\n\n /** Records which changes the store holds (a digest of their ids, in the order applied). */\n async setApplied(digest: string): Promise<void> {\n await this.serial(() => this.rows(`MATCH (m:_VineMeta {key: 'meta'}) SET m.applied = $digest`, { digest }));\n }\n\n async getApplied(): Promise<string | null> {\n const r = await this.serial(() => this.rows(`MATCH (m:_VineMeta {key: 'meta'}) RETURN m.applied AS applied`));\n return (r[0]?.applied as string | null) ?? null;\n }\n\n /** Puts each member's current name on what they recorded (after a rename). */\n async refreshNames(names: Map<string, string>): Promise<void> {\n await this.serial(async () => {\n for (const [key, name] of names) {\n await this.rows(`MATCH (n:Claim|Question|Reply) WHERE n.author = $key AND n.recorded_by <> $name SET n.recorded_by = $name`, { key, name });\n await this.rows(`MATCH (n:Claim|Question|Reply) WHERE n.withdrawn_author = $key AND n.withdrawn_by <> $name SET n.withdrawn_by = $name`, { key, name });\n await this.rows(`MATCH ()-[r]->() WHERE r.author = $key AND r.recorded_by <> $name SET r.recorded_by = $name`, { key, name });\n }\n });\n }\n\n /**\n * Items by id, with what the sync digest needs: kind, text, author, and\n * whether each is current (not withdrawn, and for a claim not replaced by a\n * current claim).\n */\n async items(ids: string[]): Promise<Map<string, { id: string; label: \"Claim\" | \"Question\"; text: string; author: string | null; by: string; current: boolean }>> {\n const out = new Map<string, { id: string; label: \"Claim\" | \"Question\"; text: string; author: string | null; by: string; current: boolean }>();\n const unique = [...new Set(ids)].filter((x) => typeof x === \"string\").slice(0, 500);\n if (!unique.length) return out;\n const rows = await this.serial(() =>\n this.rows(\n `MATCH (n:Claim|Question) WHERE n.id IN $ids ` +\n `RETURN n.id AS id, labels(n) AS labels, n.text AS text, n.author AS author, n.recorded_by AS by, ` +\n `n.withdrawn_at IS NULL AND NOT EXISTS { MATCH (r:Claim)-[:REPLACES]->(n) WHERE r.withdrawn_at IS NULL } AS current`,\n { ids: unique },\n ),\n );\n for (const r of rows)\n out.set(String(r.id), {\n id: String(r.id),\n label: (r.labels as string[]).includes(\"Claim\") ? \"Claim\" : \"Question\",\n text: String(r.text ?? \"\"),\n author: (r.author as string | null) ?? null,\n by: String(r.by ?? \"\"),\n current: Boolean(r.current),\n });\n return out;\n }\n\n /** The claims that replace this one and are themselves current: two or more means a conflict nobody settled. */\n async currentReplacers(id: string): Promise<{ id: string; text: string; by: string }[]> {\n const rows = await this.serial(() =>\n this.rows(\n `MATCH (r:Claim)-[:REPLACES]->(:Claim {id: $id}) WHERE r.withdrawn_at IS NULL ` +\n `AND NOT EXISTS { MATCH (newer:Claim)-[:REPLACES]->(r) WHERE newer.withdrawn_at IS NULL } ` +\n `RETURN r.id AS id, r.text AS text, r.recorded_by AS by ORDER BY r.recorded_at`,\n { id },\n ),\n );\n return rows.map((r) => ({ id: String(r.id), text: String(r.text ?? \"\"), by: String(r.by ?? \"\") }));\n }\n\n /** The ids of items linked to or from this one, either way. */\n async linkedIds(id: string): Promise<Set<string>> {\n const rows = await this.serial(() => this.rows(`MATCH (n:Claim|Question {id: $id})-[]-(m:Claim|Question) RETURN m.id AS id`, { id }));\n return new Set(rows.map((r) => String(r.id)));\n }\n\n /** The model summary and its instructions, for agents (the model_guide tool). */\n guide(): string {\n const { model } = this;\n const shape = [\n `# Model: ${model.title} (${model.name} v${model.version})`,\n \"\",\n model.description,\n \"\",\n \"## Nodes\",\n ...Object.entries(model.nodes).map(([l, n]) => `- **${l}**: ${n.description}`),\n \"\",\n \"## Relationships\",\n ...Object.entries(model.relationships).map(([t, r]) => `- **${t}** (${r.from.join(\"|\")} → ${r.to.join(\"|\")}): ${r.description}`),\n ].join(\"\\n\");\n return `${shape}\\n\\n${this.pack.instructions}`.trim();\n }\n\n /** Everything a client needs to offer this graph's tools, for one caller. */\n describe(host: string, you: Caller): GraphDescription {\n const { model } = this;\n return {\n graph: this.name,\n host,\n model: { name: model.name, version: model.version, title: model.title, description: model.description },\n guide: this.guide(),\n schema: this.schema(),\n tools: this.tools.map((t) => ({\n name: t.name,\n title: t.title,\n description: t.description,\n kind: t.kind,\n role: t.role,\n input: t.input,\n ...(t.view ? { view: t.view } : {}),\n ...(t.undo ? { undo: t.undo } : {}),\n })),\n you,\n };\n }\n\n /** The model's shape, for views: labels with their title property, and relationship types. */\n schema(): SnapshotSchema {\n const { model } = this;\n return {\n nodes: Object.entries(model.nodes).map(([label, n]) => ({\n label,\n description: n.description,\n key: n.key ?? null,\n title: n.title ?? (model.search && n.properties[model.search.text] ? model.search.text : (n.key ?? null)),\n properties: Object.entries(n.properties).map(([name, p]) => ({ name, type: p.type, required: p.required, description: p.description ?? null })),\n })),\n relationships: Object.entries(model.relationships).map(([type, r]) => ({ type, description: r.description, from: r.from, to: r.to })),\n time: model.time ?? null,\n };\n }\n\n /**\n * The graph as it stood at `at` (default now): its nodes, newest first, and\n * the relationships between them. Works for any model: it reads the labels\n * and relationship types from model.yaml, and the time properties from its\n * `time` section if it has one.\n */\n async snapshot(o: { at?: string; limit?: number } = {}): Promise<Snapshot> {\n const at = o.at ?? new Date().toISOString();\n if (Number.isNaN(Date.parse(at))) throw new ToolError(`'at' must be an ISO 8601 date-time: '${at}'.`);\n const limit = Math.min(Math.max(Math.trunc(o.limit ?? 200), 1), 1000);\n const schema = this.schema();\n const time = this.model.time;\n return this.serial(async () => {\n const nodes: SnapshotNode[] = [];\n for (const n of schema.nodes) {\n if (!n.key) continue; // nodes without a key can't be linked to in a view\n const when = time ? `WHERE n.${time.recorded} IS NULL OR n.${time.recorded} <= datetime($at)` : \"\";\n const order = time ? `ORDER BY n.${time.recorded} DESC` : \"\";\n const r = await this.conn.queryAsync(`MATCH (n:${n.label}) ${when} RETURN n {.*} AS n ${order} LIMIT $limit`, { at, limit } as never);\n for (const row of r.rows) {\n const props = toJson(row.n, this.R) as Record<string, unknown>;\n const ended = time?.ended ? (props[time.ended] as string | undefined) : undefined;\n nodes.push({\n id: `${n.label}:${String(props[n.key])}`,\n key: String(props[n.key]),\n label: n.label,\n title: String(props[n.title ?? n.key] ?? props[n.key]),\n ended: Boolean(ended && Date.parse(ended) <= Date.parse(at)),\n props,\n });\n }\n }\n nodes.sort((a, b) => recordedOf(b, time) - recordedOf(a, time));\n const kept = nodes.slice(0, limit);\n const ids = new Set(kept.map((n) => n.id));\n const edges: SnapshotEdge[] = [];\n const keyOf = new Map(schema.nodes.map((n) => [n.label, n.key]));\n for (const rel of schema.relationships)\n for (const from of rel.from)\n for (const to of rel.to) {\n const fk = keyOf.get(from);\n const tk = keyOf.get(to);\n if (!fk || !tk) continue;\n const when = time ? `WHERE r.${time.recorded} IS NULL OR r.${time.recorded} <= datetime($at)` : \"\";\n const r = await this.conn.queryAsync(\n `MATCH (a:${from})-[r:${rel.type}]->(b:${to}) ${when} RETURN a.${fk} AS a, b.${tk} AS b, r {.*} AS r`,\n { at } as never,\n );\n for (const row of r.rows) {\n const source = `${from}:${String(row.a)}`;\n const target = `${to}:${String(row.b)}`;\n if (ids.has(source) && ids.has(target))\n edges.push({ type: rel.type, source, target, props: toJson(row.r, this.R) as Record<string, unknown> });\n }\n }\n return { graph: this.name, model: this.model.name, at, schema, nodes: kept, edges, truncated: nodes.length > kept.length };\n });\n }\n\n /** The model, its tools and the size of the graph. */\n async info(): Promise<Record<string, unknown>> {\n return this.serial(async () => {\n const counts: Record<string, number> = {};\n for (const label of Object.keys(this.model.nodes)) {\n const r = await this.conn.queryAsync(`MATCH (n:${label}) RETURN count(n) AS n`);\n counts[label] = Number(r.rows[0]?.n ?? 0);\n }\n return {\n graph: this.name,\n model: { name: this.model.name, version: this.model.version, title: this.model.title, description: this.model.description },\n nodes: counts,\n tools: this.tools.map((t) => ({ name: t.name, kind: t.kind, role: t.role })),\n embedder: this.embedder.name,\n };\n });\n }\n}\n","// The wire protocol between a host and its clients, used both on the local\n// socket and over WebRTC data channels: one JSON object per message.\n//\n// {t: \"req\", id, method, params} client → host\n// {t: \"res\", id, result} host → client\n// {t: \"res\", id, error: {message}} host → client\n// {t: \"evt\", event, data} host → clients, unprompted\n//\n// The host decides which methods each kind of client may call: local clients\n// are the host's own user, peers only get describe, call and info.\n\nimport type { InputSpecT } from \"../core/pack.js\";\nimport type { Role, SnapshotSchema } from \"../core/graph.js\";\n\nexport type Request = { t: \"req\"; id: number; method: string; params?: unknown };\nexport type Response = { t: \"res\"; id: number; result?: unknown; error?: { message: string } };\nexport type Event = { t: \"evt\"; event: string; data?: unknown };\nexport type Message = Request | Response | Event;\n\nexport interface ToolDescriptor {\n name: string;\n title?: string;\n description: string;\n kind: \"read\" | \"write\";\n role: Role;\n input: Record<string, InputSpecT>;\n view?: \"receipt\" | \"conflicts\";\n undo?: { tool: string; arg: string; field: string };\n}\n\n/** What a client needs to offer a host's graph as MCP tools. */\nexport interface GraphDescription {\n graph: string;\n host: string;\n model: { name: string; version: number; title: string; description: string };\n guide: string;\n schema: SnapshotSchema;\n tools: ToolDescriptor[];\n you: { id: string; role: Role };\n}\n\n/** Methods a peer may call. Everything else is for the host's own user. */\nexport const PEER_METHODS = new Set([\"describe\", \"call\", \"info\", \"snapshot\"]);\n\nexport class RemoteError extends Error {}\n\n/** Matches responses to requests, for any transport that delivers whole messages. */\nexport class RpcClient {\n private next = 1;\n private pending = new Map<number, { resolve: (v: unknown) => void; reject: (e: Error) => void; timer: NodeJS.Timeout }>();\n\n constructor(\n private sendRaw: (m: Message) => void,\n private timeoutMs = 30_000,\n ) {}\n\n request<T = unknown>(method: string, params?: unknown): Promise<T> {\n const id = this.next++;\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n this.pending.delete(id);\n reject(new RemoteError(`The host did not answer '${method}' within ${this.timeoutMs / 1000}s.`));\n }, this.timeoutMs);\n this.pending.set(id, { resolve: resolve as (v: unknown) => void, reject, timer });\n try {\n this.sendRaw({ t: \"req\", id, method, params });\n } catch (e) {\n clearTimeout(timer);\n this.pending.delete(id);\n reject(e as Error);\n }\n });\n }\n\n /** Feed every response here. Returns false for messages that are not responses. */\n handle(m: Message): boolean {\n if (m.t !== \"res\") return false;\n const p = this.pending.get(m.id);\n if (!p) return true;\n this.pending.delete(m.id);\n clearTimeout(p.timer);\n if (m.error) p.reject(new RemoteError(m.error.message));\n else p.resolve(m.result);\n return true;\n }\n\n failAll(reason: string): void {\n for (const p of this.pending.values()) {\n clearTimeout(p.timer);\n p.reject(new RemoteError(reason));\n }\n this.pending.clear();\n }\n}\n\n/** Splits a stream of bytes into newline-delimited JSON messages. */\nexport function lineReader(onMessage: (m: Message) => void): (chunk: Buffer | string) => void {\n let buf = \"\";\n return (chunk) => {\n buf += chunk.toString();\n let i: number;\n while ((i = buf.indexOf(\"\\n\")) >= 0) {\n const line = buf.slice(0, i);\n buf = buf.slice(i + 1);\n if (!line.trim()) continue;\n try {\n onMessage(JSON.parse(line));\n } catch {\n // ignore malformed lines\n }\n }\n };\n}\n","// Host-side state that lives beside a graph, never inside it: where the local\n// socket is, which peers the host has approved, and its invites.\n\nimport { createHash, randomBytes } from \"node:crypto\";\nimport { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { Role } from \"../core/graph.js\";\nimport { b64u, formatCode, unb64u, type Link } from \"../p2p/link.js\";\n\n/** The local socket for a graph's host. Unix socket paths are limited to ~104 bytes, so long ones move to the temp folder. */\nexport function socketPath(dataDir: string, graph: string): string {\n if (process.platform === \"win32\") {\n const h = createHash(\"sha256\").update(`${dataDir}\\0${graph}`).digest(\"hex\").slice(0, 16);\n return `\\\\\\\\.\\\\pipe\\\\vine-${h}`;\n }\n const preferred = join(dataDir, \"run\", `${graph}.sock`);\n if (Buffer.byteLength(preferred) <= 100) return preferred;\n const h = createHash(\"sha256\").update(`${dataDir}\\0${graph}`).digest(\"hex\").slice(0, 16);\n return join(process.platform === \"darwin\" ? \"/tmp\" : tmpdir(), `vine-${h}.sock`);\n}\n\nexport function hostDir(dataDir: string, graph: string): string {\n const dir = join(dataDir, \"hosts\", graph);\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n return dir;\n}\n\n/**\n * One join code. It works for one machine: the first key that uses it is let\n * in and bound to it, and from then on only that key gets in with it (that is\n * how the person rejoins in later sessions). An unused invite expires.\n */\nexport interface Invite {\n id: string;\n room: string;\n secret: string;\n label?: string;\n /** The role the person gets when they first join (default contributor). */\n role?: Role;\n created_at: string;\n /** Unused invites stop working after this; bound ones don't expire. */\n expires_at: string;\n bound?: { key: string; name: string; at: string };\n revoked?: { at: string; reason: string };\n}\n\nexport type InviteState = \"open\" | \"used\" | \"expired\" | \"revoked\";\n\nexport const DEFAULT_INVITE_HOURS = 24;\nconst MAX_LIVE_INVITES = 50;\nconst KEEP_DEAD_MS = 7 * 24 * 3600_000;\n\nexport const inviteLink = (i: Invite): Link => ({ room: i.room, secret: unb64u(i.secret) });\n\nexport function inviteState(i: Invite, now = Date.now()): InviteState {\n if (i.revoked) return \"revoked\";\n if (i.bound) return \"used\";\n return Date.parse(i.expires_at) <= now ? \"expired\" : \"open\";\n}\n\n/** A live invite is one the host listens for: open, or bound to someone. */\nexport const isLive = (i: Invite, now = Date.now()) => [\"open\", \"used\"].includes(inviteState(i, now));\n\n/** The host's invites, by id. Written atomically, readable only by the host's user. */\nexport class InviteStore {\n private file: string;\n private invites = new Map<string, Invite>();\n\n constructor(dir: string) {\n this.file = join(dir, \"invites.json\");\n if (existsSync(this.file)) for (const i of JSON.parse(readFileSync(this.file, \"utf8\")) as Invite[]) this.invites.set(i.id, i);\n // Forget invites that have been dead for a week.\n const cutoff = Date.now() - KEEP_DEAD_MS;\n let pruned = false;\n for (const i of this.invites.values()) {\n const deadSince = i.revoked ? Date.parse(i.revoked.at) : !i.bound ? Date.parse(i.expires_at) : Infinity;\n if (deadSince < cutoff) {\n this.invites.delete(i.id);\n pruned = true;\n }\n }\n if (pruned) this.save();\n }\n\n create(opts: { label?: string; role?: Role; hours?: number; now?: number } = {}): Invite {\n const now = opts.now ?? Date.now();\n if (this.live(now).length >= MAX_LIVE_INVITES) throw new Error(`There are already ${MAX_LIVE_INVITES} live invites. Revoke some first.`);\n const hours = opts.hours ?? DEFAULT_INVITE_HOURS;\n if (!(hours > 0 && hours <= 24 * 30)) throw new Error(\"An invite lasts between a few minutes and 30 days (expires_hours up to 720).\");\n const room = b64u(randomBytes(16));\n const inv: Invite = {\n id: `inv_${room.replace(/[^A-Za-z0-9]/g, \"\").slice(0, 8).toLowerCase()}`,\n room,\n secret: b64u(randomBytes(32)),\n ...(opts.label ? { label: opts.label } : {}),\n ...(opts.role ? { role: opts.role } : {}),\n created_at: new Date(now).toISOString(),\n expires_at: new Date(now + hours * 3600_000).toISOString(),\n };\n this.invites.set(inv.id, inv);\n this.save();\n return inv;\n }\n\n get(id: string): Invite | undefined {\n return this.invites.get(id);\n }\n\n all(): Invite[] {\n return [...this.invites.values()];\n }\n\n live(now = Date.now()): Invite[] {\n return this.all().filter((i) => isLive(i, now));\n }\n\n bind(id: string, key: string, name: string): void {\n const i = this.invites.get(id);\n if (!i || i.bound) return;\n i.bound = { key, name, at: new Date().toISOString() };\n this.save();\n }\n\n revoke(id: string, reason: string): Invite | undefined {\n const i = this.invites.get(id);\n if (!i || i.revoked) return undefined;\n i.revoked = { at: new Date().toISOString(), reason };\n this.save();\n return i;\n }\n\n /** Revokes every invite bound to a key (the person was removed). */\n revokeForKey(key: string, reason: string): Invite[] {\n return this.all()\n .filter((i) => i.bound?.key === key && !i.revoked)\n .map((i) => this.revoke(i.id, reason)!);\n }\n\n summary(i: Invite, now = Date.now()) {\n const state = inviteState(i, now);\n return {\n id: i.id,\n label: i.label ?? null,\n role: i.role ?? \"contributor\",\n state,\n // The code is shown only while someone can still take it up.\n code: state === \"open\" ? formatCode(inviteLink(i)) : null,\n for: i.bound ? { name: i.bound.name, since: i.bound.at } : null,\n created_at: i.created_at,\n expires_at: i.bound ? null : i.expires_at,\n revoked: i.revoked ?? null,\n };\n }\n\n private save(): void {\n const tmp = `${this.file}.tmp`;\n writeFileSync(tmp, JSON.stringify(this.all(), null, 1) + \"\\n\", { mode: 0o600 });\n chmodSync(tmp, 0o600);\n renameSync(tmp, this.file);\n }\n}\n","// A client of the local host, over its socket. Starts a host in the\n// background if none is running, so the first session to need a graph brings\n// its host up and later sessions share it.\n\nimport { spawn } from \"node:child_process\";\nimport { EventEmitter } from \"node:events\";\nimport { closeSync, openSync } from \"node:fs\";\nimport { createConnection, type Socket } from \"node:net\";\nimport { join } from \"node:path\";\nimport { RpcClient, lineReader, type Message } from \"../p2p/protocol.js\";\nimport { hostDir, socketPath } from \"./state.js\";\n\nexport class LocalHost extends EventEmitter {\n private rpc: RpcClient;\n closed = false;\n\n private constructor(private sock: Socket) {\n super();\n this.rpc = new RpcClient((m) => {\n if (this.closed) throw new Error(\"The local host has stopped.\");\n sock.write(JSON.stringify(m) + \"\\n\");\n }, 60_000);\n sock.on(\n \"data\",\n lineReader((m: Message) => {\n if (this.rpc.handle(m)) return;\n if (m.t === \"evt\") this.emit(\"event\", m);\n }),\n );\n const gone = () => {\n if (this.closed) return;\n this.closed = true;\n this.rpc.failAll(\"The local host has stopped.\");\n this.emit(\"close\");\n };\n sock.on(\"close\", gone);\n sock.on(\"error\", gone);\n }\n\n static connect(path: string): Promise<LocalHost> {\n return new Promise((resolve, reject) => {\n const sock = createConnection(path);\n sock.once(\"connect\", () => resolve(new LocalHost(sock)));\n sock.once(\"error\", reject);\n });\n }\n\n request<T = unknown>(method: string, params?: unknown): Promise<T> {\n return this.rpc.request<T>(method, params);\n }\n\n close(): void {\n this.closed = true;\n this.sock.destroy();\n }\n}\n\nexport interface EnsureOptions {\n dataDir: string;\n graph: string;\n /** Seconds the background host waits with no clients before it exits. */\n idleSeconds?: number;\n /** How to run the CLI again: defaults to this process's own command line. */\n command?: { file: string; args: string[] };\n}\n\n/** Connects to the graph's host, starting one in the background if needed. */\nexport async function ensureHost(o: EnsureOptions): Promise<LocalHost> {\n const path = socketPath(o.dataDir, o.graph);\n try {\n return await LocalHost.connect(path);\n } catch {\n // no host yet: start one\n }\n const cmd = o.command ?? { file: process.execPath, args: [...process.execArgv, process.argv[1]!] };\n const args = [...cmd.args, \"host\", \"--graph\", o.graph, \"--idle\", String(o.idleSeconds ?? 600)];\n const logFile = join(hostDir(o.dataDir, o.graph), \"host.log\");\n const out = openSync(logFile, \"a\");\n const child = spawn(cmd.file, args, {\n detached: true,\n stdio: [\"ignore\", out, out],\n env: { ...process.env, VINE_DATA_DIR: o.dataDir },\n });\n let exited: number | null = null;\n child.on(\"exit\", (code) => (exited = code ?? 1));\n child.unref();\n // The child has its own handle on the log now. Holding ours would keep the host's folder\n // open, and Windows refuses to rename (or remove) a folder with a file open in it.\n closeSync(out);\n\n const deadline = Date.now() + 20_000;\n while (Date.now() < deadline) {\n await new Promise((r) => setTimeout(r, 150));\n try {\n return await LocalHost.connect(path);\n } catch {\n // Exit code 3: another host won the race to start, so keep trying to connect.\n if (exited !== null && exited !== 3) throw new Error(`The graph host failed to start (exit ${exited}). See ${logFile}.`);\n }\n }\n throw new Error(`The graph host did not start within 20s. See ${logFile}.`);\n}\n","// A graph's change log on this machine: every change it has seen, in the\n// order they arrived, one JSON line each. Plus the changes this machine made\n// that are still held (not yet numbered, signed or sent).\n\nimport { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport type { Change, Have, Unsigned } from \"./changes.js\";\n\nexport interface Held {\n change: Unsigned;\n /** When it is released (numbered, signed and sent), ms since the epoch. */\n until: number;\n}\n\nexport class ChangeLog {\n private file: string;\n private heldFile: string;\n private byId = new Map<string, Change>();\n private order: Change[] = [];\n /** seqs seen per author. */\n private seqs = new Map<string, Set<number>>();\n private held: Held[] = [];\n\n constructor(dir: string) {\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n this.file = join(dir, \"changes.jsonl\");\n this.heldFile = join(dir, \"held.json\");\n if (existsSync(this.file))\n for (const line of readFileSync(this.file, \"utf8\").split(\"\\n\")) {\n if (!line.trim()) continue;\n try {\n this.remember(JSON.parse(line) as Change);\n } catch {\n // a torn last line after a crash: skip it; the change comes back from another member\n }\n }\n if (existsSync(this.heldFile)) {\n try {\n this.held = JSON.parse(readFileSync(this.heldFile, \"utf8\")) as Held[];\n } catch {\n this.held = [];\n }\n }\n }\n\n private remember(c: Change): boolean {\n if (this.byId.has(c.id)) return false;\n const s = this.seqs.get(c.author) ?? new Set<number>();\n if (s.has(c.seq)) return false; // a second change with the same number from one author: keep the first\n s.add(c.seq);\n this.seqs.set(c.author, s);\n this.byId.set(c.id, c);\n this.order.push(c);\n return true;\n }\n\n /** Adds a change; false if it was already here. */\n add(c: Change): boolean {\n if (!this.remember(c)) return false;\n appendFileSync(this.file, JSON.stringify(c) + \"\\n\", { mode: 0o600 });\n return true;\n }\n\n has(id: string): boolean {\n return this.byId.has(id) || this.held.some((h) => h.change.id === id);\n }\n\n get(id: string): Change | undefined {\n return this.byId.get(id);\n }\n\n all(): Change[] {\n return this.order;\n }\n\n get size(): number {\n return this.order.length;\n }\n\n /** For each author, the highest number up to which this machine has every change. */\n have(): Have {\n const out: Have = {};\n for (const [author, s] of this.seqs) {\n let n = 0;\n while (s.has(n + 1)) n++;\n out[author] = n;\n }\n return out;\n }\n\n /** The changes the other side lacks, given what it has, in each author's order. */\n missing(theirs: Have): Change[] {\n return this.order\n .filter((c) => c.seq > (theirs[c.author] ?? 0))\n .sort((a, b) => (a.author === b.author ? a.seq - b.seq : a.author < b.author ? -1 : 1));\n }\n\n /** The next number for this author's own changes. */\n nextSeq(author: string): number {\n const s = this.seqs.get(author);\n return s ? Math.max(...s) + 1 : 1;\n }\n\n // Held changes: made here, applied here, not yet sent.\n\n hold(change: Unsigned, until: number): void {\n this.held.push({ change, until });\n this.saveHeld();\n }\n\n heldChanges(): Held[] {\n return this.held;\n }\n\n /** Removes a held change (taken back, or released). */\n unhold(id: string): Held | undefined {\n const i = this.held.findIndex((h) => h.change.id === id);\n if (i < 0) return undefined;\n const [h] = this.held.splice(i, 1);\n this.saveHeld();\n return h;\n }\n\n private saveHeld() {\n const tmp = `${this.heldFile}.tmp`;\n mkdirSync(dirname(tmp), { recursive: true });\n writeFileSync(tmp, JSON.stringify(this.held) + \"\\n\", { mode: 0o600 });\n renameSync(tmp, this.heldFile);\n }\n}\n","// Who is in a graph, worked out from its membership changes.\n//\n// Membership is changes in the same log as everything else, signed by an\n// admin (or, for `rename`, by the member themselves). Every machine folds them\n// in the same order (time, then author, then counter), checking each against\n// the membership as it stood at that moment, so every machine agrees on who\n// was a member, with which role, at any time. A data change is valid if its\n// author was a member with a role that allows it at the change's time.\n//\n// Conflicts between admins: removal beats a later role change (a removed key\n// stays out until it is added again); otherwise the later change wins. The\n// graph's creator can't be removed or demoted, so a graph always has an admin.\n// The context's description (what it is for, so agents can tell where a claim\n// belongs) is set by an admin with `describe`; the latest one counts.\n\nimport { compareChanges, RANK, ROLES, type Change, type Role } from \"./changes.js\";\nimport { fingerprint, NAME_RE } from \"./identity.js\";\n\nexport interface Member {\n key: string;\n name: string;\n role: Role;\n joined_at: string;\n added_by: string;\n invite?: { id: string; label: string | null };\n about?: Record<string, string>;\n creator: boolean;\n /** Set once removed; the member's later changes are refused. */\n removed_at?: string;\n /** When they took their current name: the earlier of two equal names keeps it. */\n named_at: string;\n}\n\ninterface Span {\n from: number;\n role: Role | null;\n}\n\nexport class Members {\n readonly graphId?: string;\n readonly graphName?: string;\n readonly createdAt?: string;\n /** What this context is for, as its admins described it. */\n description: string | null = null;\n descriptionSetBy: string | null = null;\n private members = new Map<string, Member>();\n private spans = new Map<string, Span[]>();\n /** Membership changes that were refused, with why: shown in status, never applied. */\n readonly refused: { id: string; reason: string }[] = [];\n\n constructor(changes: Iterable<Change>) {\n const list = [...changes].filter((c) => [\"create\", \"add_member\", \"set_role\", \"remove_member\", \"rename\", \"describe\"].includes(c.kind));\n list.sort(compareChanges);\n const create = list.find((c) => c.kind === \"create\" && c.id === c.graph);\n if (!create) return;\n this.graphId = create.graph;\n this.graphName = String(create.body.name ?? \"graph\");\n this.createdAt = create.at;\n for (const c of list) {\n const why = this.fold(c, create);\n if (why) this.refused.push({ id: c.id, reason: why });\n }\n }\n\n private fold(c: Change, create: Change): string | undefined {\n const t = Date.parse(c.at);\n const by = this.members.get(c.author);\n const isAdmin = by && !by.removed_at && by.role === \"admin\";\n const b = c.body;\n switch (c.kind) {\n case \"create\": {\n if (c !== create) return \"a graph is created once\";\n const name = cleanName(b.creator_name) ?? \"creator\";\n this.put({ key: c.author, name, role: \"admin\", joined_at: c.at, added_by: c.author, creator: true, named_at: c.at });\n this.span(c.author, t, \"admin\");\n const d = cleanDescription(b.description);\n if (d) {\n this.description = d;\n this.descriptionSetBy = c.author;\n }\n return;\n }\n case \"add_member\": {\n if (!isAdmin) return \"only an admin can add someone\";\n const key = typeof b.key === \"string\" && b.key.length === 43 ? b.key : undefined;\n const name = cleanName(b.name);\n const role = ROLES.includes(b.role) ? (b.role as Role) : undefined;\n if (!key || !name || !role) return \"bad add_member\";\n const existing = this.members.get(key);\n if (existing && !existing.removed_at) return \"already a member\";\n this.put({\n key,\n name,\n role,\n joined_at: c.at,\n added_by: c.author,\n invite: b.invite && typeof b.invite.id === \"string\" ? { id: b.invite.id, label: typeof b.invite.label === \"string\" ? b.invite.label : null } : undefined,\n about: cleanAbout(b.about),\n creator: false,\n named_at: c.at,\n });\n this.span(key, t, role);\n return;\n }\n case \"set_role\": {\n if (!isAdmin) return \"only an admin can change roles\";\n const m = typeof b.key === \"string\" ? this.members.get(b.key) : undefined;\n if (!m || m.removed_at) return \"not a member\";\n if (!ROLES.includes(b.role)) return \"bad role\";\n if (m.creator && b.role !== \"admin\") return \"the graph's creator stays an admin\";\n m.role = b.role;\n this.span(m.key, t, b.role);\n return;\n }\n case \"remove_member\": {\n if (!isAdmin) return \"only an admin can remove someone\";\n const m = typeof b.key === \"string\" ? this.members.get(b.key) : undefined;\n if (!m || m.removed_at) return \"not a member\";\n if (m.creator) return \"the graph's creator can't be removed\";\n m.removed_at = c.at;\n this.span(m.key, t, null);\n return;\n }\n case \"describe\": {\n if (!isAdmin) return \"only an admin can describe the context\";\n this.description = cleanDescription(b.description);\n this.descriptionSetBy = c.author;\n return;\n }\n case \"rename\": {\n if (!by || by.removed_at) return \"not a member\";\n const name = cleanName(b.name);\n if (!name) return \"bad name\";\n by.name = name;\n by.named_at = c.at;\n return;\n }\n }\n return \"not a membership change\";\n }\n\n private put(m: Member) {\n this.members.set(m.key, m);\n }\n\n private span(key: string, from: number, role: Role | null) {\n const s = this.spans.get(key) ?? [];\n s.push({ from, role });\n this.spans.set(key, s);\n }\n\n /** The key's role at a moment, or null if it wasn't a member then. */\n roleAt(key: string, at: string): Role | null {\n const t = Date.parse(at);\n let role: Role | null = null;\n for (const s of this.spans.get(key) ?? []) if (s.from <= t) role = s.role;\n return role;\n }\n\n /** May this key make a change needing `needs` at that moment? */\n allows(key: string, at: string, needs: Role): boolean {\n const r = this.roleAt(key, at);\n return r !== null && RANK[r] >= RANK[needs];\n }\n\n get(key: string): Member | undefined {\n return this.members.get(key);\n }\n\n /** Current members (not removed). */\n current(): Member[] {\n return [...this.members.values()].filter((m) => !m.removed_at);\n }\n\n all(): Member[] {\n return [...this.members.values()];\n }\n\n isMember(key: string): boolean {\n const m = this.members.get(key);\n return Boolean(m && !m.removed_at);\n }\n\n byName(name: string): Member | undefined {\n return this.current().find((m) => m.name === name || this.displayName(m.key) === name);\n }\n\n /**\n * The name to show for a key. If two current members have the same name,\n * the one who took it first keeps it; the other is shown with their key\n * fingerprint after it until they rename.\n */\n displayName(key: string): string {\n const m = this.members.get(key);\n if (!m) return fingerprint(key);\n const clash = this.current().some((o) => o.key !== key && o.name === m.name && (o.named_at < m.named_at || (o.named_at === m.named_at && o.key < key)));\n return clash ? `${m.name} (${fingerprint(key)})` : m.name;\n }\n\n creator(): Member | undefined {\n return this.all().find((m) => m.creator);\n }\n}\n\n/** A context's description: one line or a short paragraph, up to 500 characters. */\nexport function cleanDescription(v: unknown): string | null {\n if (typeof v !== \"string\") return null;\n const d = v.replace(/\\s+/g, \" \").trim().slice(0, 500);\n return d || null;\n}\n\nfunction cleanName(v: unknown): string | undefined {\n return typeof v === \"string\" && NAME_RE.test(v.trim()) ? v.trim() : undefined;\n}\n\n/** Keeps only short, printable strings from what a member said about their install. */\nexport function cleanAbout(a: unknown): Record<string, string> | undefined {\n if (!a || typeof a !== \"object\") return undefined;\n const out: Record<string, string> = {};\n for (const k of [\"agent\", \"agent_version\", \"vine\", \"platform\"]) {\n const v = (a as Record<string, unknown>)[k];\n if (typeof v === \"string\" && v.trim()) out[k] = v.replace(/[^\\x20-\\x7e]/g, \"\").trim().slice(0, 60);\n }\n return Object.keys(out).length ? out : undefined;\n}\n","// Sends protocol messages over a WebRTC data channel. Large messages (a long\n// tool result) are split into chunks, because SCTP message size limits vary\n// between WebRTC stacks.\n\nimport type { DataChannel } from \"node-datachannel\";\nimport type { Message } from \"./protocol.js\";\n\nconst CHUNK = 16_000;\nconst MAX_MESSAGE = 8 * 1024 * 1024;\n\ntype Chunk = { t: \"chunk\"; id: number; i: number; n: number; d: string };\n\nexport class FramedChannel {\n private nextChunkId = 1;\n private partial = new Map<number, { parts: string[]; got: number; size: number }>();\n private handlers: ((m: Message) => void)[] = [];\n private closeHandlers: (() => void)[] = [];\n closed = false;\n\n constructor(readonly dc: DataChannel) {\n dc.onMessage((raw) => this.receive(String(raw)));\n dc.onClosed(() => this.markClosed());\n dc.onError(() => this.markClosed());\n }\n\n onMessage(fn: (m: Message | any) => void): void {\n this.handlers.push(fn);\n }\n\n onClose(fn: () => void): void {\n if (this.closed) fn();\n else this.closeHandlers.push(fn);\n }\n\n send(m: Message | Record<string, unknown>): void {\n if (this.closed || !this.dc.isOpen()) throw new Error(\"The connection is closed.\");\n const text = JSON.stringify(m);\n if (text.length <= CHUNK) {\n this.dc.sendMessage(text);\n return;\n }\n if (text.length > MAX_MESSAGE) throw new Error(\"Message too large to send.\");\n const id = this.nextChunkId++;\n const n = Math.ceil(text.length / CHUNK);\n for (let i = 0; i < n; i++) {\n const c: Chunk = { t: \"chunk\", id, i, n, d: text.slice(i * CHUNK, (i + 1) * CHUNK) };\n this.dc.sendMessage(JSON.stringify(c));\n }\n }\n\n close(): void {\n try {\n this.dc.close();\n } catch {\n // already closed\n }\n this.markClosed();\n }\n\n private receive(text: string): void {\n let m: any;\n try {\n m = JSON.parse(text);\n } catch {\n return;\n }\n if (m?.t === \"chunk\") {\n const c = m as Chunk;\n if (!Number.isInteger(c.n) || c.n < 1 || c.n > MAX_MESSAGE / CHUNK + 1) return;\n let p = this.partial.get(c.id);\n if (!p) this.partial.set(c.id, (p = { parts: new Array(c.n), got: 0, size: 0 }));\n if (p.parts[c.i] === undefined && typeof c.d === \"string\") {\n p.parts[c.i] = c.d;\n p.got++;\n p.size += c.d.length;\n if (p.size > MAX_MESSAGE) return void this.partial.delete(c.id);\n }\n if (p.got < c.n) return;\n this.partial.delete(c.id);\n try {\n m = JSON.parse(p.parts.join(\"\"));\n } catch {\n return;\n }\n }\n for (const h of this.handlers) h(m);\n }\n\n private markClosed(): void {\n if (this.closed) return;\n this.closed = true;\n for (const h of this.closeHandlers.splice(0)) h();\n }\n}\n","// Where a password this machine needs (today: the TURN server's) is kept.\n//\n// file beside the setting that uses it, in a file only the owner can read\n// keychain the OS keychain: macOS Keychain (`security`), or the Linux secret\n// service (`secret-tool`)\n// env nowhere: read from an environment variable when it's needed\n//\n// The keychain is reached through the OS's own command-line tools, and the\n// password goes to them on stdin, never as a command argument (which other\n// users of the machine could see in the process list).\n\nimport { spawnSync } from \"node:child_process\";\n\nexport type SecretStore = \"file\" | \"keychain\" | \"env\";\nexport const SECRET_STORES: SecretStore[] = [\"file\", \"keychain\", \"env\"];\n\nconst run = (cmd: string, args: string[], input?: string) =>\n spawnSync(cmd, args, { input, encoding: \"utf8\", timeout: 10_000, stdio: [\"pipe\", \"pipe\", \"pipe\"] });\n\nconst has = (cmd: string) => run(cmd, cmd === \"security\" ? [\"help\"] : [\"--help\"]).error === undefined;\n\ntype Tool = \"security\" | \"secret-tool\";\n\n/** The OS keychain tool on this machine, if there is one. */\nexport function keychainTool(platform = process.platform): Tool | undefined {\n if (platform === \"darwin\") return has(\"security\") ? \"security\" : undefined;\n if (platform === \"linux\") return has(\"secret-tool\") ? \"secret-tool\" : undefined;\n return undefined;\n}\n\nconst NO_KEYCHAIN = \"This machine has no keychain Vine can use (macOS Keychain, or secret-tool on Linux). Choose the file or env store instead.\";\n\n/** `security -i` reads one command per line: quote the value, and escape what the quoting uses. */\nconst quoted = (s: string) => `\"${s.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"')}\"`;\n\nexport function keychainSet(service: string, account: string, password: string): void {\n if (/[\\r\\n]/.test(password)) throw new Error(\"A password can't contain a line break.\");\n const tool = keychainTool();\n if (!tool) throw new Error(NO_KEYCHAIN);\n const r =\n tool === \"security\"\n ? run(\"security\", [\"-i\"], `add-generic-password -U -s ${quoted(service)} -a ${quoted(account)} -w ${quoted(password)}\\n`)\n : run(\"secret-tool\", [\"store\", `--label=${service}`, \"service\", service, \"account\", account], password);\n if (r.status !== 0 || r.error) throw new Error(`The keychain refused the password (${tool} exited ${r.status ?? \"early\"}).`);\n}\n\nexport function keychainGet(service: string, account: string): string | undefined {\n const tool = keychainTool();\n if (!tool) return undefined;\n const r =\n tool === \"security\"\n ? run(\"security\", [\"find-generic-password\", \"-s\", service, \"-a\", account, \"-w\"])\n : run(\"secret-tool\", [\"lookup\", \"service\", service, \"account\", account]);\n if (r.status !== 0 || r.error) return undefined;\n const out = r.stdout.replace(/\\r?\\n$/, \"\");\n return out === \"\" ? undefined : out;\n}\n\nexport function keychainDelete(service: string, account: string): void {\n const tool = keychainTool();\n if (!tool) return;\n if (tool === \"security\") run(\"security\", [\"delete-generic-password\", \"-s\", service, \"-a\", account]);\n else run(\"secret-tool\", [\"clear\", \"service\", service, \"account\", account]);\n}\n","// Cloudflare Realtime TURN: the TURN server most people can set up in a few\n// minutes, on their own Cloudflare account.\n//\n// A TURN key (an id and a secret) lives on this machine, in the OS keychain.\n// It never goes to a member or into a link: at connect time the host asks\n// Cloudflare for short-lived credentials with it, and gives those to WebRTC.\n// The credentials are kept in memory only, until near expiry.\n//\n// Docs: https://developers.cloudflare.com/realtime/turn/generate-credentials/\n\nimport type { IceServer } from \"node-datachannel\";\n\nexport const CLOUDFLARE_RTC = \"https://rtc.live.cloudflare.com/v1\";\nexport const CLOUDFLARE_API = \"https://api.cloudflare.com/client/v4\";\n/** Where a person creates a TURN key by hand. */\nexport const CLOUDFLARE_TURN_KEYS_PAGE = \"https://dash.cloudflare.com/?to=/:account/calls\";\n/** Where a person makes an API token that may create TURN keys. */\nexport const CLOUDFLARE_TOKENS_PAGE = \"https://dash.cloudflare.com/profile/api-tokens\";\n/** How long minted credentials last (seconds). */\nexport const CREDENTIAL_TTL = 12 * 3600;\n\nexport type Fetch = typeof fetch;\n\nexport interface MintedTurn {\n servers: IceServer[];\n username: string;\n /** Epoch ms. */\n expiresAt: number;\n /** The URLs Cloudflare offered, for show. */\n urls: string[];\n}\n\n/** One of Cloudflare's TURN URLs, as node-datachannel takes it. Port 53 and plain STUN are left out. */\nexport function toIceServer(url: string, username: string, credential: string): IceServer | undefined {\n const m = /^(turns?):([^:?]+):(\\d+)(?:\\?transport=(udp|tcp))?$/i.exec(url.trim());\n if (!m) return undefined;\n const [, scheme, hostname, portS, transport] = m;\n const port = Number(portS);\n if (port === 53) return undefined; // often blocked, and slow to time out\n const tls = scheme!.toLowerCase() === \"turns\";\n const relayType = tls ? \"TurnTls\" : (transport ?? \"udp\").toLowerCase() === \"tcp\" ? \"TurnTcp\" : \"TurnUdp\";\n return { hostname: hostname!, port, username, password: credential, relayType };\n}\n\n/**\n * The servers to give WebRTC: UDP first (fastest), then TLS on 443 (gets\n * through most firewalls), then the rest. A few are enough: each one is tried.\n */\nexport function pickServers(urls: string[], username: string, credential: string): IceServer[] {\n const all = urls.map((u) => toIceServer(u, username, credential)).filter((s): s is IceServer => Boolean(s));\n const rank = (s: IceServer) => (s.relayType === \"TurnUdp\" && s.port === 3478 ? 0 : s.relayType === \"TurnTls\" && s.port === 443 ? 1 : s.relayType === \"TurnUdp\" ? 2 : s.relayType === \"TurnTcp\" ? 3 : 4);\n return all.sort((a, b) => rank(a) - rank(b)).slice(0, 3);\n}\n\nasync function failure(r: Response, what: string): Promise<Error> {\n let detail = \"\";\n try {\n const body = (await r.json()) as any;\n const msgs = (body?.errors ?? []).map((e: any) => e?.message).filter(Boolean);\n detail = msgs.length ? `: ${msgs.join(\"; \")}` : \"\";\n } catch {\n // not JSON\n }\n const hint =\n r.status === 401 || r.status === 403\n ? \" Cloudflare refused the key or token: check it was copied whole, and (for a token) that it has the Realtime or Calls Write permission.\"\n : r.status === 404\n ? \" Cloudflare doesn't know that key id or account id.\"\n : \"\";\n return new Error(`${what} failed (HTTP ${r.status})${detail}.${hint}`);\n}\n\n/** Short-lived TURN credentials from a TURN key. The secret goes only in the Authorization header. */\nexport async function mintCredentials(keyId: string, secret: string, opts: { ttl?: number; fetch?: Fetch; now?: () => number } = {}): Promise<MintedTurn> {\n const f = opts.fetch ?? fetch;\n const ttl = opts.ttl ?? CREDENTIAL_TTL;\n const now = opts.now ?? Date.now;\n const r = await f(`${CLOUDFLARE_RTC}/turn/keys/${encodeURIComponent(keyId)}/credentials/generate-ice-servers`, {\n method: \"POST\",\n headers: { Authorization: `Bearer ${secret}`, \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ ttl }),\n signal: AbortSignal.timeout(10_000),\n });\n if (!r.ok) throw await failure(r, \"Asking Cloudflare for TURN credentials\");\n const body = (await r.json()) as any;\n const list: any[] = Array.isArray(body?.iceServers) ? body.iceServers : body?.iceServers ? [body.iceServers] : [];\n const turn = list.find((s) => typeof s?.username === \"string\" && typeof s?.credential === \"string\");\n if (!turn) throw new Error(\"Cloudflare's answer had no TURN credentials in it.\");\n const urls: string[] = (Array.isArray(turn.urls) ? turn.urls : [turn.urls]).filter((u: unknown): u is string => typeof u === \"string\");\n const servers = pickServers(urls, turn.username, turn.credential);\n if (!servers.length) throw new Error(\"Cloudflare's answer had no TURN server Vine can use.\");\n return { servers, username: turn.username, expiresAt: now() + ttl * 1000, urls };\n}\n\n/** Revokes one minted credential (best effort; they expire anyway). */\nexport async function revokeCredentials(keyId: string, secret: string, username: string, f: Fetch = fetch): Promise<boolean> {\n try {\n const r = await f(`${CLOUDFLARE_RTC}/turn/keys/${encodeURIComponent(keyId)}/credentials/${encodeURIComponent(username)}/revoke`, {\n method: \"POST\",\n headers: { Authorization: `Bearer ${secret}` },\n signal: AbortSignal.timeout(10_000),\n });\n return r.ok;\n } catch {\n return false;\n }\n}\n\n/** Creates a TURN key on the person's account with an API token. The token is used once and not kept. */\nexport async function createTurnKey(accountId: string, apiToken: string, name: string, f: Fetch = fetch): Promise<{ keyId: string; secret: string; name: string }> {\n const r = await f(`${CLOUDFLARE_API}/accounts/${encodeURIComponent(accountId)}/calls/turn_keys`, {\n method: \"POST\",\n headers: { Authorization: `Bearer ${apiToken}`, \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ name }),\n signal: AbortSignal.timeout(15_000),\n });\n if (!r.ok) throw await failure(r, \"Creating a TURN key\");\n const body = (await r.json()) as any;\n const res = body?.result ?? body;\n if (typeof res?.uid !== \"string\" || typeof res?.secret !== \"string\") throw new Error(\"Cloudflare created no TURN key (its answer had no key id or secret).\");\n return { keyId: res.uid, secret: res.secret, name: typeof res.name === \"string\" ? res.name : name };\n}\n\n/** A key id looks like 32 hex characters; a secret like 64. Loose checks, to catch a paste of the wrong thing. */\nexport const looksLikeKeyId = (s: string) => /^[A-Za-z0-9_-]{16,128}$/.test(s);\nexport const looksLikeSecret = (s: string) => /^[A-Za-z0-9_\\-.=+/]{20,512}$/.test(s);\n","// The STUN and TURN servers WebRTC links use.\n//\n// STUN servers only tell a machine its public address; two public ones are the\n// default. A TURN server carries the data between two machines that can't\n// reach each other directly (strict NAT). There is none by default: a person\n// who needs one sets it with `vine turn set` (or the turn_server tool),\n// and it is kept in <data dir>/network.json for every Vine process on the\n// machine. Each new link reads it, so a running host picks up a change.\n//\n// Or the TURN server is Cloudflare's (`vine turn set --provider cloudflare`):\n// then this machine keeps a TURN key in its keychain, and mints short-lived\n// credentials from it at connect time (see cloudflare.ts). They're held in\n// memory until near expiry, and minted again on the next connection after.\n//\n// VINE_ICE, when set, replaces all of this with its own list.\n\nimport { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport nodeDataChannel, { type IceServer } from \"node-datachannel\";\nimport { keychainDelete, keychainGet, keychainSet, type SecretStore } from \"../core/secret.js\";\nimport { mintCredentials, type MintedTurn } from \"./cloudflare.js\";\n\nexport const DEFAULT_STUN = [\"stun:stun.l.google.com:19302\", \"stun:stun.cloudflare.com:3478\"];\nexport const TURN_PASSWORD_ENV = \"VINE_TURN_PASSWORD\";\n/** Where a Cloudflare TURN key's secret is read from, when it was set with --store env. */\nexport const CLOUDFLARE_SECRET_ENV = \"VINE_CLOUDFLARE_TURN_SECRET\";\n/** Mint again when credentials have less than this left. */\nconst REFRESH_BEFORE_MS = 3600_000;\n/** After a failed mint, wait this long before trying again. */\nconst RETRY_AFTER_MS = 30_000;\nconst KEYCHAIN_SERVICE = \"vine-context-turn\";\n\nexport type TurnTransport = \"udp\" | \"tcp\" | \"tls\";\nexport const TURN_TRANSPORTS: TurnTransport[] = [\"udp\", \"tcp\", \"tls\"];\n\nexport interface TurnSetting {\n host: string;\n port: number;\n username: string;\n transport: TurnTransport;\n store: SecretStore;\n /** Only with store \"file\". */\n password?: string;\n}\n\n/** Cloudflare Realtime TURN: a key whose secret is in the keychain (or an env var), never in network.json. */\nexport interface CloudflareTurnSetting {\n provider: \"cloudflare\";\n keyId: string;\n store: \"keychain\" | \"env\";\n /** The key's name on the account, for show. */\n name?: string;\n}\n\nexport type AnyTurnSetting = TurnSetting | CloudflareTurnSetting;\n\n/** What a PeerConnection is given. */\nexport interface IceConfig {\n servers: (string | IceServer)[];\n /** \"relay\": use only a TURN server's addresses (tests, and `vine turn test`). */\n policy?: \"all\" | \"relay\";\n}\n\n/**\n * Read for each new link, so a changed setting is picked up. A plain list is\n * fixed. A function may carry `prepare`, awaited before a link is made (to\n * fetch credentials that are minted, not stored).\n */\nexport type IceSource = (string | IceServer)[] | ((() => IceConfig) & { prepare?: () => Promise<void> });\n\n/** Gets the source ready for a new link. Never throws: a link without TURN is still worth trying. */\nexport async function prepareIce(ice: IceSource): Promise<void> {\n if (typeof ice !== \"function\" || !ice.prepare) return;\n try {\n await ice.prepare();\n } catch {\n // resolveIce reports the problem\n }\n}\n\n/** What status shows. It never holds a password. */\nexport interface IceSummary {\n stun: string[];\n /** \"host:port (udp)\", or null when there's none. */\n turn: string | null;\n /** Where the list came from: the defaults, `vine turn set`, or VINE_ICE. */\n source: \"default\" | \"setting\" | \"env\";\n /** Whose TURN server, when one is set: Cloudflare's (minted credentials) or one of your own. */\n provider?: \"cloudflare\" | \"custom\";\n /** When the minted credentials run out (Cloudflare), ISO. */\n expires?: string;\n /** Why a TURN server that is set can't be used, if so. */\n problem?: string;\n}\n\nexport function rtcConfig(ice: IceSource): { iceServers: (string | IceServer)[]; iceTransportPolicy?: \"all\" | \"relay\" } {\n const c = typeof ice === \"function\" ? ice() : { servers: ice };\n return { iceServers: c.servers, ...(c.policy ? { iceTransportPolicy: c.policy } : {}) };\n}\n\nconst networkFile = (dataDir: string) => join(dataDir, \"network.json\");\nconst account = (t: Pick<TurnSetting, \"host\" | \"port\" | \"username\">) => `${t.username}@${t.host}:${t.port}`;\nconst label = (t: Pick<TurnSetting, \"host\" | \"port\" | \"transport\">) => `${t.host}:${t.port} (${t.transport})`;\n\nfunction validCloudflare(t: any): t is CloudflareTurnSetting {\n return Boolean(t) && t.provider === \"cloudflare\" && typeof t.keyId === \"string\" && t.keyId !== \"\" && [\"keychain\", \"env\"].includes(t.store);\n}\n\nfunction valid(t: any): t is TurnSetting {\n return (\n t &&\n t.provider === undefined &&\n typeof t.host === \"string\" &&\n t.host !== \"\" &&\n Number.isInteger(t.port) &&\n t.port > 0 &&\n t.port < 65536 &&\n typeof t.username === \"string\" &&\n TURN_TRANSPORTS.includes(t.transport) &&\n [\"file\", \"keychain\", \"env\"].includes(t.store)\n );\n}\n\n/** The stored TURN setting of either kind, without looking up any secret. */\nexport function readTurnSetting(dataDir: string): AnyTurnSetting | undefined {\n try {\n const t = JSON.parse(readFileSync(networkFile(dataDir), \"utf8\")).turn;\n return valid(t) || validCloudflare(t) ? t : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** The stored TURN server of your own (not Cloudflare's), without looking up its password. */\nexport function readTurn(dataDir: string): TurnSetting | undefined {\n const t = readTurnSetting(dataDir);\n return t && !isCloudflare(t) ? t : undefined;\n}\n\nexport const isCloudflare = (t: AnyTurnSetting | undefined): t is CloudflareTurnSetting => (t as CloudflareTurnSetting | undefined)?.provider === \"cloudflare\";\n\n/** The stored Cloudflare TURN key, if that's the setting. */\nexport function readCloudflare(dataDir: string): CloudflareTurnSetting | undefined {\n const t = readTurnSetting(dataDir);\n return isCloudflare(t) ? t : undefined;\n}\n\nconst cfAccount = (t: Pick<CloudflareTurnSetting, \"keyId\">) => `cloudflare:${t.keyId}`;\nconst keychainAccount = (t: AnyTurnSetting) => (isCloudflare(t) ? cfAccount(t) : account(t));\n\n/** Removes the keychain entry of the setting that was there before, unless the new one uses the same entry. */\nfunction dropOldSecret(before: AnyTurnSetting | undefined, now: AnyTurnSetting) {\n if (before?.store !== \"keychain\") return;\n if (now.store === \"keychain\" && keychainAccount(before) === keychainAccount(now)) return;\n keychainDelete(KEYCHAIN_SERVICE, keychainAccount(before));\n}\n\nexport interface TurnInput {\n host: string;\n port?: number;\n username: string;\n transport?: TurnTransport;\n store?: SecretStore;\n /** Required for the file and keychain stores; refused for env. */\n password?: string;\n}\n\n/** \"turn.example.org\" or \"turn.example.org:3478\" (or \"[::1]:3478\"). */\nexport function parseHostPort(s: string): { host: string; port?: number } {\n const m = /^\\[([^\\]]+)\\](?::(\\d+))?$/.exec(s) ?? /^([^:\\s]+)(?::(\\d+))?$/.exec(s);\n if (!m) throw new Error(`\"${s}\" isn't a server address. Give a host name, or host:port.`);\n return { host: m[1]!, ...(m[2] ? { port: Number(m[2]) } : {}) };\n}\n\n/** Saves the TURN server for this machine, replacing any other. */\nexport function saveTurn(dataDir: string, input: TurnInput): TurnSetting {\n const transport = input.transport ?? \"udp\";\n const store = input.store ?? \"file\";\n const t: TurnSetting = {\n host: input.host.trim(),\n port: input.port ?? (transport === \"tls\" ? 5349 : 3478),\n username: input.username,\n transport,\n store,\n };\n if (!valid(t)) throw new Error(\"A TURN server needs a host, a port from 1 to 65535, and a username.\");\n if (store === \"env\") {\n if (input.password !== undefined) throw new Error(`With the env store the password isn't saved: set ${TURN_PASSWORD_ENV} where Vine runs, and give no password here.`);\n } else if (!input.password) throw new Error(\"A password is needed.\");\n\n const before = readTurnSetting(dataDir);\n if (store === \"keychain\") keychainSet(KEYCHAIN_SERVICE, account(t), input.password!);\n if (store === \"file\") t.password = input.password;\n dropOldSecret(before, t);\n write(dataDir, { turn: t });\n minted.delete(dataDir);\n return t;\n}\n\nexport interface CloudflareInput {\n keyId: string;\n /** The key's secret. Required for the keychain store; refused for env. */\n secret?: string;\n store?: \"keychain\" | \"env\";\n name?: string;\n}\n\n/**\n * Saves a Cloudflare TURN key as this machine's TURN server, replacing any\n * other. The secret goes to the OS keychain (or nowhere, with env); never\n * into network.json.\n */\nexport function saveCloudflareTurn(dataDir: string, input: CloudflareInput): CloudflareTurnSetting {\n const store = input.store ?? \"keychain\";\n const t: CloudflareTurnSetting = { provider: \"cloudflare\", keyId: input.keyId.trim(), store, ...(input.name ? { name: input.name } : {}) };\n if (!validCloudflare(t)) throw new Error(\"A Cloudflare TURN key needs its key id, and the keychain or env store.\");\n if (store === \"env\") {\n if (input.secret !== undefined) throw new Error(`With the env store the secret isn't saved: set ${CLOUDFLARE_SECRET_ENV} where Vine runs, and give no secret here.`);\n } else if (!input.secret) throw new Error(\"The TURN key's secret is needed.\");\n const before = readTurnSetting(dataDir);\n if (store === \"keychain\") keychainSet(KEYCHAIN_SERVICE, cfAccount(t), input.secret!);\n dropOldSecret(before, t);\n write(dataDir, { turn: t });\n minted.delete(dataDir);\n return t;\n}\n\n/** Forgets the TURN server (and its password, wherever it was kept). True if there was one. */\nexport function clearTurn(dataDir: string): boolean {\n const before = readTurnSetting(dataDir);\n if (before?.store === \"keychain\") keychainDelete(KEYCHAIN_SERVICE, keychainAccount(before));\n minted.delete(dataDir);\n try {\n rmSync(networkFile(dataDir));\n } catch {\n // none\n }\n return before !== undefined;\n}\n\nfunction write(dataDir: string, value: unknown) {\n mkdirSync(dataDir, { recursive: true, mode: 0o700 });\n const file = networkFile(dataDir);\n const tmp = `${file}.${process.pid}.tmp`;\n writeFileSync(tmp, JSON.stringify(value, null, 1) + \"\\n\", { mode: 0o600 });\n chmodSync(tmp, 0o600);\n renameSync(tmp, file);\n}\n\n/** VINE_ICE entries with any \"user:pass@\" taken out, for status. */\nconst redact = (s: string) => s.replace(/^(turns?:)[^@]*@/i, \"$1\");\n\ninterface Resolved {\n config: IceConfig;\n summary: IceSummary;\n}\n\n// The keychain is a subprocess call: look the password up once per saved setting, not once per link.\nconst keychainCache = new Map<string, { stamp: string; password: string | undefined }>();\n\nfunction fromKeychain(dataDir: string, acct: string): string | undefined {\n let stamp = \"\";\n try {\n const s = statSync(networkFile(dataDir));\n stamp = `${s.mtimeMs}:${s.size}:${acct}`;\n } catch {\n // just read\n }\n let hit = keychainCache.get(dataDir);\n if (!hit || hit.stamp !== stamp || hit.password === undefined) {\n hit = { stamp, password: keychainGet(KEYCHAIN_SERVICE, acct) };\n keychainCache.set(dataDir, hit);\n }\n return hit.password;\n}\n\nfunction turnPassword(dataDir: string, t: TurnSetting): { password?: string; problem?: string } {\n if (t.store === \"file\") return t.password ? { password: t.password } : { problem: \"its password is missing from network.json\" };\n if (t.store === \"env\") {\n const p = process.env[TURN_PASSWORD_ENV];\n return p ? { password: p } : { problem: `${TURN_PASSWORD_ENV} isn't set where this is running` };\n }\n const password = fromKeychain(dataDir, account(t));\n return password ? { password } : { problem: \"its password wasn't found in the keychain\" };\n}\n\nfunction cloudflareSecret(dataDir: string, t: CloudflareTurnSetting): { secret?: string; problem?: string } {\n if (t.store === \"env\") {\n const s = process.env[CLOUDFLARE_SECRET_ENV];\n return s ? { secret: s } : { problem: `${CLOUDFLARE_SECRET_ENV} isn't set where this is running` };\n }\n const secret = fromKeychain(dataDir, cfAccount(t));\n return secret ? { secret } : { problem: \"the TURN key's secret wasn't found in the keychain (run `vine setup` or `vine turn set --provider cloudflare` again)\" };\n}\n\n// ---- Minted credentials (Cloudflare) ------------------------------------\n\ninterface MintState {\n /** Which key these are for: a changed setting starts over. */\n key: string;\n creds?: MintedTurn;\n inflight?: Promise<void>;\n failedAt?: number;\n error?: string;\n}\n\n/** Per data folder, in memory only. */\nconst minted = new Map<string, MintState>();\n\nconst usable = (m: MintState | undefined, now = Date.now()) => (m?.creds && m.creds.expiresAt - now > 60_000 ? m.creds : undefined);\nconst fresh = (m: MintState | undefined, now = Date.now()) => Boolean(m?.creds && m.creds.expiresAt - now > REFRESH_BEFORE_MS);\n\n/**\n * Mints Cloudflare credentials when there are none, or they're near expiry.\n * One request at a time per data folder; a failure waits a little before the\n * next try (unless forced). Does nothing for other settings.\n */\nexport async function refreshIce(dataDir: string, opts: { force?: boolean } = {}): Promise<void> {\n if (process.env.VINE_ICE !== undefined) return;\n const t = readCloudflare(dataDir);\n if (!t) return;\n const key = `${t.keyId}:${t.store}`;\n let m = minted.get(dataDir);\n if (!m || m.key !== key) {\n m = { key };\n minted.set(dataDir, m);\n }\n const state = m;\n if (state.inflight) return state.inflight;\n const now = Date.now();\n if (!opts.force && fresh(state, now)) return;\n if (!opts.force && state.failedAt && now - state.failedAt < RETRY_AFTER_MS) return;\n const { secret, problem } = cloudflareSecret(dataDir, t);\n if (!secret) {\n state.failedAt = now;\n state.error = problem;\n return;\n }\n state.inflight = mintCredentials(t.keyId, secret)\n .then((creds) => {\n state.creds = creds;\n state.failedAt = undefined;\n state.error = undefined;\n })\n .catch((e: Error) => {\n state.failedAt = Date.now();\n state.error = e.message;\n })\n .finally(() => {\n state.inflight = undefined;\n });\n return state.inflight;\n}\n\n/** Forgets minted credentials (tests, and a changed setting). */\nexport function forgetMinted(dataDir?: string): void {\n if (dataDir === undefined) minted.clear();\n else minted.delete(dataDir);\n}\n\nconst relayType = { udp: \"TurnUdp\", tcp: \"TurnTcp\", tls: \"TurnTls\" } as const;\n\nexport function turnServer(t: TurnSetting, password: string): IceServer {\n return { hostname: t.host, port: t.port, username: t.username, password, relayType: relayType[t.transport] };\n}\n\n/** The servers to use now, and what to show about them. */\nexport function resolveIce(dataDir: string): Resolved {\n const env = process.env.VINE_ICE;\n if (env !== undefined) {\n const list = env\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n const turn = list.filter((s) => /^turns?:/i.test(s)).map(redact);\n return {\n config: { servers: list },\n summary: { stun: list.filter((s) => !/^turns?:/i.test(s)), turn: turn.length ? turn.join(\", \") : null, source: \"env\" },\n };\n }\n const any = readTurnSetting(dataDir);\n if (!any) return { config: { servers: DEFAULT_STUN }, summary: { stun: DEFAULT_STUN, turn: null, source: \"default\" } };\n if (isCloudflare(any)) {\n const m = minted.get(dataDir);\n const creds = m?.key === `${any.keyId}:${any.store}` ? usable(m) : undefined;\n // Stale or missing: start minting for the next link (prepare waits for it; this doesn't).\n if (!fresh(m)) void refreshIce(dataDir);\n const problem = creds ? undefined : (m?.error ?? cloudflareSecret(dataDir, any).problem ?? \"no credentials fetched yet\");\n return {\n config: { servers: creds ? [...DEFAULT_STUN, ...creds.servers] : DEFAULT_STUN },\n summary: {\n stun: DEFAULT_STUN,\n turn: CLOUDFLARE_LABEL,\n source: \"setting\",\n provider: \"cloudflare\",\n ...(creds ? { expires: new Date(creds.expiresAt).toISOString() } : {}),\n ...(problem ? { problem } : {}),\n },\n };\n }\n const { password, problem } = turnPassword(dataDir, any);\n return {\n config: { servers: password ? [...DEFAULT_STUN, turnServer(any, password)] : DEFAULT_STUN },\n summary: { stun: DEFAULT_STUN, turn: label(any), source: \"setting\", provider: \"custom\", ...(problem ? { problem } : {}) },\n };\n}\n\nexport const CLOUDFLARE_LABEL = \"Cloudflare Realtime TURN (turn.cloudflare.com)\";\n\n/** The setting as a live source: each new link reads it, after minting credentials if they're due. */\nexport const storedIce = (dataDir: string): IceSource => Object.assign(() => resolveIce(dataDir).config, { prepare: () => refreshIce(dataDir) });\n\nexport interface TurnCheck {\n ok: boolean;\n /** The address the server lent, when ok. */\n relay?: string;\n error?: string;\n}\n\n/**\n * Asks the TURN server for a relay address, using nothing else. Getting one\n * proves the host, port, username and password. It doesn't prove the server\n * will carry data to a particular member.\n */\nexport function checkTurn(server: IceServer, timeoutMs = 10_000): Promise<TurnCheck> {\n return new Promise((resolve) => {\n let done = false;\n const pc = new nodeDataChannel.PeerConnection(\"vine-turn-check\", { iceServers: [server], iceTransportPolicy: \"relay\" });\n const finish = (r: TurnCheck) => {\n if (done) return;\n done = true;\n clearTimeout(timer);\n try {\n pc.close();\n } catch {\n // already closed\n }\n resolve(r);\n };\n const none = \"The server gave no relay address. Check the host, port, username and password, and that the server is reachable.\";\n const timer = setTimeout(() => finish({ ok: false, error: none }), timeoutMs);\n pc.onLocalCandidate((candidate) => {\n const m = /^(?:a=)?candidate:\\S+ \\d+ \\S+ \\d+ (\\S+) (\\d+) typ relay/.exec(candidate);\n if (m) finish({ ok: true, relay: `${m[1]}:${m[2]}` });\n });\n pc.onGatheringStateChange((s) => {\n // Candidates are reported before \"complete\": give the last one a moment.\n if (s === \"complete\") setTimeout(() => finish({ ok: false, error: none }), 50);\n });\n try {\n pc.createDataChannel(\"probe\");\n } catch (e) {\n finish({ ok: false, error: (e as Error).message });\n }\n });\n}\n\n/** Checks the stored TURN server. For Cloudflare, mints fresh credentials and tries each server it gave. */\nexport async function checkStoredTurn(dataDir: string, timeoutMs?: number, check: typeof checkTurn = checkTurn): Promise<TurnCheck & { turn: string | null }> {\n const any = readTurnSetting(dataDir);\n if (!any) return { ok: false, turn: null, error: \"No TURN server is set.\" };\n if (isCloudflare(any)) {\n await refreshIce(dataDir, { force: true });\n const m = minted.get(dataDir);\n const creds = usable(m);\n if (!creds) return { ok: false, turn: CLOUDFLARE_LABEL, error: `Couldn't get TURN credentials from Cloudflare: ${m?.error ?? cloudflareSecret(dataDir, any).problem ?? \"no answer\"}.` };\n let last: TurnCheck = { ok: false, error: \"Cloudflare gave no TURN server.\" };\n for (const s of creds.servers) {\n last = await check(s, timeoutMs);\n if (last.ok) break;\n }\n return { turn: CLOUDFLARE_LABEL, ...last };\n }\n const t = any;\n const { password, problem } = turnPassword(dataDir, t);\n if (!password) return { ok: false, turn: label(t), error: `The TURN server can't be used: ${problem}.` };\n return { turn: label(t), ...(await check(turnServer(t, password), timeoutMs)) };\n}\n","// The invite desk: answers join codes. It runs on the machine that made the\n// codes (an admin's), while that machine is sharing; a code whose maker is\n// offline waits until it's back.\n//\n// One signalling room per live invite; the room an offer arrives on says\n// which invite (and so which secret) the newcomer must prove. A newcomer's\n// first frames, in order:\n// desk → {t:\"challenge\", nonce, host}\n// them → {t:\"auth\", proof, name, key, sig, about} proof = HMAC(invite secret), sig = Ed25519 over the nonce\n// desk → {t:\"welcome\", ...} | {t:\"denied\", reason}\n// The welcome carries the graph (id, name, group secret) and its whole change\n// log, so the newcomer has a full copy from the start and can join the mesh.\n// The newcomer answers {t:\"thanks\"} once it has it, and the connection closes.\n\nimport { randomBytes } from \"node:crypto\";\nimport nodeDataChannel, { type PeerConnection } from \"node-datachannel\";\nimport { NAME_RE, verifySignature } from \"../core/identity.js\";\nimport { cleanAbout } from \"../core/members.js\";\nimport { inviteLink, isLive, type Invite, type InviteStore } from \"../host/state.js\";\nimport { FramedChannel } from \"./channel.js\";\nimport { prepareIce, rtcConfig, type IceSource } from \"./ice.js\";\nimport { b64u, checkProof } from \"./link.js\";\nimport type { SignalFactory, Signaller } from \"./signal.js\";\n\nconst MAX_AT_ONCE = 20;\nconst PROVE_WITHIN_MS = 15_000;\n\nexport interface Newcomer {\n key: string;\n name: string;\n about?: Record<string, string>;\n invite: Invite;\n}\n\nexport type Admission = { welcome: Record<string, unknown> } | { deny: string };\n\nexport interface DeskOptions {\n hostName(): string;\n invites: InviteStore;\n signal: SignalFactory;\n /** Read for each newcomer. */\n ice: IceSource;\n /** Decides on someone who proved a live code: let them in (and what to send them), or not. */\n admit(n: Newcomer): Promise<Admission>;\n log?(msg: string): void;\n}\n\ninterface Pending {\n id: string;\n from: string;\n invite: string;\n pc: PeerConnection;\n ch?: FramedChannel;\n answer?: { sdp: string; sdpType: string };\n done: boolean;\n}\n\nexport class InviteDesk {\n private pending = new Map<string, Pending>();\n private rooms = new Map<string, Signaller>();\n private sweep: NodeJS.Timeout;\n private stopped = false;\n\n constructor(private o: DeskOptions) {\n for (const inv of o.invites.live()) this.listen(inv);\n this.sweep = setInterval(() => this.closeDead(), 60_000);\n this.sweep.unref();\n }\n\n /** Makes a new invite and starts listening for it. */\n invite(opts: { label?: string; role?: Invite[\"role\"]; hours?: number } = {}): Invite {\n const inv = this.o.invites.create(opts);\n this.listen(inv);\n this.o.log?.(`new invite ${inv.id}${inv.label ? ` (${inv.label})` : \"\"}`);\n return inv;\n }\n\n /** Cancels an invite: its code stops working. */\n revoke(id: string, reason = \"The host cancelled this join code.\"): boolean {\n const inv = this.o.invites.revoke(id, reason);\n for (const p of this.pending.values()) if (p.invite === id) this.drop(p, reason);\n this.unlisten(id);\n return Boolean(inv);\n }\n\n stop(): void {\n if (this.stopped) return;\n this.stopped = true;\n clearInterval(this.sweep);\n for (const p of this.pending.values()) this.drop(p, \"The host stopped sharing.\");\n for (const id of [...this.rooms.keys()]) this.unlisten(id);\n }\n\n private listen(inv: Invite): void {\n if (this.rooms.has(inv.id) || this.stopped) return;\n this.rooms.set(inv.id, this.o.signal(inviteLink(inv), (m) => void this.onSignal(inv.id, m)));\n }\n\n private unlisten(id: string): void {\n this.rooms.get(id)?.close();\n this.rooms.delete(id);\n }\n\n private closeDead(): void {\n for (const id of this.rooms.keys()) {\n const inv = this.o.invites.get(id);\n if (!inv || !isLive(inv)) this.unlisten(id);\n }\n }\n\n private async onSignal(invite: string, m: any): Promise<void> {\n if (this.stopped || m?.type !== \"offer\" || typeof m.from !== \"string\" || typeof m.sdp !== \"string\") return;\n const signaller = this.rooms.get(invite);\n const inv = this.o.invites.get(invite);\n if (!signaller || !inv || !isLive(inv)) return this.unlisten(invite);\n const id = `${invite}:${m.from}`;\n const existing = this.pending.get(id);\n if (existing) {\n if (existing.answer) await signaller.send({ type: \"answer\", to: m.from, ...existing.answer });\n return;\n }\n if (this.pending.size >= MAX_AT_ONCE) return;\n await prepareIce(this.o.ice);\n if (this.stopped || this.pending.has(id)) return;\n const pc = new nodeDataChannel.PeerConnection(`vine-desk-${m.from}`, rtcConfig(this.o.ice));\n const p: Pending = { id, from: m.from, invite, pc, done: false };\n this.pending.set(id, p);\n pc.onStateChange((s) => {\n if (s === \"failed\" || s === \"closed\" || s === \"disconnected\") this.forget(p);\n });\n pc.onDataChannel((dc) => this.onChannel(p, new FramedChannel(dc)));\n setTimeout(() => this.pending.get(id) === p && this.drop(p, \"Took too long to connect.\"), PROVE_WITHIN_MS + 30_000).unref();\n try {\n pc.setRemoteDescription(m.sdp, m.sdpType);\n const local = await gathered(pc);\n p.answer = { sdp: local.sdp, sdpType: local.type };\n await signaller.send({ type: \"answer\", to: m.from, ...p.answer });\n } catch (e) {\n this.o.log?.(`offer from ${m.from} failed: ${(e as Error).message}`);\n this.forget(p);\n }\n }\n\n private onChannel(p: Pending, ch: FramedChannel): void {\n p.ch = ch;\n const nonce = b64u(randomBytes(16));\n ch.onClose(() => this.forget(p));\n ch.onMessage(async (m: any) => {\n if (p.done) {\n if (m?.t === \"thanks\") this.drop(p, \"\", false); // they have the log: close\n return;\n }\n p.done = true;\n const inv = this.o.invites.get(p.invite);\n if (!inv || !isLive(inv)) return this.drop(p, \"This join code no longer works. Ask for a new one.\");\n if (m?.t !== \"auth\" || !checkProof(inviteLink(inv).secret, nonce, p.from, m.proof)) return this.drop(p, \"Wrong or missing join code secret.\");\n if (typeof m.key !== \"string\" || !verifySignature(m.key, `vine-id-v1:${nonce}:${p.from}`, m.sig)) return this.drop(p, \"Identity signature did not verify.\");\n if (typeof m.name !== \"string\" || !NAME_RE.test(m.name)) return this.drop(p, \"Names are 1–40 letters, digits, spaces, dots, dashes or underscores.\");\n let out: Admission;\n try {\n out = await this.o.admit({ key: m.key, name: m.name, about: cleanAbout(m.about), invite: inv });\n } catch (e) {\n out = { deny: (e as Error).message };\n }\n if (\"deny\" in out) return this.drop(p, out.deny);\n this.send(p, { t: \"welcome\", host: this.o.hostName(), ...out.welcome });\n setTimeout(() => this.drop(p, \"\", false), 60_000).unref();\n });\n const greet = () => this.send(p, { t: \"challenge\", nonce, host: this.o.hostName() });\n if (ch.dc.isOpen()) greet();\n else ch.dc.onOpen(greet);\n }\n\n private send(p: Pending, m: Record<string, unknown>) {\n try {\n p.ch?.send(m);\n } catch {\n this.forget(p);\n }\n }\n\n private drop(p: Pending, reason: string, deny = true): void {\n if (deny && reason) this.send(p, { t: \"denied\", reason });\n setTimeout(() => {\n try {\n p.pc.close();\n } catch {\n // already closed\n }\n }, 300).unref();\n this.forget(p);\n }\n\n private forget(p: Pending): void {\n if (this.pending.get(p.id) === p) this.pending.delete(p.id);\n }\n}\n\nexport function gathered(pc: PeerConnection): Promise<{ sdp: string; type: string }> {\n return new Promise((resolve, reject) => {\n const done = () => {\n const d = pc.localDescription();\n if (d) resolve(d as { sdp: string; type: string });\n else reject(new Error(\"no local description\"));\n };\n if (pc.gatheringState() === \"complete\") return done();\n pc.onGatheringStateChange((s) => s === \"complete\" && done());\n });\n}\n","// The mesh: every online member of a graph connected to every other, keeping\n// each other's change logs in step.\n//\n// Members meet in the group's signalling room (named and sealed with the\n// group secret, which only members hold) and set up WebRTC links with each\n// other. Of two members, the one with the smaller key makes the offer.\n//\n// A link's first frames, both ways:\n// {t:\"hi\", key, nonce}\n// {t:\"prove\", sig, proof, joined?} sig: Ed25519 over the other's nonce; proof: HMAC(group secret)\n// `joined` may carry the prover's add_member change, for a member who sees\n// them before their add_member reached it. Only current members are accepted.\n// Then both send {t:\"have\"} (one number per author), each sends what the other\n// lacks ({t:\"changes\"}), and from then on new changes are forwarded as they\n// come. Links are pinged; one that goes quiet is dropped and set up again.\n\nimport { randomBytes } from \"node:crypto\";\nimport nodeDataChannel, { type PeerConnection } from \"node-datachannel\";\nimport type { Change, Have } from \"../core/changes.js\";\nimport { fingerprint, verifySignature, type Identity } from \"../core/identity.js\";\nimport { FramedChannel } from \"./channel.js\";\nimport { prepareIce, rtcConfig, type IceSource } from \"./ice.js\";\nimport { gathered } from \"./invites.js\";\nimport { b64u, checkProof, proof, type Link } from \"./link.js\";\nimport type { SignalFactory, Signaller } from \"./signal.js\";\n\n/** Up to 20 members: at most 19 links each. A little room for reconnects. */\nconst MAX_LINKS = 30;\nconst BATCH = 400;\n\nexport interface MeshOptions {\n group: Link;\n graphId: string;\n identity: Identity;\n signal: SignalFactory;\n /** Read for each new link. */\n ice: IceSource;\n /** Is this key a current member? */\n isMember(key: string): boolean;\n /** This machine's add_member change, if it has one, to show members who haven't seen it yet. */\n myJoin(): Change | undefined;\n have(): Have;\n missing(theirs: Have): Change[];\n /** Takes changes from a member; returns those that were new here (to forward). */\n receive(changes: Change[], from: string): Promise<Change[]>;\n onChange?(): void;\n /**\n * A member was found through the relays, but links to them keep failing to\n * connect (their network and this one won't allow a direct connection).\n * Called once each time a member becomes unreachable.\n */\n onUnreachable?(key: string): void;\n log?(m: string): void;\n /** Ping interval and the silence after which a link is dropped. */\n pingMs?: number;\n helloMs?: number;\n /** How long a link may take to connect before it's dropped (default 45 s). */\n connectMs?: number;\n}\n\ninterface PeerLink {\n id: string;\n pc: PeerConnection;\n ch?: FramedChannel;\n key?: string;\n /** The other side's session id in the room. */\n them: string;\n state: \"connecting\" | \"active\";\n nonce: string;\n proven: { me: boolean; them: boolean };\n lastHeard: number;\n since: string;\n answer?: { sdp: string; sdpType: string };\n initiator: boolean;\n /** Sync frames that arrived before this side finished checking the link: handled once it has. */\n early: any[];\n}\n\n/** Failed attempts in a row before a member counts as unreachable. */\nconst UNREACHABLE_AFTER = 2;\n\n/** A member found through the relays whose links never connect. */\nexport interface Unreachable {\n key: string;\n fingerprint: string;\n attempts: number;\n /** When the first failed attempt in this run was. */\n since: string;\n}\n\nexport interface LinkInfo {\n key: string;\n fingerprint: string;\n state: \"connecting\" | \"active\";\n since: string;\n /** How the data travels once linked: straight between the two machines, or through a TURN server. */\n route?: \"direct\" | \"relayed\";\n}\n\n/** The route a connected link settled on, if the library can say. */\nexport function routeOf(pc: PeerConnection): \"direct\" | \"relayed\" | undefined {\n try {\n const pair = pc.getSelectedCandidatePair();\n if (!pair) return undefined;\n return [pair.local?.type, pair.remote?.type].some((t) => String(t).toLowerCase() === \"relay\") ? \"relayed\" : \"direct\";\n } catch {\n return undefined;\n }\n}\n\nexport class Mesh {\n private me = b64u(randomBytes(6));\n private room: Signaller;\n private links = new Map<string, PeerLink>();\n private timers: NodeJS.Timeout[] = [];\n private stopped = false;\n private lastHelloReply = new Map<string, number>();\n private failures = new Map<string, { attempts: number; since: string }>();\n\n constructor(private o: MeshOptions) {\n this.room = o.signal(o.group, (m) => void this.onSignal(m));\n const pingMs = o.pingMs ?? 15_000;\n this.timers.push(setInterval(() => this.hello(), o.helloMs ?? 30_000));\n this.timers.push(setInterval(() => this.keepalive(pingMs), pingMs));\n for (const t of this.timers) t.unref();\n this.hello();\n }\n\n get myKey(): string {\n return this.o.identity.publicKey;\n }\n\n /** Members this machine has a link to. */\n online(): LinkInfo[] {\n return [...this.links.values()]\n .filter((l) => l.key)\n .map((l) => {\n const route = l.state === \"active\" ? routeOf(l.pc) : undefined;\n return { key: l.key!, fingerprint: fingerprint(l.key!), state: l.state, since: l.since, ...(route ? { route } : {}) };\n });\n }\n\n /** The signalling relays' states, for status. */\n relayStatus(): Record<string, string> {\n return this.room.status?.() ?? {};\n }\n\n /** Members found through the relays whose links keep failing to connect, and who aren't linked now. */\n unreachable(): Unreachable[] {\n return [...this.failures.entries()]\n .filter(([key, f]) => f.attempts >= UNREACHABLE_AFTER && !this.isOnline(key) && this.o.isMember(key))\n .map(([key, f]) => ({ key, fingerprint: fingerprint(key), attempts: f.attempts, since: f.since }));\n }\n\n isOnline(key: string): boolean {\n return [...this.links.values()].some((l) => l.key === key && l.state === \"active\");\n }\n\n /** Sends new changes to every linked member, except the one they came from. */\n broadcast(changes: Change[], exceptKey?: string): void {\n if (!changes.length) return;\n for (const l of this.links.values()) if (l.state === \"active\" && l.key !== exceptKey) this.sendChanges(l, changes);\n }\n\n /** Says hello again now: after a new member is added, so links to them don't wait for the next round. */\n nudge(): void {\n this.hello();\n }\n\n /**\n * Drops links to a key (removed from the graph). `farewell` (the removal\n * itself) is sent first, so the removed machine learns it was removed.\n */\n drop(key: string, farewell: Change[] = [], reason = \"removed\"): void {\n for (const l of [...this.links.values()]) {\n if (l.key !== key) continue;\n if (l.state === \"active\" && farewell.length) {\n this.sendChanges(l, farewell);\n setTimeout(() => this.close(l, reason), 1000).unref();\n } else this.close(l, reason);\n }\n }\n\n stop(): void {\n if (this.stopped) return;\n this.stopped = true;\n for (const t of this.timers) clearInterval(t);\n for (const l of [...this.links.values()]) this.close(l, \"stopped\");\n this.room.close();\n }\n\n private log(m: string) {\n this.o.log?.(m);\n }\n\n private hello(to?: string) {\n if (this.stopped) return;\n void this.room.send({ type: \"hello\", from: this.me, key: this.myKey, ...(to ? { to } : {}) });\n }\n\n private keepalive(pingMs: number) {\n const now = Date.now();\n for (const l of [...this.links.values()]) {\n if (l.state === \"active\" && now - l.lastHeard > pingMs * 3) {\n this.log(`no word from ${l.key ? fingerprint(l.key) : l.them} for ${Math.round((now - l.lastHeard) / 1000)}s; reconnecting`);\n this.close(l, \"silent\");\n this.hello();\n continue;\n }\n if (l.state === \"connecting\" && now - l.lastHeard > (this.o.connectMs ?? 45_000)) {\n this.noteFailure(l);\n this.close(l, \"took too long to connect\");\n continue;\n }\n if (l.state === \"active\") this.send(l, { t: \"ping\" });\n }\n }\n\n private linkTo(key: string): PeerLink | undefined {\n return [...this.links.values()].find((l) => l.key === key);\n }\n\n private async onSignal(m: any): Promise<void> {\n if (this.stopped || !m || typeof m.from !== \"string\" || m.from === this.me) return;\n if (m.to && m.to !== this.me) return;\n if (m.type === \"hello\") {\n if (typeof m.key !== \"string\" || m.key === this.myKey || !this.o.isMember(m.key)) return;\n const existing = this.linkTo(m.key);\n // The same session, still linked or linking: nothing to do. A new session of\n // that member (it restarted, or went offline and back) replaces a link that\n // may still look alive on this side.\n if (existing && existing.them === m.from && (existing.state === \"active\" || Date.now() - existing.lastHeard < 20_000)) return;\n if (existing) this.close(existing, existing.them === m.from ? \"stale\" : \"they reconnected\");\n if (this.myKey < m.key) return this.offer(m.from, m.key);\n // They make the offer: make sure they've heard of us.\n const last = this.lastHelloReply.get(m.from) ?? 0;\n if (Date.now() - last > 5000) {\n this.lastHelloReply.set(m.from, Date.now());\n this.hello(m.from);\n }\n return;\n }\n if (m.type === \"offer\" && typeof m.sdp === \"string\" && typeof m.key === \"string\") return this.answer(m);\n if (m.type === \"answer\" && typeof m.sdp === \"string\") {\n const l = this.links.get(m.from);\n if (!l || !l.initiator || l.answer) return;\n l.answer = { sdp: m.sdp, sdpType: m.sdpType };\n try {\n l.pc.setRemoteDescription(m.sdp, m.sdpType);\n } catch (e) {\n this.close(l, `bad answer: ${(e as Error).message}`);\n }\n }\n }\n\n private newLink(them: string, initiator: boolean, key?: string): PeerLink | undefined {\n if (this.links.size >= MAX_LINKS) {\n this.log(`ignoring ${them}: ${MAX_LINKS} links already`);\n return undefined;\n }\n const pc = new nodeDataChannel.PeerConnection(`vine-mesh-${this.me}-${them}`, rtcConfig(this.o.ice));\n const l: PeerLink = {\n id: them,\n pc,\n them,\n key,\n state: \"connecting\",\n nonce: b64u(randomBytes(16)),\n proven: { me: false, them: false },\n lastHeard: Date.now(),\n since: new Date().toISOString(),\n initiator,\n early: [],\n };\n this.links.set(them, l);\n pc.onStateChange((s) => {\n if (s === \"failed\" && l.state === \"connecting\") this.noteFailure(l);\n if (s === \"failed\" || s === \"closed\" || s === \"disconnected\") this.forget(l);\n });\n return l;\n }\n\n private async offer(them: string, key: string) {\n // Minted TURN credentials (Cloudflare) are fetched or renewed first, if due.\n await prepareIce(this.o.ice);\n if (this.stopped || this.links.has(them) || this.linkTo(key)) return;\n const l = this.newLink(them, true, key);\n if (!l) return;\n const dc = l.pc.createDataChannel(\"vine-mesh\");\n this.attach(l, new FramedChannel(dc));\n try {\n const offer = await gathered(l.pc);\n const msg = { type: \"offer\", from: this.me, to: them, key: this.myKey, sdp: offer.sdp, sdpType: offer.type };\n await this.room.send(msg);\n // Relays can drop messages: resend until answered.\n const retry = setInterval(() => {\n if (l.answer || this.links.get(them) !== l || this.stopped) return clearInterval(retry);\n void this.room.send(msg);\n }, 3000);\n retry.unref();\n } catch (e) {\n this.log(`offer to ${fingerprint(key)} failed: ${(e as Error).message}`);\n this.forget(l);\n }\n }\n\n private async answer(m: any) {\n if (!this.o.isMember(m.key) && m.key !== this.myKey) return;\n const existing = this.links.get(m.from);\n if (existing) {\n if (existing.answer && !existing.initiator) await this.room.send({ type: \"answer\", from: this.me, to: m.from, ...existing.answer });\n return;\n }\n await prepareIce(this.o.ice);\n if (this.stopped || this.links.has(m.from)) return;\n const byKey = this.linkTo(m.key);\n if (byKey?.state === \"active\" && byKey.them === m.from) return;\n if (byKey) this.close(byKey, \"they reconnected\");\n const l = this.newLink(m.from, false, m.key);\n if (!l) return;\n l.pc.onDataChannel((dc) => this.attach(l, new FramedChannel(dc)));\n try {\n l.pc.setRemoteDescription(m.sdp, m.sdpType);\n const local = await gathered(l.pc);\n l.answer = { sdp: local.sdp, sdpType: local.type };\n await this.room.send({ type: \"answer\", from: this.me, to: m.from, ...l.answer });\n } catch (e) {\n this.log(`answer to ${m.from} failed: ${(e as Error).message}`);\n this.forget(l);\n }\n }\n\n private attach(l: PeerLink, ch: FramedChannel) {\n l.ch = ch;\n ch.onClose(() => this.forget(l));\n ch.onMessage((m: any) => void this.onFrame(l, m));\n const greet = () => this.send(l, { t: \"hi\", key: this.myKey, nonce: l.nonce });\n if (ch.dc.isOpen()) greet();\n else ch.dc.onOpen(greet);\n }\n\n private async onFrame(l: PeerLink, m: any) {\n l.lastHeard = Date.now();\n switch (m?.t) {\n case \"hi\": {\n if (typeof m.key !== \"string\" || typeof m.nonce !== \"string\") return this.close(l, \"bad hello\");\n if (l.key && l.key !== m.key) return this.close(l, \"key changed\");\n l.key = m.key;\n const msg = `vine-mesh-v1:${this.o.graphId}:${m.nonce}:${this.myKey}`;\n return this.send(l, {\n t: \"prove\",\n sig: this.o.identity.sign(msg),\n proof: proof(this.o.group.secret, m.nonce, this.myKey),\n joined: this.o.myJoin() ?? null,\n });\n }\n case \"prove\": {\n if (!l.key) return this.close(l, \"prove before hello\");\n const ok =\n verifySignature(l.key, `vine-mesh-v1:${this.o.graphId}:${l.nonce}:${l.key}`, m.sig) && checkProof(this.o.group.secret, l.nonce, l.key, m.proof);\n if (!ok) return this.close(l, \"proof did not verify\");\n if (!this.o.isMember(l.key) && m.joined) await this.o.receive([m.joined], l.key);\n if (!this.o.isMember(l.key)) return this.close(l, \"not a member\");\n l.proven.them = true;\n l.state = \"active\";\n this.failures.delete(l.key);\n this.log(`linked with ${fingerprint(l.key)}`);\n this.o.onChange?.();\n this.send(l, { t: \"have\", have: this.o.have() });\n // The other side may have checked us first and already sent its sync frames.\n for (const f of l.early.splice(0)) await this.onFrame(l, f);\n return;\n }\n case \"have\": {\n if (l.state !== \"active\") return void l.early.push(m);\n const missing = this.o.missing(m.have && typeof m.have === \"object\" ? m.have : {});\n if (missing.length) this.log(`catching ${fingerprint(l.key!)} up: ${missing.length} change(s)`);\n this.sendChanges(l, missing);\n return;\n }\n case \"changes\": {\n if (!Array.isArray(m.changes)) return;\n if (l.state !== \"active\") return void (l.early.length < 1000 && l.early.push(m));\n const fresh = await this.o.receive(m.changes, l.key!);\n this.broadcast(fresh, l.key);\n return;\n }\n case \"ping\":\n return this.send(l, { t: \"pong\" });\n case \"pong\":\n return;\n }\n }\n\n private sendChanges(l: PeerLink, changes: Change[]) {\n for (let i = 0; i < changes.length; i += BATCH) this.send(l, { t: \"changes\", changes: changes.slice(i, i + BATCH) });\n }\n\n private send(l: PeerLink, m: Record<string, unknown>) {\n try {\n l.ch?.send(m);\n } catch {\n this.forget(l);\n }\n }\n\n /**\n * A link that got as far as the handshake (both sides' descriptions\n * swapped through the relays) but never connected: the networks are in the\n * way, not the relays.\n */\n private noteFailure(l: PeerLink) {\n if (!l.key || l.state !== \"connecting\" || this.stopped || this.links.get(l.id) !== l) return;\n if (l.initiator && !l.answer) return; // the answer never came: a relay problem, not a network one\n const f = this.failures.get(l.key) ?? { attempts: 0, since: new Date().toISOString() };\n f.attempts++;\n this.failures.set(l.key, f);\n this.log(`couldn't connect to ${fingerprint(l.key)} (attempt ${f.attempts}): found through the relays, but no direct or relayed route worked`);\n if (f.attempts === UNREACHABLE_AFTER) this.o.onUnreachable?.(l.key);\n }\n\n private close(l: PeerLink, reason: string) {\n this.log(`closing link ${l.key ? fingerprint(l.key) : l.them}: ${reason}`);\n try {\n l.pc.close();\n } catch {\n // already closed\n }\n this.forget(l);\n }\n\n private forget(l: PeerLink) {\n if (this.links.get(l.id) !== l) return;\n this.links.delete(l.id);\n try {\n l.pc.close();\n } catch {\n // already closed\n }\n this.o.onChange?.();\n // Look for the others again soon: this one may come straight back.\n if (!this.stopped) setTimeout(() => this.hello(), 1000).unref();\n }\n}\n\n/** The group's signalling room: named from the graph id, sealed with the group secret. */\nexport function groupLink(graphId: string, secret: Buffer): Link {\n return { room: `group-${graphId}`, secret };\n}\n","// What to tell a person when members are found but can't be connected to.\n\n/** \"Sam\", \"Sam and Ana\", \"Sam, Ana and Lee\". */\nexport function names(list: string[]): string {\n if (list.length <= 1) return list[0] ?? \"a member\";\n return `${list.slice(0, -1).join(\", \")} and ${list.at(-1)}`;\n}\n\n/**\n * The message for members found through the relays whose links never\n * connect. `anyLinked`: whether this machine reaches any member at all (then\n * changes still arrive, forwarded, and nothing needs doing). `turn`: whether\n * a TURN server is set here.\n */\nexport function unreachableAdvice(who: string[], o: { anyLinked: boolean; turn: \"none\" | \"cloudflare\" | \"custom\" | \"env\" }): string {\n const machine = who.length === 1 ? `${who[0]}'s machine` : `the machines of ${names(who)}`;\n const found = `Found ${machine}, but your networks wouldn't allow a direct connection.`;\n if (o.anyLinked) return `${found} Nothing to do: you're linked to another member, so their changes still reach you, forwarded.`;\n if (o.turn === \"none\")\n return (\n `${found} A TURN server can carry the connection (it only relays encrypted data, and only one of you needs one). ` +\n \"Run `vine turn set --provider cloudflare` (or `npx vine-context setup`) to set up Cloudflare's, free for this use.\"\n );\n if (o.turn === \"env\") return `${found} VINE_ICE is set here and replaces the TURN setting: check the TURN server in it.`;\n return `${found} Even your TURN server didn't get through: run \\`vine turn test\\` to check it.`;\n}\n","// A minimal Nostr relay client for signalling: publish ephemeral events and\n// subscribe by tag, across several relays, with per-relay timeouts and\n// reconnects. nostr-tools is used only to sign (finalizeEvent).\n//\n// A host runs for hours, through sleeps and network drops, so each relay is\n// pinged; one that stops answering is dropped and reconnected, forever, with\n// the wait between tries capped. A connection that dies without closing\n// (common after a sleep) would otherwise look open while hearing nothing.\n//\n// Why not nostr-tools' SimplePool: in nostr-tools 2.26 a failed relay\n// connection overflows the stack (found 2026-11-15).\n\nimport WebSocket from \"ws\";\nimport { finalizeEvent, generateSecretKey, type Event } from \"nostr-tools/pure\";\nimport type { Filter } from \"nostr-tools/filter\";\n\ntype Handler = (ev: Event) => void;\n\nexport class RelaySet {\n private sockets = new Map<string, WebSocket>();\n private subs = new Map<string, { filter: Filter; handler: Handler }>();\n private waiting = new Map<string, Map<string, (ok: boolean) => void>>();\n private seen = new Set<string>();\n private closed = false;\n private sk = generateSecretKey();\n readonly status = new Map<string, \"connecting\" | \"open\" | \"down\">();\n\n constructor(\n private relays: string[],\n private timeoutMs = 4000,\n private keepalive: { pingMs: number; maxWaitMs: number } = { pingMs: 30_000, maxWaitMs: 60_000 },\n ) {\n for (const url of relays) this.connect(url, 0);\n }\n\n private connect(url: string, attempt: number) {\n if (this.closed) return;\n this.status.set(url, \"connecting\");\n const ws = new WebSocket(url, { handshakeTimeout: this.timeoutMs });\n this.sockets.set(url, ws);\n let alive = true;\n let ping: NodeJS.Timeout | undefined;\n ws.on(\"pong\", () => (alive = true));\n ws.on(\"open\", () => {\n attempt = 0;\n this.status.set(url, \"open\");\n for (const [id, s] of this.subs) ws.send(JSON.stringify([\"REQ\", id, s.filter]));\n ping = setInterval(() => {\n if (!alive) return ws.terminate(); // no pong since the last ping: dead\n alive = false;\n ws.ping();\n }, this.keepalive.pingMs);\n ping.unref();\n });\n ws.on(\"message\", (data) => {\n let msg: unknown[];\n try {\n msg = JSON.parse(String(data));\n } catch {\n return;\n }\n if (msg[0] === \"EVENT\") {\n const ev = msg[2] as Event;\n if (this.seen.has(ev.id)) return;\n this.seen.add(ev.id);\n this.subs.get(msg[1] as string)?.handler(ev);\n } else if (msg[0] === \"OK\") {\n this.waiting.get(url)?.get(msg[1] as string)?.(msg[2] === true);\n }\n });\n let gone = false;\n const down = () => {\n // \"error\" and \"close\" both arrive for one failure; act once, and only for the current socket.\n if (gone) return;\n gone = true;\n clearInterval(ping);\n ws.removeAllListeners(\"message\");\n if (this.sockets.get(url) !== ws) return;\n this.status.set(url, \"down\");\n for (const resolve of this.waiting.get(url)?.values() ?? []) resolve(false);\n if (this.closed) return;\n const wait = Math.min(500 * 2 ** attempt, this.keepalive.maxWaitMs);\n setTimeout(() => this.connect(url, attempt + 1), wait).unref();\n };\n ws.on(\"error\", down);\n ws.on(\"close\", down);\n }\n\n subscribe(filter: Filter, handler: Handler): string {\n const id = Math.random().toString(36).slice(2, 10);\n this.subs.set(id, { filter, handler });\n for (const ws of this.sockets.values())\n if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify([\"REQ\", id, filter]));\n return id;\n }\n\n /** Publish to every relay. Resolves as soon as one relay accepts, or with 0 when all fail or time out. */\n publish(template: { kind: number; tags: string[][]; content: string }): Promise<number> {\n const ev = finalizeEvent({ ...template, created_at: Math.floor(Date.now() / 1000) }, this.sk);\n return new Promise((resolve) => {\n let pending = this.relays.length;\n let accepted = 0;\n const settle = (ok: boolean) => {\n if (ok && ++accepted === 1) resolve(1);\n if (--pending === 0 && accepted === 0) resolve(0);\n };\n for (const url of this.relays) {\n const ws = this.sockets.get(url);\n const send = () => {\n const map = this.waiting.get(url) ?? new Map();\n this.waiting.set(url, map);\n const timer = setTimeout(() => done(false), this.timeoutMs);\n const done = (ok: boolean) => {\n clearTimeout(timer);\n if (map.delete(ev.id)) settle(ok);\n };\n map.set(ev.id, done);\n ws!.send(JSON.stringify([\"EVENT\", ev]));\n };\n if (ws?.readyState === WebSocket.OPEN) send();\n else if (ws?.readyState === WebSocket.CONNECTING) {\n const t = setTimeout(() => settle(false), this.timeoutMs);\n ws.once(\"open\", () => (clearTimeout(t), send()));\n ws.once(\"error\", () => (clearTimeout(t), settle(false)));\n } else settle(false);\n }\n });\n }\n\n close() {\n this.closed = true;\n for (const ws of this.sockets.values()) {\n ws.on(\"error\", () => undefined); // terminating a connecting socket emits an error\n ws.terminate();\n }\n }\n}\n","// Signalling: how members (and newcomers with a join code) exchange WebRTC offers and answers.\n//\n// Messages are sealed with the link's key and published on a topic named by a\n// hash of the room, so a relay sees neither the secret nor the contents.\n// Production uses public Nostr relays; tests use an in-process bus.\n\nimport { EventEmitter } from \"node:events\";\nimport { RelaySet } from \"./nostr.js\";\nimport { roomKeys, seal, unseal, type Link } from \"./link.js\";\n\nexport interface Signaller {\n /** Resolves true once at least one relay accepted the message. */\n send(message: unknown): Promise<boolean>;\n close(): void;\n /** Each relay's connection state, where there are relays. */\n status?(): Record<string, string>;\n}\n\nexport type SignalFactory = (link: Link, onMessage: (m: any) => void) => Signaller;\n\nexport const DEFAULT_RELAYS = [\n \"wss://relay.primal.net\",\n \"wss://offchain.pub\",\n \"wss://relay.snort.social\",\n \"wss://relay.nostr.net\",\n \"wss://nos.lol\",\n];\n\nconst KIND = 25050; // ephemeral: relays forward it but don't store it\n\nexport function relayList(): string[] {\n const env = process.env.VINE_RELAYS;\n return env ? env.split(\",\").map((s) => s.trim()).filter(Boolean) : DEFAULT_RELAYS;\n}\n\nexport const nostrSignaller: SignalFactory = (link, onMessage) => {\n const { tag, key } = roomKeys(link);\n const relays = new RelaySet(relayList());\n relays.subscribe({ kinds: [KIND], \"#t\": [tag], since: Math.floor(Date.now() / 1000) - 10 }, (ev) => {\n const m = unseal(key, ev.content);\n if (m) onMessage(m);\n });\n return {\n send: async (m) => (await relays.publish({ kind: KIND, tags: [[\"t\", tag]], content: seal(key, m) })) > 0,\n close: () => relays.close(),\n status: () => Object.fromEntries(relays.status),\n };\n};\n\n/** An in-process signalling bus, for tests: the same sealing, no network. */\nexport function memorySignaller(bus = new EventEmitter()): SignalFactory {\n bus.setMaxListeners(100);\n return (link, onMessage) => {\n const { tag, key } = roomKeys(link);\n const listener = (content: string) => {\n const m = unseal(key, content);\n if (m) onMessage(m);\n };\n bus.on(tag, listener);\n return {\n send: async (m) => {\n const content = seal(key, m);\n setImmediate(() => bus.emit(tag, content));\n return true;\n },\n close: () => bus.off(tag, listener),\n };\n };\n}\n","// The sync digest: what changes from other members mean for this machine's\n// person, worked out after they arrive (a live sync, or a catch-up after being\n// offline). Not just \"bob claimed …\", but:\n// - a claim of yours was replaced (and by what);\n// - a question of yours was answered;\n// - a new conflict: a claim contradicts another (yours first);\n// - two current claims replace the same claim: nobody settled which holds;\n// - a possible overlap: a new claim close to an existing one by someone else,\n// with no link between them, for the agent to link if they are related.\n// Nothing is linked automatically: recording SUPPORTS, CONTRADICTS or REPLACES\n// stays the agent's (and person's) decision.\n//\n// The briefing is the same idea for someone who has just joined: everything is\n// new to them, so it says what the context holds, what's open and what's\n// disputed.\n\nimport type { Change } from \"../core/changes.js\";\nimport { contentWords } from \"../core/embed.js\";\nimport type { Caller, Graph } from \"../core/graph.js\";\n\nconst MAX_LINES = 12;\nconst MAX_OVERLAP_CHECKS = 40;\n\nexport interface DigestContext {\n graph: Graph;\n me: string;\n name(key: string): string;\n reader: Caller;\n}\n\nconst q = (s: string, n = 90) => `\"${s.length > n ? `${s.slice(0, n - 1)}…` : s}\"`;\nconst arr = (v: unknown): string[] => (Array.isArray(v) ? v.filter((x): x is string => typeof x === \"string\") : []);\n\n/** Shared content words, as a share of the shorter text's: a rough \"about the same thing\" for the offline embedder. */\nexport function overlap(a: string, b: string): number {\n const x = new Set(contentWords(a).filter((w) => w.length > 2));\n const y = new Set(contentWords(b).filter((w) => w.length > 2));\n if (!x.size || !y.size) return 0;\n let shared = 0;\n for (const w of x) if (y.has(w)) shared++;\n return shared < 3 ? 0 : shared / Math.min(x.size, y.size);\n}\n\nexport async function digest(changes: Change[], ctx: DigestContext): Promise<string[]> {\n const others = changes.filter((c) => c.author !== ctx.me && [\"claim\", \"question\", \"reply\", \"link\", \"withdraw\"].includes(c.kind));\n if (!others.length) return [];\n const g = ctx.graph;\n\n // Every item the changes touch, looked up once.\n const ids: string[] = [];\n for (const c of others) {\n const b = c.body;\n if (typeof b.node === \"string\") ids.push(b.node);\n ids.push(...arr(b.replaces), ...arr(b.answers), ...arr(b.contradicts), ...arr(b.supports));\n if (typeof b.question === \"string\") ids.push(b.question);\n if (typeof b.from === \"string\") ids.push(b.from);\n if (typeof b.to === \"string\") ids.push(b.to);\n }\n const items = await g.items(ids);\n const mine = (id: string) => items.get(id)?.author === ctx.me;\n const text = (id: string) => q(items.get(id)?.text ?? id);\n\n const yours: string[] = [];\n const general: string[] = [];\n const replacedTargets = new Set<string>();\n const contradictions: [string, string, string][] = [];\n\n for (const c of others) {\n const who = ctx.name(c.author);\n const b = c.body;\n const rels: [string, string, string][] = [];\n if (c.kind === \"claim\" && typeof b.node === \"string\") {\n for (const t of arr(b.replaces)) rels.push([\"REPLACES\", b.node, t]);\n for (const t of arr(b.answers)) rels.push([\"ANSWERS\", b.node, t]);\n for (const t of arr(b.contradicts)) rels.push([\"CONTRADICTS\", b.node, t]);\n } else if (c.kind === \"link\" && typeof b.from === \"string\" && typeof b.to === \"string\" && typeof b.relation === \"string\") {\n rels.push([b.relation, b.from, b.to]);\n } else if (c.kind === \"reply\" && typeof b.question === \"string\" && mine(b.question)) {\n yours.push(`${who} replied to your question ${b.question} ${text(b.question)}: ${q(String(b.text ?? \"\"))}.`);\n } else if (c.kind === \"withdraw\" && typeof b.node === \"string\" && mine(b.node)) {\n yours.push(`${who} withdrew your ${items.get(b.node)?.label === \"Question\" ? \"question\" : \"claim\"} ${b.node} ${text(b.node)}.`);\n }\n for (const [rel, from, to] of rels) {\n if (!items.has(from) || !items.has(to)) continue;\n if (rel === \"REPLACES\") {\n replacedTargets.add(to);\n (mine(to) ? yours : general).push(\n mine(to) ? `${who} replaced your claim ${to} ${text(to)} with ${from} ${text(from)}.` : `${who} replaced ${to} ${text(to)} with ${from} ${text(from)}.`,\n );\n } else if (rel === \"ANSWERS\") {\n (mine(to) ? yours : general).push(\n mine(to) ? `${who} answered your question ${to} ${text(to)}: ${from} ${text(from)}.` : `${who} answered ${to} ${text(to)}: ${from} ${text(from)}.`,\n );\n } else if (rel === \"CONTRADICTS\") {\n contradictions.push([who, from, to]);\n }\n }\n }\n\n for (const [who, from, to] of contradictions) {\n const a = items.get(from)!;\n const b = items.get(to)!;\n if (!a.current || !b.current) continue;\n (mine(to) || mine(from) ? yours : general).push(\n mine(to)\n ? `New conflict: ${who}'s claim ${from} ${text(from)} contradicts your claim ${to} ${text(to)}.`\n : `New conflict: ${who}'s claim ${from} ${text(from)} contradicts ${b.by}'s claim ${to} ${text(to)}.`,\n );\n }\n\n // Two current claims replacing one: nobody has settled which holds.\n for (const t of replacedTargets) {\n const r = await g.currentReplacers(t);\n if (r.length >= 2)\n general.push(\n `Unsettled: ${r.length} current claims replace ${t} ${text(t)}: ${r.map((x) => `${x.id} by ${x.by} ${q(x.text, 60)}`).join(\"; \")}. Settle it with a claim that replaces them, or link them CONTRADICTS.`,\n );\n }\n\n // Possible overlaps: new claims close to an existing claim by someone else, with no link between them.\n const overlaps: string[] = [];\n const newClaims = others.filter((c) => c.kind === \"claim\" && typeof c.body.node === \"string\").slice(0, MAX_OVERLAP_CHECKS);\n for (const c of newClaims) {\n const node = c.body.node as string;\n const own = items.get(node);\n if (!own?.current) continue;\n const linked = await g.linkedIds(node);\n let found: Record<string, unknown>[] = [];\n try {\n found = (await g.call(\"search\", { query: own.text, kind: \"claim\", limit: 6 }, ctx.reader)) as Record<string, unknown>[];\n } catch {\n continue;\n }\n const match = found.find((r) => r.id !== node && !linked.has(String(r.id)) && r.recorded_by !== own.by && overlap(own.text, String(r.text ?? \"\")) >= 0.4);\n if (match)\n overlaps.push(\n `Possible overlap: ${own.by}'s new claim ${node} ${q(own.text, 70)} and ${match.recorded_by}'s claim ${match.id} ${q(String(match.text), 70)}. If they're related, link them (SUPPORTS, CONTRADICTS or REPLACES).`,\n );\n }\n\n const lines = [...yours, ...general, ...overlaps];\n const authors = [...new Set(others.map((c) => ctx.name(c.author)))];\n const head = others.length >= 3 ? [`Caught up ${others.length} changes from ${authors.join(\", \")}.`] : [];\n const shown = [...head, ...lines].slice(0, MAX_LINES);\n const more = head.length + lines.length - shown.length;\n return more > 0 ? [...shown, `…and ${more} more (recent with activity lists them).`] : shown;\n}\n\n/** For someone who has just joined: what the context holds, and what is open or disputed. */\nexport async function briefing(g: Graph, reader: Caller): Promise<Record<string, unknown>> {\n const read = async (tool: string, args: Record<string, unknown> = {}) => {\n try {\n return (await g.call(tool, args, reader)) as Record<string, unknown>[];\n } catch {\n return [];\n }\n };\n const info = await g.info();\n const open = await read(\"open_questions\");\n const conflicts = await read(\"conflicts\");\n const recent = await read(\"recent\", { since: \"2000-01-01T00:00:00Z\", limit: 5 });\n return {\n holds: info.nodes,\n open_questions: open.slice(0, 5).map((r) => ({ id: r.id, text: r.text, by: r.recorded_by })),\n open_question_count: open.length,\n conflicts: conflicts.slice(0, 5).map((r: any) => ({ claim: r.claim?.text ?? r.claim, contradicts: r.contradicts?.text ?? r.contradicts, flagged_by: r.flagged_by })),\n conflict_count: conflicts.length,\n latest: recent.map((r) => ({ id: r.id, text: r.text, by: r.recorded_by, at: r.recorded_at })),\n };\n}\n","// What others' changes meant for this machine's person (the sync digest), kept\n// on disk beside the context's host so anything on this machine can read it\n// without a running host: `hosts/<context>/news.json`, the latest entries,\n// newest last. The host is its only writer.\n//\n// Each chat keeps a marker of how far it has been told, per context, in\n// `chats/<chat id>.json`. Two things deliver news to a chat's agent: the MCP\n// server (in front of its next tool result) and the agent hook (`vine hook`,\n// beside the person's next prompt). Both read and move the same marker, so an\n// entry reaches the agent once.\n\nimport { mkdirSync, readFileSync, renameSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\n\nexport interface NewsEntry {\n at: string;\n lines: string[];\n}\n\nconst KEEP = 50;\n\nconst newsFile = (dataDir: string, graph: string) => join(dataDir, \"hosts\", graph, \"news.json\");\n\nfunction writeJson(file: string, value: unknown): void {\n mkdirSync(dirname(file), { recursive: true, mode: 0o700 });\n const tmp = `${file}.${process.pid}.tmp`;\n writeFileSync(tmp, JSON.stringify(value) + \"\\n\", { mode: 0o600 });\n renameSync(tmp, file);\n}\n\nfunction readJson(file: string): unknown {\n try {\n return JSON.parse(readFileSync(file, \"utf8\"));\n } catch {\n return undefined;\n }\n}\n\n/** The context's kept news, oldest first. */\nexport function readNews(dataDir: string, graph: string): NewsEntry[] {\n const raw = readJson(newsFile(dataDir, graph));\n if (!Array.isArray(raw)) return [];\n return raw.filter(\n (e): e is NewsEntry => Boolean(e) && typeof e.at === \"string\" && Array.isArray(e.lines) && e.lines.every((l: unknown) => typeof l === \"string\"),\n );\n}\n\nexport function appendNews(dataDir: string, graph: string, entry: NewsEntry): void {\n writeJson(newsFile(dataDir, graph), [...readNews(dataDir, graph), entry].slice(-KEEP));\n}\n\n/** What a chat has been told so far. */\nexport interface ChatMarks {\n /** Per context: the `at` of the newest news entry its agent was given. */\n seen: Record<string, string>;\n /** The contexts whose purpose its agent has been told (by the hook). */\n briefed: string[];\n}\n\n// A chat's id is its agent's (a UUID from Claude Code or Codex); anything else is made safe for a file name.\nconst chatFile = (dataDir: string, chat: string) => join(dataDir, \"chats\", `${chat.replace(/[^A-Za-z0-9._-]/g, \"_\").slice(0, 120)}.json`);\n\nexport function chatMarks(dataDir: string, chat: string): ChatMarks {\n const raw = readJson(chatFile(dataDir, chat)) as Partial<ChatMarks> | undefined;\n const seen: Record<string, string> = {};\n if (raw?.seen && typeof raw.seen === \"object\") for (const [k, v] of Object.entries(raw.seen)) if (typeof v === \"string\") seen[k] = v;\n return { seen, briefed: Array.isArray(raw?.briefed) ? raw.briefed.filter((b): b is string => typeof b === \"string\") : [] };\n}\n\n/** Changes a chat's marks. A failed write is not an error: the worst case is news told twice. */\nexport function updateChatMarks(dataDir: string, chat: string, change: (m: ChatMarks) => void): void {\n const m = chatMarks(dataDir, chat);\n change(m);\n try {\n writeJson(chatFile(dataDir, chat), m);\n } catch {\n // read-only data folder: nothing to do\n }\n}\n\n/** The news a chat hasn't been told yet, oldest first. A chat with no marker for the context has none: it starts from now. */\nexport function unseenNews(dataDir: string, chat: string, graph: string): NewsEntry[] {\n const since = chatMarks(dataDir, chat).seen[graph];\n return since ? readNews(dataDir, graph).filter((e) => e.at > since) : [];\n}\n\n/** Moves the chat's marker for a context forward to `at` (never back). */\nexport function markSeen(dataDir: string, chat: string, graph: string, at: string): void {\n updateChatMarks(dataDir, chat, (m) => {\n if (!m.seen[graph] || m.seen[graph]! < at) m.seen[graph] = at;\n });\n}\n","// The host: one long-running process per graph on each member's machine. It\n// owns this machine's copy of the graph: the change log, the Relate store\n// built from it, and the group secret.\n//\n// - Agent sessions on this machine reach it through a local socket, with this\n// machine's role in the graph.\n// - A write is checked, made into a change, applied here at once, and held\n// for HOLD_MS so it can be taken back; then it is numbered, signed and sent.\n// - While sharing (the default), it is in the mesh: linked to every other\n// online member, swapping the changes each side lacks. If this machine is\n// an admin it also answers the join codes it made.\n// - Changes from others are checked (signature, graph, the author's role at\n// the change's time) and applied. A membership change that arrives \"in the\n// past\" rebuilds the store from the log, so every machine ends up the same.\n\nimport { createHash, randomBytes } from \"node:crypto\";\nimport { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport { createConnection, createServer, type Server, type Socket } from \"node:net\";\nimport { dirname, join } from \"node:path\";\nimport { compareChanges, DATA_KINDS, MEMBER_KINDS, ROLES, signChange, uuidv7, wellFormed, type Change, type Role, type Unsigned } from \"../core/changes.js\";\nimport { Graph, ToolError, type ApplyContext, type Caller } from \"../core/graph.js\";\nimport { defaultName, fingerprint, loadIdentity, NAME_RE, type Identity } from \"../core/identity.js\";\nimport { ChangeLog } from \"../core/log.js\";\nimport { cleanDescription, Members, type Member } from \"../core/members.js\";\nimport { autoShare } from \"../core/paths.js\";\nimport { InviteDesk, type Admission, type Newcomer } from \"../p2p/invites.js\";\nimport { b64u, formatCode, unb64u } from \"../p2p/link.js\";\nimport { groupLink, Mesh } from \"../p2p/mesh.js\";\nimport { lineReader, type Event, type Message, type Request } from \"../p2p/protocol.js\";\nimport { prepareIce, resolveIce, storedIce, type IceSource } from \"../p2p/ice.js\";\nimport { unreachableAdvice } from \"../p2p/advice.js\";\nimport { nostrSignaller, type SignalFactory } from \"../p2p/signal.js\";\nimport { briefing, digest } from \"./digest.js\";\nimport { appendNews } from \"./news.js\";\nimport { InviteStore, hostDir, inviteLink, isLive, socketPath } from \"./state.js\";\n\n/** How long a write stays on this machine, where Undo removes it without trace, before it is sent. */\nexport const HOLD_MS = Number(process.env.VINE_HOLD_MS ?? 10_000);\n\nexport interface HostOptions {\n dataDir: string;\n graph: string;\n /** This machine's name in its graphs (default: the identity's). */\n user?: string;\n identity?: Identity;\n /** Exit after this many seconds with no local clients and no sharing. 0 never exits. */\n idleSeconds?: number;\n signal?: SignalFactory;\n /** STUN/TURN servers. Left out, each new link reads this machine's setting (`vine turn set`, or VINE_ICE). */\n ice?: IceSource;\n /** Tests: \"relay\" allows only links through the TURN server. */\n icePolicy?: \"all\" | \"relay\";\n /** Overrides HOLD_MS (tests). */\n holdMs?: number;\n log?(msg: string): void;\n onStop?(): void;\n}\n\nexport interface GroupInfo {\n id: string;\n name: string;\n /** base64url */\n secret: string;\n}\n\nexport class HostRunningError extends Error {}\n\n/** True if a host answers on the socket. */\nexport function hostAlive(path: string): Promise<boolean> {\n return new Promise((resolve) => {\n const s = createConnection(path);\n const done = (v: boolean) => {\n s.destroy();\n resolve(v);\n };\n s.once(\"connect\", () => done(true));\n s.once(\"error\", () => done(false));\n setTimeout(() => done(false), 1000).unref();\n });\n}\n\nconst groupFile = (dataDir: string, graph: string) => join(hostDir(dataDir, graph), \"group.json\");\n\nexport function readGroup(dataDir: string, graph: string): GroupInfo | undefined {\n try {\n const g = JSON.parse(readFileSync(groupFile(dataDir, graph), \"utf8\"));\n return typeof g.id === \"string\" && typeof g.secret === \"string\" ? g : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction writeGroup(dataDir: string, graph: string, g: GroupInfo) {\n const file = groupFile(dataDir, graph);\n const tmp = `${file}.tmp`;\n writeFileSync(tmp, JSON.stringify(g, null, 1) + \"\\n\", { mode: 0o600 });\n chmodSync(tmp, 0o600);\n renameSync(tmp, file);\n}\n\n/**\n * Moves a stopped context to a new local name: its store, its host folder\n * (group, change log, invites, peers) and the name in its group file. The name\n * is this machine's label: the id, which the other members know it by, stays.\n */\n/**\n * renameSync, tried again for a few seconds while Windows says the folder is busy: a host that\n * was just stopped can hold its files open until its process has fully exited.\n */\nfunction renameRetrying(from: string, to: string): void {\n for (let i = 0; ; i++) {\n try {\n return renameSync(from, to);\n } catch (e) {\n const code = (e as NodeJS.ErrnoException).code;\n if (i >= 30 || (code !== \"EPERM\" && code !== \"EBUSY\" && code !== \"EACCES\")) throw e;\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 100);\n }\n }\n}\n\nexport function moveContext(dataDir: string, from: string, to: string): void {\n const graphs = join(dataDir, \"graphs\");\n const hosts = join(dataDir, \"hosts\");\n if (existsSync(join(graphs, to)) || existsSync(join(hosts, to))) throw new Error(`There's already a context '${to}' on this machine.`);\n renameSync(join(graphs, from), join(graphs, to));\n try {\n if (existsSync(join(hosts, from))) renameRetrying(join(hosts, from), join(hosts, to));\n } catch (e) {\n renameSync(join(graphs, to), join(graphs, from)); // don't leave the context half renamed\n throw e;\n }\n const g = readGroup(dataDir, to);\n if (g) writeGroup(dataDir, to, { ...g, name: to });\n}\n\n/**\n * Puts a graph someone shared with us on this machine, before its host starts:\n * the group details and the change log from the welcome. Returns false if this\n * machine already has a different graph under that name.\n */\nexport function placeReplica(dataDir: string, graph: string, group: GroupInfo, changes: Change[]): boolean {\n const have = readGroup(dataDir, graph);\n if (have && have.id !== group.id) return false;\n if (!have) writeGroup(dataDir, graph, group);\n const log = new ChangeLog(hostDir(dataDir, graph));\n for (const c of changes) if (wellFormed(c) && c.graph === group.id) log.add(c);\n return true;\n}\n\n/** Order-independent digest of the changes a store holds: tells whether the store matches the log. */\nclass Digest {\n private x = Buffer.alloc(32);\n private n = 0;\n add(id: string) {\n const h = createHash(\"sha256\").update(id).digest();\n for (let i = 0; i < 32; i++) this.x[i]! ^= h[i]!;\n this.n++;\n }\n toString() {\n return `${this.n}:${this.x.toString(\"hex\")}`;\n }\n}\n\nexport class Host {\n readonly socket: string;\n readonly identity: Identity;\n private server!: Server;\n private clients = new Set<Socket>();\n private log: ChangeLog;\n members: Members;\n private group!: GroupInfo;\n private invites: InviteStore;\n private mesh?: Mesh;\n private desk?: InviteDesk;\n private idleTimer?: NodeJS.Timeout;\n private releaseTimer?: NodeJS.Timeout;\n private stopped = false;\n private digest = new Digest();\n /** Data changes not applied because their author couldn't make them (re-checked on rebuild). */\n private refused = new Map<string, string>();\n private maxDataAt = 0;\n private busy: Promise<unknown> = Promise.resolve();\n /** Admissions wait their turn, so two machines can't both take one code. (Not `busy`: admitting makes a membership change, which queues there.) */\n private admitting: Promise<unknown> = Promise.resolve();\n /** The latest sync digests (what others' changes meant for this machine's person), newest last. */\n private digests: { at: string; lines: string[] }[] = [];\n\n private constructor(\n readonly graph: Graph,\n private o: HostOptions,\n ) {\n this.socket = socketPath(o.dataDir, o.graph);\n this.identity = o.identity ?? loadIdentity(o.dataDir, o.user ?? defaultName(o.dataDir));\n this.log = new ChangeLog(hostDir(o.dataDir, o.graph));\n this.members = new Members(this.log.all());\n this.invites = new InviteStore(hostDir(o.dataDir, o.graph));\n }\n\n static async start(o: HostOptions): Promise<Host> {\n const path = socketPath(o.dataDir, o.graph);\n if (await hostAlive(path)) throw new HostRunningError(`A host for graph '${o.graph}' is already running.`);\n const graph = await Graph.open({ dataDir: o.dataDir, name: o.graph, log: o.log });\n const host = new Host(graph, o);\n await host.init();\n await host.listen();\n if (host.sharingWanted()) host.startSharing();\n host.armIdle();\n return host;\n }\n\n private get holdMs() {\n return this.o.holdMs ?? HOLD_MS;\n }\n\n private say(m: string) {\n this.o.log?.(m);\n }\n\n get me(): string {\n return this.identity.publicKey;\n }\n\n /** Runs state changes one at a time. */\n private serial<T>(fn: () => Promise<T>): Promise<T> {\n const run = this.busy.then(fn, fn);\n this.busy = run.catch(() => undefined);\n return run;\n }\n\n // ---- Start-up ---------------------------------------------------------\n\n private async init() {\n const group = readGroup(this.o.dataDir, this.o.graph);\n if (group) this.group = group;\n else if (!this.log.size) await this.createGraph();\n else throw new Error(`Graph '${this.o.graph}' has a change log but no group details (${groupFile(this.o.dataDir, this.o.graph)}).`);\n this.members = new Members(this.log.all());\n if (this.members.graphId !== this.group.id) throw new Error(`Graph '${this.o.graph}': its change log has no create change for ${this.group.id}.`);\n\n // The store must hold exactly what the log (and the held changes) say.\n const expected = new Digest();\n for (const c of this.log.all()) expected.add(c.id);\n for (const h of this.log.heldChanges()) expected.add(h.change.id);\n if ((await this.graph.getApplied()) !== expected.toString()) await this.rebuild();\n else {\n this.digest = expected;\n for (const c of this.log.all()) if (DATA_KINDS.has(c.kind)) this.maxDataAt = Math.max(this.maxDataAt, Date.parse(c.at));\n }\n await this.syncMyName();\n this.scheduleRelease();\n }\n\n /** A new graph: this machine is its creator. */\n private async createGraph() {\n const id = uuidv7();\n this.group = { id, name: this.o.graph, secret: b64u(randomBytes(32)) };\n const now = new Date().toISOString();\n this.log.add(signChange({ id, graph: id, kind: \"create\", author: this.me, seq: 1, at: now, body: { name: this.o.graph, creator_name: this.identity.name } }, this.identity));\n writeGroup(this.o.dataDir, this.o.graph, this.group);\n await this.graph.reset();\n }\n\n /** Makes, signs and logs a change at once (membership changes are never held). */\n private signNow(kind: Change[\"kind\"], body: Record<string, unknown>, at = new Date().toISOString()): Change {\n const c = signChange({ id: uuidv7(), graph: this.group.id, kind, author: this.me, seq: this.log.nextSeq(this.me), at, body }, this.identity);\n this.log.add(c);\n return c;\n }\n\n /** If this machine's name changed, tell the graph. */\n private async syncMyName() {\n const m = this.members.get(this.me);\n if (m && !m.removed_at && m.name !== this.identity.name && NAME_RE.test(this.identity.name)) await this.renameTo(this.identity.name);\n }\n\n // ---- Applying ---------------------------------------------------------\n\n private ctx(): ApplyContext {\n return {\n name: (key) => this.members.displayName(key),\n isAdmin: (key, at) => this.members.roleAt(key, at) === \"admin\",\n };\n }\n\n /** Applies a data change if its author could make it then. */\n private async applyData(c: Pick<Change, \"id\" | \"kind\" | \"author\" | \"at\" | \"body\">, own = false) {\n const needs: Role = \"contributor\";\n const allowed = own || this.members.allows(c.author, c.at, needs);\n if (!allowed) {\n this.refused.set(c.id, \"its author couldn't make this change at that time\");\n return { status: \"refused\" as const, reason: \"not allowed\" };\n }\n this.refused.delete(c.id);\n const r = await this.graph.apply(c, this.ctx());\n if (r.status === \"refused\") this.refused.set(c.id, r.reason);\n this.maxDataAt = Math.max(this.maxDataAt, Date.parse(c.at));\n return r;\n }\n\n /** Builds the store again from the log: every change, in the order every machine uses. */\n private async rebuild() {\n this.say(\"building the store from the change log\");\n await this.graph.reset();\n this.members = new Members(this.log.all());\n this.refused.clear();\n this.maxDataAt = 0;\n this.digest = new Digest();\n for (const c of [...this.log.all()].sort(compareChanges)) {\n if (DATA_KINDS.has(c.kind)) await this.applyData(c);\n this.digest.add(c.id);\n }\n for (const h of this.log.heldChanges()) {\n await this.applyData(h.change, true);\n this.digest.add(h.change.id);\n }\n await this.graph.refreshNames(this.names());\n await this.graph.setApplied(this.digest.toString());\n }\n\n private names(): Map<string, string> {\n return new Map(this.members.all().map((m) => [m.key, this.members.displayName(m.key)]));\n }\n\n /**\n * Takes changes from another member (or a welcome). Returns the ones that\n * were new here, to pass on.\n */\n receive(changes: unknown[], from?: string): Promise<Change[]> {\n const done = this.receiveNow(changes, from);\n void done.then((fresh) => this.afterSync(fresh)).catch((e) => this.say(`digest failed: ${(e as Error).message}`));\n return done;\n }\n\n /** Works out what others' new changes mean here, and tells this machine's sessions. */\n private async afterSync(fresh: Change[]) {\n const data = fresh.filter((c) => DATA_KINDS.has(c.kind) && c.author !== this.me && !this.refused.has(c.id));\n if (!data.length) return;\n const lines = await digest(data, { graph: this.graph, me: this.me, name: (k) => this.members.displayName(k), reader: this.readCaller() });\n if (!lines.length) return;\n const entry = { at: new Date().toISOString(), lines };\n this.digests.push(entry);\n this.digests = this.digests.slice(-20);\n // Kept on disk too, for the agent hook, which reads it without a host.\n try {\n appendNews(this.o.dataDir, this.o.graph, entry);\n } catch (e) {\n this.say(`couldn't keep the digest: ${(e as Error).message}`);\n }\n this.broadcastLocal({ t: \"evt\", event: \"digest\", data: { context: this.o.graph, lines, at: entry.at } });\n }\n\n private receiveNow(changes: unknown[], from?: string): Promise<Change[]> {\n return this.serial(async () => {\n const fresh: Change[] = [];\n for (const c of changes) {\n if (!wellFormed(c) || c.graph !== this.group.id) continue;\n if (this.log.add(c)) fresh.push(c);\n }\n if (!fresh.length) return fresh;\n this.say(`received ${fresh.length} new change(s)${from ? ` from ${fingerprint(from)}` : \"\"}`);\n const membership = fresh.filter((c) => MEMBER_KINDS.has(c.kind));\n const before = this.members;\n if (membership.length) this.members = new Members(this.log.all());\n // A membership change older than data already applied (or one that may make a refused change valid) means building again.\n const inThePast = membership.length > 0 && (membership.some((c) => Date.parse(c.at) <= this.maxDataAt) || this.refused.size > 0);\n if (inThePast) {\n await this.rebuild();\n } else {\n for (const c of fresh.sort(compareChanges)) {\n if (DATA_KINDS.has(c.kind)) await this.applyData(c);\n this.digest.add(c.id);\n }\n if (membership.length) await this.graph.refreshNames(this.names());\n await this.graph.setApplied(this.digest.toString());\n }\n if (membership.length) this.afterMembership(before, membership);\n const data = fresh.filter((c) => DATA_KINDS.has(c.kind));\n if (data.length) this.broadcastLocal({ t: \"evt\", event: \"changed\", data: { count: data.length, from: from ? this.members.displayName(from) : null } });\n return fresh;\n });\n }\n\n /** Tells this machine's sessions about joins, and acts on removals. */\n private afterMembership(before: Members, changes: Change[]) {\n for (const c of changes) {\n if (c.kind === \"add_member\" && typeof c.body.key === \"string\" && !before.isMember(c.body.key) && this.members.isMember(c.body.key)) {\n const m = this.members.get(c.body.key)!;\n if (m.key !== this.me) this.broadcastLocal({ t: \"evt\", event: \"joined\", data: this.personNotice(m) });\n // They may already have said hello and been ignored as a stranger: say hello back.\n this.mesh?.nudge();\n }\n if (c.kind === \"remove_member\" && typeof c.body.key === \"string\") {\n if (c.body.key === this.me) {\n this.say(\"this machine was removed from the graph\");\n this.mesh?.stop();\n this.mesh = undefined;\n this.desk?.stop();\n this.desk = undefined;\n this.broadcastLocal({ t: \"evt\", event: \"removed\", data: { by: this.members.displayName(c.author), at: c.at } });\n } else {\n this.mesh?.drop(c.body.key, [c]);\n for (const inv of this.invites.revokeForKey(c.body.key, \"removed\")) this.desk?.revoke(inv.id);\n }\n }\n if (c.kind === \"set_role\" && c.body.key === this.me) this.broadcastLocal({ t: \"evt\", event: \"role\", data: { role: this.members.get(this.me)?.role } });\n }\n }\n\n private personNotice(m: Member) {\n return {\n name: this.members.displayName(m.key),\n fingerprint: fingerprint(m.key),\n role: m.role,\n invite: m.invite ?? null,\n joined_at: m.joined_at,\n added_by: this.members.displayName(m.added_by),\n ...(m.about ?? {}),\n };\n }\n\n // ---- Writing ----------------------------------------------------------\n\n private caller(): Caller {\n const role = this.members.roleAt(this.me, new Date().toISOString());\n if (!role) throw new ToolError(this.members.get(this.me)?.removed_at ? \"You were removed from this graph: you can read your copy, but not write to it.\" : \"You are not a member of this graph.\");\n return { id: this.members.displayName(this.me), key: this.me, role };\n }\n\n private readCaller(): Caller {\n const role = this.members.roleAt(this.me, new Date().toISOString());\n return { id: this.members.displayName(this.me), key: this.me, role: role ?? \"reader\" };\n }\n\n /** A write from this machine: checked, applied here, held for HOLD_MS, then sent. */\n private write(tool: string, args: unknown) {\n return this.serial(async () => {\n const caller = this.caller();\n const now = new Date().toISOString();\n const p = await this.graph.prepare(tool, args, caller, now);\n const change: Unsigned = { id: uuidv7(), graph: this.group.id, kind: p.kind, author: this.me, at: now, body: p.body };\n const r = await this.applyData(change, true);\n if (r.status === \"refused\") throw new ToolError(`That change can't be made: ${r.reason}.`);\n const until = Date.now() + this.holdMs;\n this.log.hold(change, until);\n this.digest.add(change.id);\n await this.graph.setApplied(this.digest.toString());\n this.scheduleRelease();\n this.broadcastLocal({ t: \"evt\", event: \"changed\", data: { count: 1, from: null } });\n const result = r.status === \"applied\" ? r.result : { waiting_for: r.waiting };\n return { ...result, change: change.id, shared_at: new Date(until).toISOString() };\n });\n }\n\n /** Undo, while a write is still held: it is removed and never leaves this machine. */\n takeBack(changeId: string, newOnly = false) {\n return this.serial(async () => {\n // With newOnly, an item's id only finds the write that made it, not a held withdrawal of it.\n const held = this.log.heldChanges().find((h) => h.change.id === changeId || (h.change.body.node === changeId && !(newOnly && h.change.kind === \"withdraw\")));\n // With newOnly, an item something else already links to is left for a withdrawal, which keeps those links meaningful.\n if (newOnly && held && held.change.id !== changeId) {\n const node = held.change.body.node;\n const points = (c: { id: string; body: Record<string, unknown> }) =>\n c.id !== held.change.id &&\n c.body.node !== node &&\n [c.body.supports, c.body.contradicts, c.body.replaces, c.body.answers, c.body.about, c.body.question, c.body.from, c.body.to].flat().includes(node);\n if (this.log.heldChanges().some((h) => points(h.change)) || this.log.all().some(points))\n throw new ToolError(\"Other items already link to it, so it can't be undone without trace. Withdraw it instead (it stays in the history).\");\n }\n if (!held) {\n if (this.log.get(changeId) || this.log.all().some((c) => c.body.node === changeId))\n throw new ToolError(\"It has already been shared with the other members, so it can't be taken back without trace. Withdraw it instead (it stays in the history).\");\n throw new ToolError(`No write ${changeId} from this machine.`);\n }\n this.log.unhold(held.change.id);\n if (held.change.kind === \"claim\" || held.change.kind === \"question\" || held.change.kind === \"reply\") await this.graph.discard(held.change.id);\n else {\n await this.rebuild();\n return { taken_back: held.change.id };\n }\n // The digest is order-independent: removing the id is adding it again (XOR).\n this.digest.add(held.change.id);\n await this.graph.setApplied(this.digest.toString());\n this.broadcastLocal({ t: \"evt\", event: \"changed\", data: { count: 1, from: null } });\n return { taken_back: held.change.id, kind: held.change.kind, node: held.change.body.node ?? null };\n });\n }\n\n private scheduleRelease() {\n clearTimeout(this.releaseTimer);\n const held = this.log.heldChanges();\n if (!held.length || this.stopped) return;\n const next = Math.min(...held.map((h) => h.until));\n this.releaseTimer = setTimeout(() => void this.release(), Math.max(0, next - Date.now()));\n this.releaseTimer.unref();\n }\n\n /** Numbers, signs and sends the held writes whose time is up. */\n release(force = false) {\n return this.serial(async () => {\n const due = this.log.heldChanges().filter((h) => force || h.until <= Date.now());\n const out: Change[] = [];\n for (const h of due.sort((a, b) => compareChanges({ ...a.change, seq: 0 }, { ...b.change, seq: 0 }))) {\n this.log.unhold(h.change.id);\n const c = signChange({ ...h.change, seq: this.log.nextSeq(this.me) }, this.identity);\n this.log.add(c);\n out.push(c);\n }\n if (out.length) {\n this.say(`sent ${out.length} change(s) to ${this.mesh?.online().filter((l) => l.state === \"active\").length ?? 0} linked member(s)`);\n this.mesh?.broadcast(out);\n }\n this.scheduleRelease();\n return out;\n });\n }\n\n /** A membership change from this machine: applied and sent at once. */\n private member(kind: Change[\"kind\"], body: Record<string, unknown>) {\n return this.serial(async () => {\n const before = this.members;\n const c = this.signNow(kind, body);\n this.members = new Members(this.log.all());\n const refused = this.members.refused.find((r) => r.id === c.id);\n if (refused) {\n // Shouldn't happen (we check first), but never leave a refused change unexplained.\n this.say(`own membership change refused: ${refused.reason}`);\n }\n this.digest.add(c.id);\n await this.graph.refreshNames(this.names());\n await this.graph.setApplied(this.digest.toString());\n this.mesh?.broadcast([c]);\n this.afterMembership(before, [c]);\n return c;\n });\n }\n\n private requireAdmin() {\n if (this.members.roleAt(this.me, new Date().toISOString()) !== \"admin\") throw new ToolError(\"Only an admin of this graph can do that.\");\n }\n\n private checkRole(role: unknown): Role {\n if (!ROLES.includes(role as Role)) throw new ToolError(\"role must be reader, contributor or admin.\");\n return role as Role;\n }\n\n private memberByName(name: string): Member {\n const m = this.members.byName(name);\n if (!m) throw new ToolError(`No one named '${name}' is in this graph.`);\n return m;\n }\n\n async setRole(name: string, role: unknown) {\n this.requireAdmin();\n const r = this.checkRole(role);\n const m = this.memberByName(name);\n if (m.creator && r !== \"admin\") throw new ToolError(\"The graph's creator stays an admin.\");\n await this.member(\"set_role\", { key: m.key, role: r });\n return { name: this.members.displayName(m.key), role: r };\n }\n\n async remove(name: string) {\n this.requireAdmin();\n const m = this.memberByName(name);\n if (m.creator) throw new ToolError(\"The graph's creator can't be removed.\");\n if (m.key === this.me) throw new ToolError(\"You can't remove yourself.\");\n await this.member(\"remove_member\", { key: m.key });\n return {\n removed: m.name,\n note: \"Every member's machine stops talking to them. They keep the copy they already had: removing someone can't take back what they received.\",\n };\n }\n\n private async renameTo(name: string) {\n if (!NAME_RE.test(name)) throw new ToolError(\"Names are 1–40 letters, digits, spaces, dots, dashes or underscores.\");\n const taken = this.members.current().find((m) => m.key !== this.me && m.name === name);\n if (taken) throw new ToolError(`Someone in this graph is already called '${name}'.`);\n await this.member(\"rename\", { name });\n }\n\n async setDescription(text: unknown) {\n this.requireAdmin();\n const d = cleanDescription(text);\n if (!d) throw new ToolError(\"Describe the context in a sentence or two: what goes in it, and what doesn't.\");\n await this.member(\"describe\", { description: d });\n return { context: this.o.graph, description: d };\n }\n\n async rename(name: string) {\n const m = this.members.get(this.me);\n if (!m || m.removed_at || m.name === name) return { name };\n await this.renameTo(name);\n return { name };\n }\n\n // ---- Invites ----------------------------------------------------------\n\n share(opts: { label?: unknown; role?: unknown; expires_hours?: unknown } = {}) {\n this.requireAdmin();\n const label = opts.label === undefined || opts.label === null || opts.label === \"\" ? undefined : String(opts.label).slice(0, 60);\n const role = opts.role === undefined || opts.role === null ? undefined : this.checkRole(opts.role);\n const hours = opts.expires_hours === undefined || opts.expires_hours === null ? undefined : Number(opts.expires_hours);\n const already = Boolean(this.mesh);\n this.startSharing();\n const inv = this.desk!.invite({ label, role, hours });\n return { ...this.invites.summary(inv), code: formatCode(inviteLink(inv)), already_sharing: already };\n }\n\n revokeInvite(id: unknown) {\n if (typeof id !== \"string\" || !this.invites.get(id)) throw new ToolError(`No invite '${String(id)}'.`);\n const inv = this.invites.get(id)!;\n if (this.desk) this.desk.revoke(id);\n else this.invites.revoke(id, \"The host cancelled this join code.\");\n return { revoked: id, label: inv.label ?? null };\n }\n\n /** Someone proved a live join code: decide, and send them the graph. */\n private admit(n: Newcomer): Promise<Admission> {\n // One at a time: the code is read and tied to a machine with a membership write in between.\n const run = this.admitting.then(() => this.admitOne(n));\n this.admitting = run.catch(() => undefined);\n return run;\n }\n\n private admitOne(n: Newcomer): Promise<Admission> {\n return (async () => {\n if (this.members.roleAt(this.me, new Date().toISOString()) !== \"admin\") return { deny: \"The person who made this code can no longer invite people to this graph.\" };\n // The invite as it stands now: someone ahead in the queue may have used it or it may have been cancelled.\n const inv = this.invites.get(n.invite.id);\n if (!inv || !isLive(inv)) return { deny: \"This join code no longer works. Ask for a new one.\" };\n if (inv.bound && inv.bound.key !== n.key)\n return { deny: \"This code has already been used on another machine. If that wasn't you, tell the person who sent it: the code may have leaked. Ask for a new code of your own.\" };\n const existing = this.members.get(n.key);\n if (existing?.removed_at && inv.bound) return { deny: \"You were removed from this graph. Ask for a new code.\" };\n // A code that nobody has used is for someone new: a member using it would take it from them.\n if (existing && !existing.removed_at && !inv.bound)\n return { deny: \"You are already in this graph, and this code is for someone else. It hasn't been used up: they can still join with it.\" };\n if (!existing || existing.removed_at) {\n const taken = this.members.current().some((m) => m.name === n.name);\n if (taken) return { deny: `The name '${n.name}' is taken in this graph. Set another name (update_context with my_name) and use the code again.` };\n await this.member(\"add_member\", {\n key: n.key,\n name: n.name,\n role: inv.role ?? \"contributor\",\n invite: { id: inv.id, label: inv.label ?? null },\n about: n.about ?? {},\n });\n this.say(`${n.name} (${fingerprint(n.key)}) joined with invite ${inv.id}${inv.label ? ` (${inv.label})` : \"\"}`);\n }\n this.invites.bind(inv.id, n.key, n.name);\n await this.release(true); // send them everything, held writes too\n return {\n welcome: {\n graph: this.group,\n role: this.members.get(n.key)?.role ?? \"contributor\",\n changes: this.log.all(),\n },\n };\n })();\n }\n\n // ---- Sharing ----------------------------------------------------------\n\n private get sharingFile(): string {\n return join(hostDir(this.o.dataDir, this.o.graph), \"sharing.json\");\n }\n\n private sharingWanted(): boolean {\n try {\n return JSON.parse(readFileSync(this.sharingFile, \"utf8\")).on === true;\n } catch {\n return autoShare();\n }\n }\n\n private rememberSharing(on: boolean) {\n try {\n mkdirSync(dirname(this.sharingFile), { recursive: true, mode: 0o700 });\n writeFileSync(this.sharingFile, JSON.stringify({ on }) + \"\\n\", { mode: 0o600 });\n } catch (e) {\n this.say(`couldn't save the sharing setting: ${(e as Error).message}`);\n }\n }\n\n /** Joins the mesh (and, as an admin, answers join codes). */\n startSharing(): void {\n if (this.mesh || this.stopped) return;\n this.rememberSharing(true);\n if (!this.members.isMember(this.me)) return;\n const signal = this.o.signal ?? nostrSignaller;\n const policy = this.o.icePolicy;\n const stored = storedIce(this.o.dataDir) as Exclude<IceSource, unknown[]>;\n const ice: IceSource = this.o.ice ?? Object.assign(() => ({ ...stored(), ...(policy ? { policy } : {}) }), { prepare: stored.prepare });\n void prepareIce(ice); // fetch minted TURN credentials now, before the first link wants them\n this.mesh = new Mesh({\n group: groupLink(this.group.id, unb64u(this.group.secret)),\n graphId: this.group.id,\n identity: this.identity,\n signal,\n ice,\n isMember: (key) => this.members.isMember(key),\n myJoin: () => this.log.all().find((c) => c.kind === \"add_member\" && c.body.key === this.me),\n have: () => this.log.have(),\n missing: (theirs) => this.log.missing(theirs),\n receive: (changes, from) => this.receive(changes, from),\n onChange: () => this.broadcastLocal({ t: \"evt\", event: \"peers\", data: { online: this.mesh?.online().length ?? 0 } }),\n onUnreachable: (key) => {\n const advice = this.unreachableAdvice([key]);\n this.say(advice.message);\n // Only worth a notice when nothing gets through: otherwise changes arrive forwarded.\n if (!advice.anyLinked) this.broadcastLocal({ t: \"evt\", event: \"unreachable\", data: { name: this.members.displayName(key), message: advice.message } });\n },\n log: (m) => this.say(m),\n });\n this.desk = new InviteDesk({\n hostName: () => this.members.displayName(this.me),\n invites: this.invites,\n signal,\n ice,\n admit: (n) => this.admit(n),\n log: (m) => this.say(m),\n });\n this.armIdle();\n this.say(`sharing graph '${this.o.graph}'`);\n }\n\n /** Stops sharing, and keeps it off across restarts. */\n unshare(): { stopped: boolean } {\n this.rememberSharing(false);\n return this.closeMesh();\n }\n\n private closeMesh(): { stopped: boolean } {\n if (!this.mesh && !this.desk) return { stopped: false };\n this.mesh?.stop();\n this.desk?.stop();\n this.mesh = undefined;\n this.desk = undefined;\n this.armIdle();\n this.say(\"stopped sharing\");\n return { stopped: true };\n }\n\n // ---- Local sessions ---------------------------------------------------\n\n private listen(): Promise<void> {\n if (process.platform !== \"win32\") {\n mkdirSync(dirname(this.socket), { recursive: true, mode: 0o700 });\n if (existsSync(this.socket)) unlinkSync(this.socket);\n }\n this.server = createServer((sock) => this.onClient(sock));\n return new Promise((resolve, reject) => {\n this.server.once(\"error\", reject);\n this.server.listen(this.socket, () => {\n this.server.off(\"error\", reject);\n if (process.platform !== \"win32\") chmodSync(this.socket, 0o600);\n resolve();\n });\n });\n }\n\n private onClient(sock: Socket) {\n this.clients.add(sock);\n this.armIdle();\n const write = (m: Message) => {\n if (!sock.destroyed) sock.write(JSON.stringify(m) + \"\\n\");\n };\n sock.on(\n \"data\",\n lineReader(async (m) => {\n if (m.t !== \"req\") return;\n try {\n write({ t: \"res\", id: m.id, result: await this.handleLocal(m) });\n } catch (e) {\n write({ t: \"res\", id: m.id, error: { message: (e as Error).message } });\n }\n }),\n );\n const gone = () => {\n this.clients.delete(sock);\n this.armIdle();\n };\n sock.on(\"close\", gone);\n sock.on(\"error\", gone);\n }\n\n private broadcastLocal(e: Event) {\n const line = JSON.stringify(e) + \"\\n\";\n for (const c of this.clients) if (!c.destroyed) c.write(line);\n }\n\n async handleLocal(req: Request): Promise<unknown> {\n const p = (req.params ?? {}) as Record<string, any>;\n switch (req.method) {\n case \"describe\":\n return this.describe();\n case \"call\": {\n const spec = this.graph.tools.find((t) => t.name === p.tool);\n if (spec?.kind === \"write\") return this.write(p.tool, p.args);\n return this.graph.call(p.tool, p.args, this.readCaller());\n }\n case \"take_back\":\n return this.takeBack(String(p.id ?? \"\"), Boolean(p.new_only));\n case \"info\":\n return this.info();\n case \"snapshot\":\n return this.graph.snapshot(p);\n case \"share\":\n return this.share(p);\n case \"revoke_invite\":\n return this.revokeInvite(p.id);\n case \"rename\":\n return this.rename(String(p.name ?? \"\"));\n case \"unshare\":\n return this.unshare();\n case \"start_sharing\":\n this.startSharing();\n return { sharing: Boolean(this.mesh) };\n case \"activity\":\n return this.activity(Number(p.limit ?? 30));\n case \"describe_context\":\n return this.setDescription(p.description);\n case \"briefing\":\n return briefing(this.graph, this.readCaller());\n case \"status\":\n return this.status();\n case \"set_role\":\n return this.setRole(p.name, p.role);\n case \"remove\":\n return this.remove(p.name);\n case \"sync\":\n await this.release(true);\n return { have: this.log.have(), changes: this.log.size };\n case \"shutdown\":\n setImmediate(() => this.stop());\n return { stopping: true };\n default:\n throw new Error(`Unknown method ${req.method}`);\n }\n }\n\n describe() {\n const creator = this.members.creator();\n const caller = this.readCaller();\n const d = this.graph.describe(creator ? this.members.displayName(creator.key) : \"unknown\", caller);\n return { ...d, graph_id: this.group.id, creator: creator?.key === this.me, member: this.members.isMember(this.me), description: this.members.description };\n }\n\n async info() {\n return {\n ...(await this.graph.info()),\n graph_id: this.group.id,\n description: this.members.description,\n created_by: this.members.creator() ? this.members.displayName(this.members.creator()!.key) : null,\n you: { name: this.members.displayName(this.me), role: this.members.roleAt(this.me, new Date().toISOString()), fingerprint: fingerprint(this.me) },\n sharing: { sharing: Boolean(this.mesh), online: this.mesh?.online().filter((l) => l.state === \"active\").length ?? 0 },\n people: this.people(),\n log: { changes: this.log.size, held: this.log.heldChanges().length, refused: this.refused.size },\n };\n }\n\n /**\n * The latest changes, newest first, described for a person: what the\n * Claude Code mod's band and panel show. Held writes (still undoable) are\n * marked.\n */\n activity(limit = 30) {\n const n = Math.min(Math.max(Math.trunc(limit) || 30, 1), 200);\n const held = this.log.heldChanges().map((h) => ({ c: { ...h.change, seq: 0, sig: \"\" } as Change, held: true, until: h.until }));\n const all = [...held, ...this.log.all().map((c) => ({ c, held: false, until: 0 }))];\n all.sort((a, b) => Date.parse(b.c.at) - Date.parse(a.c.at));\n const name = (k: unknown) => (typeof k === \"string\" ? this.members.displayName(k) : \"someone\");\n const describe = (c: Change): string => {\n const b = c.body;\n switch (c.kind) {\n case \"claim\":\n return `claimed: ${String(b.text ?? \"\").slice(0, 160)}`;\n case \"question\":\n return `asked: ${String(b.text ?? \"\").slice(0, 160)}`;\n case \"reply\":\n return `replied to ${b.question}: ${String(b.text ?? \"\").slice(0, 160)}`;\n case \"link\":\n return `linked ${b.from} ${String(b.relation ?? \"\").toLowerCase()} ${b.to}`;\n case \"withdraw\":\n return `withdrew ${b.node}${b.reason ? ` (${String(b.reason).slice(0, 80)})` : \"\"}`;\n case \"create\":\n return `created the graph '${b.name}'`;\n case \"add_member\":\n return `let in ${b.name} as ${b.role}`;\n case \"set_role\":\n return `made ${name(b.key)} ${b.role}`;\n case \"remove_member\":\n return `removed ${name(b.key)}`;\n case \"rename\":\n return `is now called ${b.name}`;\n case \"describe\":\n return `described the context: ${String(b.description ?? \"\").slice(0, 120)}`;\n }\n return c.kind;\n };\n return {\n graph: this.o.graph,\n graph_id: this.group.id,\n description: this.members.description,\n digest: this.digests.slice(-3),\n created_by: this.members.creator() ? this.members.displayName(this.members.creator()!.key) : null,\n you: { name: this.members.displayName(this.me), role: this.members.roleAt(this.me, new Date().toISOString()), fingerprint: fingerprint(this.me) },\n sharing: Boolean(this.mesh),\n online: this.mesh?.online().filter((l) => l.state === \"active\").map((l) => this.members.displayName(l.key)) ?? [],\n members: this.members.current().length,\n people: this.people(),\n relays_up: Object.values(this.mesh?.relayStatus() ?? {}).filter((s) => s === \"open\").length,\n changes: this.log.size,\n recent: all.slice(0, n).map(({ c, held, until }) => ({\n id: c.id,\n kind: c.kind,\n at: c.at,\n by: name(c.author),\n mine: c.author === this.me,\n summary: describe(c),\n node: typeof c.body.node === \"string\" ? c.body.node : null,\n held,\n shared_at: held ? new Date(until).toISOString() : null,\n })),\n };\n }\n\n people() {\n return this.members.all().map((m) => ({\n name: this.members.displayName(m.key),\n fingerprint: fingerprint(m.key),\n role: m.removed_at ? null : m.role,\n you: m.key === this.me,\n creator: m.creator,\n joined_at: m.joined_at,\n removed_at: m.removed_at ?? null,\n invite: m.invite ?? null,\n agent: m.about?.agent ? `${m.about.agent}${m.about.agent_version ? ` ${m.about.agent_version}` : \"\"}` : null,\n vine: m.about?.vine ?? null,\n platform: m.about?.platform ?? null,\n online: m.key === this.me ? Boolean(this.mesh) : Boolean(this.mesh?.isOnline(m.key)),\n }));\n }\n\n /** The TURN advice for members who are found but can't be connected to. */\n private unreachableAdvice(keys: string[]): { message: string; anyLinked: boolean } {\n const anyLinked = Boolean(this.mesh?.online().some((l) => l.state === \"active\"));\n const ice = this.o.ice ? undefined : resolveIce(this.o.dataDir).summary;\n const turn = !ice ? \"custom\" : ice.source === \"env\" ? \"env\" : ice.provider === \"cloudflare\" ? \"cloudflare\" : ice.turn ? \"custom\" : \"none\";\n return { anyLinked, message: unreachableAdvice(keys.map((k) => this.members.displayName(k)), { anyLinked, turn }) };\n }\n\n status() {\n const unreachable = this.mesh?.unreachable() ?? [];\n return {\n graph: this.o.graph,\n graph_id: this.group.id,\n description: this.members.description,\n host: this.members.creator() ? this.members.displayName(this.members.creator()!.key) : null,\n you: { name: this.members.displayName(this.me), role: this.members.roleAt(this.me, new Date().toISOString()), fingerprint: fingerprint(this.me) },\n sharing: Boolean(this.mesh),\n can_invite: this.members.roleAt(this.me, new Date().toISOString()) === \"admin\",\n invites: this.invites\n .all()\n .filter((i) => !i.revoked || Date.now() - Date.parse(i.revoked.at) < 24 * 3600_000)\n .sort((a, b) => b.created_at.localeCompare(a.created_at))\n .map((i) => this.invites.summary(i)),\n links: this.mesh?.online().map((l) => ({ name: this.members.displayName(l.key), fingerprint: l.fingerprint, state: l.state, since: l.since, ...(l.route ? { route: l.route } : {}) })) ?? [],\n // Members found through the relays whose links never connect, and the advice for that.\n unreachable: unreachable.map((u) => ({ name: this.members.displayName(u.key), fingerprint: u.fingerprint, attempts: u.attempts, since: u.since })),\n ...(unreachable.length ? { advice: this.unreachableAdvice(unreachable.map((u) => u.key)).message } : {}),\n relays: this.mesh?.relayStatus() ?? {},\n // The STUN/TURN servers new links use (never a password). Absent when the host was given a fixed list.\n ...(this.o.ice ? {} : { ice: resolveIce(this.o.dataDir).summary }),\n people: this.people(),\n log: { changes: this.log.size, held: this.log.heldChanges().length, refused: this.refused.size },\n };\n }\n\n // ---- Lifetime ---------------------------------------------------------\n\n private armIdle() {\n clearTimeout(this.idleTimer);\n const secs = this.o.idleSeconds ?? 0;\n if (!secs || this.stopped || this.clients.size || this.mesh) return;\n this.idleTimer = setTimeout(() => {\n this.say(`idle for ${secs}s; stopping`);\n this.stop();\n }, secs * 1000);\n this.idleTimer.unref();\n }\n\n stop(): void {\n if (this.stopped) return;\n this.stopped = true;\n clearTimeout(this.idleTimer);\n clearTimeout(this.releaseTimer); // held writes stay held, and go out on the next start\n this.closeMesh(); // stopping the host isn't stopping sharing: it resumes on the next start\n for (const c of this.clients) c.destroy();\n this.server?.close();\n if (process.platform !== \"win32\" && existsSync(this.socket)) unlinkSync(this.socket);\n this.o.onStop?.();\n }\n}\n","// The newcomer's side of a join code: reach the machine that made the code,\n// prove the code's secret and this machine's key, and receive the graph (its\n// id, name, group secret and whole change log). After that the newcomer has\n// its own copy and meets the other members in the mesh; the code isn't needed\n// again.\n\nimport { randomBytes } from \"node:crypto\";\nimport nodeDataChannel from \"node-datachannel\";\nimport type { Change } from \"../core/changes.js\";\nimport type { Identity } from \"../core/identity.js\";\nimport { FramedChannel } from \"./channel.js\";\nimport { prepareIce, rtcConfig, type IceSource } from \"./ice.js\";\nimport { gathered } from \"./invites.js\";\nimport { b64u, proof, type Link } from \"./link.js\";\nimport type { SignalFactory } from \"./signal.js\";\n\nexport interface Welcome {\n host: string;\n graph: { id: string; name: string; secret: string };\n role: string;\n changes: Change[];\n}\n\nexport interface JoinOptions {\n signal: SignalFactory;\n ice: IceSource;\n about?: Record<string, string | undefined>;\n /** Give up if no one answers by then. */\n timeoutMs?: number;\n log?(msg: string): void;\n}\n\nexport class JoinRefused extends Error {}\n\nexport async function joinWithCode(link: Link, identity: Identity, o: JoinOptions): Promise<Welcome> {\n // Minted TURN credentials (Cloudflare) are fetched first, if due.\n await prepareIce(o.ice);\n return joinNow(link, identity, o);\n}\n\nfunction joinNow(link: Link, identity: Identity, o: JoinOptions): Promise<Welcome> {\n const me = b64u(randomBytes(6));\n const pc = new nodeDataChannel.PeerConnection(`vine-join-${me}`, rtcConfig(o.ice));\n let answered = false;\n let offerTimer: NodeJS.Timeout | undefined;\n let settled = false;\n\n return new Promise<Welcome>((resolve, reject) => {\n const signaller = o.signal(link, (m) => {\n if (m?.type !== \"answer\" || m.to !== me || answered) return;\n answered = true;\n clearInterval(offerTimer);\n try {\n pc.setRemoteDescription(m.sdp, m.sdpType);\n } catch (e) {\n fail(new Error(`Bad answer: ${(e as Error).message}`));\n }\n });\n const finish = () => {\n settled = true;\n clearInterval(offerTimer);\n clearTimeout(deadline);\n signaller.close();\n setTimeout(() => {\n try {\n pc.close();\n } catch {\n // already closed\n }\n }, 500).unref();\n };\n const fail = (e: Error) => {\n if (settled) return;\n finish();\n reject(e);\n };\n const timeoutMs = o.timeoutMs ?? 30_000;\n const deadline = setTimeout(\n () =>\n fail(\n new Error(\n answered\n ? \"Reached the person who invited you, but the connection didn't finish. Your network or theirs may block direct connections: one of you can set a TURN server (run `vine turn set`, or ask your agent to set one) and try again.\"\n : \"No answer. The person who invited you isn't online right now (their machine answers the code), or the code has expired or was cancelled. Try again later, or ask them for a new code.\",\n ),\n ),\n timeoutMs,\n );\n deadline.unref();\n pc.onStateChange((s) => {\n if (s === \"failed\") fail(new Error(\"Could not connect to the person who invited you. Your network or theirs blocks direct connections: one of you can set a TURN server (run `vine turn set`, or ask your agent to set one) and try again.\"));\n });\n\n const ch = new FramedChannel(pc.createDataChannel(\"vine-join\"));\n ch.onMessage((m: any) => {\n if (settled) return;\n if (m?.t === \"challenge\") {\n ch.send({\n t: \"auth\",\n proof: proof(link.secret, m.nonce, me),\n name: identity.name,\n key: identity.publicKey,\n sig: identity.sign(`vine-id-v1:${m.nonce}:${me}`),\n about: o.about ?? {},\n });\n } else if (m?.t === \"denied\") {\n fail(new JoinRefused(m.reason ?? \"The code was refused.\"));\n } else if (m?.t === \"welcome\") {\n if (!m.graph || typeof m.graph.id !== \"string\" || typeof m.graph.secret !== \"string\" || !Array.isArray(m.changes))\n return fail(new Error(\"The welcome was incomplete.\"));\n try {\n ch.send({ t: \"thanks\" });\n } catch {\n // they close anyway\n }\n finish();\n resolve({ host: String(m.host ?? \"\"), graph: { id: m.graph.id, name: String(m.graph.name ?? \"graph\"), secret: m.graph.secret }, role: String(m.role ?? \"\"), changes: m.changes });\n }\n });\n ch.onClose(() => fail(new Error(\"The connection closed before the graph arrived.\")));\n\n void (async () => {\n const offer = await gathered(pc);\n const msg = { type: \"offer\", from: me, sdp: offer.sdp, sdpType: offer.type };\n const send = async () => {\n if (answered || settled) return clearInterval(offerTimer);\n if (!(await signaller.send(msg))) o.log?.(\"no signalling relay accepted the offer; retrying\");\n };\n await send();\n offerTimer = setInterval(() => void send(), 3000);\n offerTimer.unref();\n })().catch((e) => fail(e as Error));\n });\n}\n","// MCP App views. All views are one React bundle, built to a single HTML file\n// (dist/apps/views.html). Each view is its own ui:// resource: the same HTML,\n// with the view's name filled in, so a host can show it next to the tool call\n// that asked for it. A tool names one resource, so open_view (which shows any\n// of three views) names ui://vine/view, and that page picks the view from the\n// tool call's input and result.\n\nimport { existsSync, readFileSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { packageRoot } from \"../core/package-root.js\";\n\n/** The MCP Apps resource type (ext-apps RESOURCE_MIME_TYPE). */\nexport const APP_MIME = \"text/html;profile=mcp-app\";\n\nexport const VIEWS = {\n view: \"Views: the contexts panel, the sharing console or the graph explorer, whichever open_view was asked for\",\n contexts: \"Contexts panel: what needs you in this chat's context, its questions, claims and people, and the chat's contexts\",\n console: \"Sharing console: join codes, everyone in the graph, who is online, and their roles\",\n explorer: \"Graph explorer: the graph as it stood at any moment, with search\",\n receipt: \"Receipt: what your agent just wrote, with Undo while it is still on this machine\",\n conflicts: \"Conflicts: items that contradict each other, side by side\",\n} as const;\nexport type ViewName = keyof typeof VIEWS;\n\nexport const viewUri = (v: ViewName) => `ui://vine/${v}`;\n\n/** The built views file, or undefined if `npm run build` hasn't made it. */\nexport function viewsFile(): string | undefined {\n const f = join(packageRoot(), \"dist\", \"apps\", \"views.html\");\n return existsSync(f) ? f : undefined;\n}\n\n// Read once, and again whenever a rebuild changes the file.\nlet cached: { mtime: number; html: string } | undefined;\nfunction viewsHtml(): string {\n const f = viewsFile();\n if (!f)\n return `<!doctype html><meta charset=\"utf-8\"><body style=\"font:14px system-ui;padding:16px\">The views aren't built. Run <code>npm run build</code> in vine-context.</body>`;\n const mtime = statSync(f).mtimeMs;\n if (cached?.mtime !== mtime) cached = { mtime, html: readFileSync(f, \"utf8\") };\n return cached.html;\n}\n\n/** The HTML for one view. */\nexport function viewHtml(view: ViewName): string {\n // The view name is one of a fixed set, so it can go into the page as is.\n return viewsHtml().replace(\"<!--VINE_VIEW-->\", `<script>window.__VINE_VIEW__=${JSON.stringify(view)}</script>`);\n}\n\nexport function registerViews(server: McpServer): void {\n for (const [view, description] of Object.entries(VIEWS) as [ViewName, string][]) {\n const uri = viewUri(view);\n server.registerResource(`view-${view}`, uri, { title: description.split(\":\")[0], description, mimeType: APP_MIME }, async () => ({\n contents: [{ uri, mimeType: APP_MIME, text: viewHtml(view) }],\n }));\n }\n}\n\n/**\n * Tool _meta that shows a view with the tool's result. With `beside`, hosts that\n * have a panel beside the conversation (ChatGPT, Codex) may also open the view\n * there by itself, calling the tool with no arguments.\n */\nexport const uiMeta = (view: ViewName, opts: { beside?: boolean } = {}) => ({\n ui: { resourceUri: viewUri(view) },\n ...(opts.beside ? { \"openai/ui\": { entrypoints: [{ type: \"thread\" }] } } : {}),\n});\n","// Which contexts each chat uses (usually one), and (optionally) which new\n// chats in a folder start with. Kept in this machine's data folder,\n// `links.json`, so nothing is written into project folders:\n//\n// {\n// \"chats\": { \"<chat id>\": { \"contexts\": [{ \"name\": \"team\", \"id\": \"0193…\" }], \"write_to\": \"team\", \"at\": \"…\" } },\n// \"folders\": { \"/Users/me/project\": { \"contexts\": [{ \"name\": \"team\", \"id\": \"0193…\" }], \"at\": \"…\" } }\n// }\n//\n// (A link written before chats could hold several, `{ name, id, at }`, reads\n// as one context.)\n//\n// A chat's id comes from its agent (Claude Code's session id), so reopening\n// the chat brings back its context. A context is found by its id first (it\n// may have been renamed on this machine), then by name.\n\nimport { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from \"node:fs\";\nimport { dirname, join, parse, resolve } from \"node:path\";\nimport { readGroup } from \"../host/host.js\";\n\nconst NAME_RE = /^[a-z0-9][a-z0-9-]{0,62}$/;\n\nexport interface Ref {\n name: string;\n id?: string;\n}\n\nexport interface Link {\n contexts: Ref[];\n write_to?: string;\n at: string;\n}\n\ntype Stored = Link | (Ref & { at: string });\n\ninterface Links {\n chats: Record<string, Stored>;\n folders: Record<string, Stored>;\n}\n\n/** A stored link, read the same whether it's from before several contexts per chat or not. */\nfunction asLink(x: Stored | undefined): Link | undefined {\n if (!x) return undefined;\n if (\"contexts\" in x && Array.isArray(x.contexts)) return x;\n const r = x as Ref & { at: string };\n return typeof r.name === \"string\" ? { contexts: [{ name: r.name, ...(r.id ? { id: r.id } : {}) }], at: r.at } : undefined;\n}\n\n/** The chat's id, as its agent gives it: VINE_CHAT, else Claude Code's session id. */\nexport function chatIdFromEnv(env = process.env): string | undefined {\n return env.VINE_CHAT || env.CLAUDE_CODE_SESSION_ID || env.CODEX_SESSION_ID || undefined;\n}\n\n/** The contexts on this machine, by local name, with their ids. */\nexport function localContexts(dataDir: string): { name: string; id?: string }[] {\n const dir = join(dataDir, \"graphs\");\n if (!existsSync(dir)) return [];\n return readdirSync(dir)\n .filter((n) => NAME_RE.test(n))\n .sort()\n .map((name) => ({ name, id: readGroup(dataDir, name)?.id }));\n}\n\nconst file = (dataDir: string) => join(dataDir, \"links.json\");\n\nfunction load(dataDir: string): Links {\n try {\n const raw = JSON.parse(readFileSync(file(dataDir), \"utf8\")) as Partial<Links>;\n return { chats: raw.chats ?? {}, folders: raw.folders ?? {} };\n } catch {\n return { chats: {}, folders: {} };\n }\n}\n\nfunction save(dataDir: string, links: Links): void {\n mkdirSync(dataDir, { recursive: true });\n const f = file(dataDir);\n const tmp = `${f}.${process.pid}.tmp`;\n writeFileSync(tmp, JSON.stringify(links, null, 1) + \"\\n\");\n renameSync(tmp, f);\n}\n\n/** The local name of a context: by id first, then by name; undefined if it isn't on this machine. */\nexport function resolveRef(dataDir: string, ref: Ref): string | undefined {\n const here = localContexts(dataDir);\n return (ref.id ? here.find((c) => c.id === ref.id) : undefined)?.name ?? here.find((c) => c.name === ref.name && (!ref.id || !c.id))?.name;\n}\n\nexport function chatLink(dataDir: string, chat: string): Link | undefined {\n return asLink(load(dataDir).chats[chat]);\n}\n\nexport function setChatLink(dataDir: string, chat: string, link: Omit<Link, \"at\"> | null): void {\n const links = load(dataDir);\n if (link) links.chats[chat] = { ...link, at: new Date().toISOString() };\n else delete links.chats[chat];\n save(dataDir, links);\n}\n\n/** The folder link nearest `start` (it or a parent), with the folder it's on. */\nexport function folderLink(dataDir: string, start: string): (Link & { folder: string }) | undefined {\n const folders = load(dataDir).folders;\n let dir = resolve(start);\n const root = parse(dir).root;\n for (;;) {\n const hit = asLink(folders[dir]);\n if (hit) return { ...hit, folder: dir };\n if (dir === root) return undefined;\n dir = dirname(dir);\n }\n}\n\nexport function setFolderLink(dataDir: string, folder: string, link: Omit<Link, \"at\"> | null): void {\n const links = load(dataDir);\n const dir = resolve(folder);\n if (link) links.folders[dir] = { ...link, at: new Date().toISOString() };\n else delete links.folders[dir];\n save(dataDir, links);\n}\n\n/** Points every chat's and folder's link at a context's new name (it keeps its id). */\nexport function renameInLinks(dataDir: string, from: string, to: string, id?: string): void {\n const links = load(dataDir);\n const is = (r: Ref) => (id && r.id ? r.id === id : r.name === from);\n const move = (all: Record<string, Stored>) => {\n for (const [k, v] of Object.entries(all)) {\n const l = asLink(v);\n if (!l || !l.contexts.some(is)) continue;\n all[k] = {\n contexts: l.contexts.map((r) => (is(r) ? { ...r, name: to } : r)),\n ...(l.write_to ? { write_to: l.write_to === from ? to : l.write_to } : {}),\n at: l.at,\n };\n }\n };\n move(links.chats);\n move(links.folders);\n save(dataDir, links);\n}\n\n/** Takes a deleted context out of every chat's and folder's link (a link left with none goes too). */\nexport function forgetContext(dataDir: string, name: string, id?: string): void {\n const links = load(dataDir);\n const is = (r: Ref) => (id && r.id ? r.id === id : r.name === name);\n const prune = (all: Record<string, Stored>) => {\n for (const [k, v] of Object.entries(all)) {\n const l = asLink(v);\n if (!l || !l.contexts.some(is)) continue;\n const contexts = l.contexts.filter((r) => !is(r));\n if (!contexts.length) delete all[k];\n else all[k] = { contexts, ...(l.write_to && contexts.some((r) => r.name === l.write_to) ? { write_to: l.write_to } : {}), at: l.at };\n }\n };\n prune(links.chats);\n prune(links.folders);\n save(dataDir, links);\n}\n","// The contexts on this machine, as a small graph to search: one Context node\n// per local context, with its name and description, a search vector and a\n// full-text index, so find_context can rank them by hybrid search (meaning\n// plus keywords) the same way a context's own search ranks claims.\n//\n// The catalogue is derived, never stored: it is built in memory from each\n// context's change log (read straight from disk, no host needed) and kept in\n// step by re-reading a log only when its file changes. So it is never synced,\n// any number of processes can hold one, and each uses its own embedder, like\n// the vectors inside a context.\n\nimport { existsSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { contentWords, makeEmbedder, type Embedder } from \"./embed.js\";\nimport { ChangeLog } from \"./log.js\";\nimport { Members } from \"./members.js\";\nimport { loadRelate, type Connection, type RelateModule } from \"./relate.js\";\nimport { toJson } from \"./values.js\";\n\n/** What the catalogue knows about one context on this machine. */\nexport interface ContextCard {\n name: string;\n /** The context's id (the same on every member's machine); null before its log has a create. */\n id: string | null;\n description: string | null;\n /** Current members, from the membership changes. */\n members: number;\n created_at: string | null;\n /** When the latest change this machine has was made. */\n last_change_at: string | null;\n}\n\nexport interface ContextHit extends ContextCard {\n score: number;\n}\n\n/** The text a context is searched by: its name as words, then its description. */\nexport function cardText(c: Pick<ContextCard, \"name\" | \"description\">): string {\n const name = c.name.replace(/-+/g, \" \");\n return c.description ? `${name}. ${c.description}` : name;\n}\n\n/** Reads a context's card from its change log on disk, without starting its host. */\nexport function readCard(dataDir: string, name: string): ContextCard {\n const dir = join(dataDir, \"hosts\", name);\n const changes = existsSync(join(dir, \"changes.jsonl\")) ? new ChangeLog(dir).all() : [];\n const members = new Members(changes);\n let last: string | null = null;\n for (const c of changes) if (!last || c.at > last) last = c.at;\n return {\n name,\n id: members.graphId ?? null,\n description: members.description,\n members: members.current().length,\n created_at: members.createdAt ?? null,\n last_change_at: last,\n };\n}\n\n/** A log's size and time, to tell cheaply whether it changed since it was read. */\nfunction stamp(dataDir: string, name: string): string {\n try {\n const s = statSync(join(dataDir, \"hosts\", name, \"changes.jsonl\"));\n return `${s.size}:${s.mtimeMs}`;\n } catch {\n return \"none\";\n }\n}\n\nexport class Catalogue {\n private stamps = new Map<string, string>();\n private queue: Promise<unknown> = Promise.resolve();\n\n private constructor(\n readonly dataDir: string,\n readonly embedder: Embedder,\n private conn: Connection,\n private R: RelateModule,\n ) {}\n\n /** A fresh in-memory catalogue for a data folder; find() fills it on first use. */\n static async open(dataDir: string, opts: { embedder?: Embedder; log?(msg: string): void } = {}): Promise<Catalogue> {\n const R = await loadRelate();\n const embedder = opts.embedder ?? makeEmbedder(undefined, opts.log);\n const conn = R.Database.open(\":memory:\").connect();\n conn.query(\"CREATE CONSTRAINT context_name_key IF NOT EXISTS FOR (n:Context) REQUIRE n.name IS UNIQUE\");\n conn.query(\n \"CREATE VECTOR INDEX context_embedding IF NOT EXISTS FOR (n:Context) ON (n.embedding) \" +\n `OPTIONS {indexConfig: {\\`vector.dimensions\\`: ${embedder.dim}, \\`vector.similarity_function\\`: 'cosine'}}`,\n );\n conn.query(\"CREATE FULLTEXT INDEX context_text IF NOT EXISTS FOR (n:Context) ON EACH [n.text]\");\n return new Catalogue(dataDir, embedder, conn, R);\n }\n\n /** Runs calls one at a time: a sync and a search never interleave. */\n private serial<T>(fn: () => T | Promise<T>): Promise<T> {\n const run = this.queue.then(fn, fn);\n this.queue = run.catch(() => undefined);\n return run;\n }\n\n /**\n * Brings the catalogue in step with the given contexts: adds new ones,\n * re-reads those whose log changed, and drops those no longer here.\n * Returns how many cards it (re)wrote.\n */\n sync(names: string[]): Promise<number> {\n return this.serial(() => {\n const want = new Set(names);\n let wrote = 0;\n for (const name of [...this.stamps.keys()])\n if (!want.has(name)) {\n this.conn.query(\"MATCH (n:Context {name: $name}) DETACH DELETE n\", { name });\n this.stamps.delete(name);\n }\n for (const name of want) {\n const s = stamp(this.dataDir, name);\n if (this.stamps.get(name) === s) continue;\n const card = readCard(this.dataDir, name);\n const text = cardText(card);\n const embedding = contentWords(text).length ? this.embedder.embed(text) : null;\n this.conn.query(\n \"MERGE (n:Context {name: $name}) SET n.id = $id, n.description = $description, n.text = $text, n.embedding = $embedding, \" +\n \"n.members = $members, n.created_at = $created_at, n.last_change_at = $last_change_at\",\n { ...card, text, embedding },\n );\n this.stamps.set(name, s);\n wrote++;\n }\n return wrote;\n });\n }\n\n /** The contexts that best match a text, by hybrid search over name and description. */\n find(query: string, limit = 10): Promise<ContextHit[]> {\n const terms = contentWords(query);\n if (!terms.length) return Promise.reject(new Error(\"'query' needs at least one letter or digit.\"));\n return this.serial(async () => {\n const r = await this.conn.queryAsync(\n \"MATCH (n:Context) SEARCH n IN (COMBINE (\" +\n \" VECTOR INDEX context_embedding FOR $vector LIMIT 100 WEIGHT 1,\" +\n \" FULLTEXT INDEX context_text FOR $terms LIMIT 100 WEIGHT 1\" +\n \" ) USING WRRF WITH CONSTANT 60 LIMIT 100) SCORE AS score \" +\n \"RETURN n.name AS name, n.id AS id, n.description AS description, n.members AS members, \" +\n \"n.created_at AS created_at, n.last_change_at AS last_change_at, round(score, 4) AS score \" +\n \"ORDER BY score DESC, name LIMIT $limit\",\n { vector: this.embedder.embed(query), terms: terms.join(\" \"), limit } as never,\n );\n return r.rows.map((row) => toJson(row, this.R) as unknown as ContextHit);\n });\n }\n}\n","// The MCP server each agent session runs. It never opens a context graph\n// itself: it is a client of this machine's hosts (started if needed). Every\n// context this machine is in, its own or one it joined, is a full local copy\n// kept in step with the other members by its host, so reads and writes always\n// work, offline too.\n//\n// A chat usually uses one context, and can use several. Which ones is\n// remembered on this machine under the chat's id (links.json in the data\n// folder), so reopening the chat brings them back. A chat with none yet starts\n// with the contexts linked to its folder, if the person linked any, or the one\n// the agent's configuration names; else the agent asks (there's no default).\n//\n// With one context, the tools simply act on it. With several, reads run on\n// all of them (each row saying which), each write goes to the context the call\n// names or else the write context, and the tools say what each context is for\n// so the agent can choose.\n//\n// The model's tools are re-registered (with tools/list_changed) when the\n// contexts or a role change.\n\nimport { spawn } from \"node:child_process\";\nimport { existsSync, renameSync, rmSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { McpServer, type RegisteredTool } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport type { Catalogue } from \"../core/catalogue.js\";\nimport { RANK } from \"../core/changes.js\";\nimport { inputShape, isoMoment, type Role, type Snapshot } from \"../core/graph.js\";\nimport { fingerprint, isGuessedName, nameSource, setName, type Identity } from \"../core/identity.js\";\nimport { claimsPack, type ToolSpec } from \"../core/pack.js\";\nimport { packageInfo } from \"../core/package-root.js\";\nimport { autoShare, defaultDataDir } from \"../core/paths.js\";\nimport { LocalHost } from \"../host/client.js\";\nimport { hostAlive, moveContext, placeReplica, readGroup } from \"../host/host.js\";\nimport { chatMarks, markSeen } from \"../host/news.js\";\nimport { socketPath } from \"../host/state.js\";\nimport { checkStoredTurn, clearTurn, readCloudflare, readTurn, saveTurn, type IceSource } from \"../p2p/ice.js\";\nimport { joinWithCode } from \"../p2p/join.js\";\nimport { parseCode } from \"../p2p/link.js\";\nimport type { GraphDescription } from \"../p2p/protocol.js\";\nimport type { SignalFactory } from \"../p2p/signal.js\";\nimport { registerViews, uiMeta } from \"./apps.js\";\nimport { chatLink, folderLink, forgetContext, localContexts, renameInLinks, resolveRef, setChatLink, setFolderLink, type Link, type Ref } from \"./links.js\";\n\ntype Content = { content: { type: \"text\"; text: string }[]; structuredContent?: Record<string, unknown>; isError?: boolean };\nconst text = (value: unknown): Content => ({\n content: [{ type: \"text\", text: typeof value === \"string\" ? value : JSON.stringify(value, null, 1) }],\n});\nconst failure = (message: string): Content => ({ ...text(message), isError: true });\n\n/** The views open_view shows. */\nconst OPEN_VIEWS = [\"contexts\", \"console\", \"explorer\"] as const;\ntype OpenView = (typeof OPEN_VIEWS)[number];\n\nconst OS: Record<string, string> = { darwin: \"macOS\", win32: \"Windows\", linux: \"Linux\" };\nconst GRAPH_RE = /^[a-z0-9][a-z0-9-]{0,62}$/;\n\ntype Description = GraphDescription & { graph_id?: string; creator?: boolean; member?: boolean; description?: string | null };\n\ninterface Attached {\n name: string;\n host: LocalHost;\n d: Description;\n}\n\ntype Origin = \"chat\" | \"folder\" | \"configured\" | \"chosen\";\n\n/** One line about a newcomer, for every agent in the graph. */\nfunction joinNotice(p: Record<string, any>, where: string): string {\n const via = p.invite?.label ? ` with the invite '${p.invite.label}'` : p.invite?.id ? ` with invite ${p.invite.id}` : \"\";\n const agent = p.agent ? `${p.agent}${p.agent_version ? ` ${p.agent_version}` : \"\"}` : \"an unknown agent\";\n const extra = [p.platform ? `on ${p.platform}` : \"\", p.vine ? `vine ${p.vine}` : \"\"].filter(Boolean).join(\", \");\n const by = p.added_by ? `, let in by ${p.added_by}` : \"\";\n return `News: ${p.name} joined ${where} as ${p.role}${via}${by}, at ${p.joined_at}. Key fingerprint ${p.fingerprint}; ${agent}${extra ? ` (${extra})` : \"\"}.`;\n}\n\n/** Opens a URL in the default browser; false where that isn't possible or is turned off. */\nfunction openInBrowser(url: string): boolean {\n if (process.env.VINE_NO_OPEN) return false;\n const cmd = process.platform === \"darwin\" ? \"open\" : process.platform === \"win32\" ? \"explorer\" : \"xdg-open\";\n try {\n spawn(cmd, [url], { stdio: \"ignore\", detached: true }).on(\"error\", () => undefined).unref();\n return true;\n } catch {\n return false;\n }\n}\n\nexport interface SessionOptions {\n /** A context named for this session (the CLI's --context or VINE_CONTEXT), used when the chat has none yet. */\n local?: () => Promise<LocalHost>;\n /** Connects to (and if needed starts) this machine's host for a context by name. */\n openLocal?: (graph: string) => Promise<LocalHost>;\n identity: () => Identity;\n signal: SignalFactory;\n /** STUN/TURN servers for joining. Read when a join starts. */\n ice: IceSource;\n /** How long join_context waits for the person who made the code to answer. */\n joinWaitMs?: number;\n /** Where contexts live. */\n dataDir?: string;\n /** The chat's id (Claude Code's session id): its contexts are remembered under it. Without one, the choice lasts this session. */\n chat?: string;\n /** The folder the chat started in: contexts linked to it (or a parent) are where a new chat starts. */\n cwd?: string;\n /** Starts (once) the localhost page that shows the views, and returns its link: open_view with `browser`. */\n browserView?: () => Promise<string>;\n log?(msg: string): void;\n}\n\nconst contextArg = z.string().regex(GRAPH_RE).optional();\n\nexport class Session {\n readonly server: McpServer;\n /** This chat's contexts, in the order added. Usually one. */\n private contexts = new Map<string, Attached>();\n /** Where writes go unless a call names another context. */\n private writeTo?: string;\n private modelTools = new Map<string, RegisteredTool>();\n /** The contexts on this machine, searchable: opened on the first find_context. */\n private catalogue?: Promise<Catalogue>;\n /** Notices not yet shown to the agent: they ride on its next tool result. */\n private news: string[] = [];\n /** Sync digests not yet shown to the agent. The agent hook may show one first: see withNews. */\n private digests: { context: string; at?: string; lines: string[] }[] = [];\n /** Where the contexts came from when the chat started. */\n private origin: Origin | null = null;\n\n constructor(private o: SessionOptions) {\n this.server = new McpServer(\n { name: \"vine-context\", version: packageInfo().version },\n {\n capabilities: { tools: { listChanged: true }, resources: {}, prompts: {} },\n // Some agents read only the start of this (Codex: the first 512 characters), so that much stands alone.\n instructions:\n \"Vine Context holds shared contexts: what a group knows, as dated claims and open questions, synced peer to peer between its members' agents. \" +\n \"Use it during ordinary work, not only when asked: when this chat reaches a decision, establishes a fact or leaves a question open that fits its context's purpose, record it (add_claim, ask_question; search first), \" +\n \"and look there (search, open_questions) before answering what the group may already know. context_info says which context this chat uses and what it is for. \" +\n \"Every member keeps a full copy, so it works offline. A chat usually uses one context; use_context switches it (or, with `mode`, adds or drops one), and the chat keeps them when reopened. \" +\n \"find_context searches this machine's contexts by what they are for: use it to pick one, and before starting a new one. \" +\n \"Call model_guide once before you first write, and follow it. \" +\n \"To invite someone, use share_context: it makes a join code for one person. To join someone else's context, call join_context with the vine1_ code they sent.\",\n },\n );\n registerViews(this.server);\n // A slash command for agents that have this server but not the plugin.\n this.server.registerPrompt(\n \"join\",\n {\n title: \"Join a shared context\",\n description: \"Join someone's shared context with the join code (vine1_…) they sent you\",\n argsSchema: { code: z.string().describe(\"The vine1_… join code\") },\n },\n ({ code }) => ({\n messages: [\n {\n role: \"user\",\n content: {\n type: \"text\",\n text:\n `Join the shared context with this join code: ${code}\\n\\n` +\n \"Call join_context with the code exactly as given. When I'm in, tell me whose context it is, what it's for, my role, that I now have my own full copy, and that everyone in it has been told I joined (with my name and key fingerprint). \" +\n \"Then give me the short briefing it returns (open questions, conflicts, latest), and call model_guide before writing. If the person who made the code isn't online, tell me to try again later. If the code was already used on another machine, expired or was cancelled, tell me to ask for a new one (and, if it was already used and not by me, to warn them it may have leaked).\",\n },\n },\n ],\n }),\n );\n this.registerSessionTools();\n this.registerAppTools();\n }\n\n private get dataDir(): string {\n return this.o.dataDir ?? defaultDataDir();\n }\n\n close(): void {\n for (const c of this.contexts.values()) c.host.close();\n void this.server.close().catch(() => undefined);\n }\n\n /** Picks up the chat's contexts: the ones it used before, else its folder's, else the configured one; else none until one is chosen. */\n async start(): Promise<void> {\n const remembered = this.o.chat ? chatLink(this.dataDir, this.o.chat) : undefined;\n const folder = !remembered && this.o.cwd ? folderLink(this.dataDir, this.o.cwd) : undefined;\n const link: Link | undefined = remembered ?? folder;\n if (link && this.o.openLocal) {\n const origin: Origin = remembered ? \"chat\" : \"folder\";\n for (const ref of link.contexts) {\n const name = resolveRef(this.dataDir, ref);\n if (!name) {\n this.news.push(\n `News: this ${origin} uses the context '${ref.name}'${ref.id ? ` (id ${ref.id})` : \"\"}, which isn't on this machine. Ask one of its members for a join code (join_context), or use another.`,\n );\n continue;\n }\n try {\n await this.attach(name, false);\n this.origin = origin;\n } catch (e) {\n this.news.push(`News: couldn't open the context '${name}': ${(e as Error).message}`);\n }\n }\n const w = link.write_to && link.contexts.find((r) => r.name === link.write_to);\n const local = w ? resolveRef(this.dataDir, w) : undefined;\n if (local && this.contexts.has(local)) this.writeTo = local;\n }\n if (!this.contexts.size && this.o.local) {\n const host = await this.o.local();\n const d = await host.request<Description>(\"describe\");\n this.add(d.graph, host, d);\n this.origin = \"configured\";\n }\n this.remember();\n this.offer();\n }\n\n // ---- The chat's contexts -----------------------------------------------\n\n /** Saves the chat's contexts under its id, so reopening the chat brings them back. */\n private remember() {\n if (!this.o.chat || !this.contexts.size) return;\n setChatLink(this.dataDir, this.o.chat, this.link());\n }\n\n private link(): Omit<Link, \"at\"> {\n return {\n contexts: [...this.contexts.values()].map((c) => ({ name: c.name, ...(c.d.graph_id ? { id: c.d.graph_id } : {}) })),\n ...(this.writeTo ? { write_to: this.writeTo } : {}),\n };\n }\n\n private add(name: string, host: LocalHost, d: Description) {\n this.contexts.get(name)?.host.close();\n this.contexts.set(name, { name, host, d });\n this.writeTo ??= name;\n // News starts from when the chat first has the context: whichever of this server and the agent hook tells it first moves the marker on.\n if (this.o.chat && !chatMarks(this.dataDir, this.o.chat).seen[name]) markSeen(this.dataDir, this.o.chat, name, new Date().toISOString());\n host.on(\"close\", () => this.o.log?.(`local host connection for '${name}' closed`));\n host.on(\"event\", (e: { event: string; data: any }) => {\n if (this.contexts.get(name)?.host !== host) return;\n const where = this.where(name);\n const tag = this.contexts.size > 1 ? ` (${name})` : \"\";\n if (e.event === \"joined\") this.news.push(joinNotice(e.data, where));\n if (e.event === \"digest\" && Array.isArray(e.data?.lines)) {\n this.digests.push({ context: name, at: typeof e.data.at === \"string\" ? e.data.at : undefined, lines: e.data.lines.map((l: string) => `News${tag}: ${l}`) });\n }\n if (e.event === \"unreachable\" && typeof e.data?.message === \"string\") this.news.push(`News${tag}: ${e.data.message}`);\n if (e.event === \"removed\") {\n this.news.push(`News: ${e.data?.by ?? \"An admin\"} removed you from ${where}. You keep your copy to read, but can't write to it any more.`);\n void this.refresh(name);\n }\n if (e.event === \"role\") {\n this.news.push(`News: your role in ${where} is now ${e.data?.role}.`);\n void this.refresh(name);\n }\n });\n }\n\n private async refresh(name: string) {\n const c = this.contexts.get(name);\n if (!c) return;\n try {\n c.d = await c.host.request<Description>(\"describe\");\n this.offer();\n } catch {\n // the host went away; the next call reconnects\n }\n }\n\n /** Adds a context on this machine (starting it if new) to the chat. */\n private async attach(name: string, offer = true): Promise<Attached> {\n const existing = this.contexts.get(name);\n if (existing && !existing.host.closed) return existing;\n if (!this.o.openLocal) throw new Error(\"This session can't open other contexts.\");\n const host = await this.o.openLocal(name);\n const d = await host.request<Description>(\"describe\");\n this.add(name, host, d);\n if (offer) {\n this.remember();\n this.offer();\n }\n return this.contexts.get(name)!;\n }\n\n private detach(name: string) {\n const c = this.contexts.get(name);\n if (!c) throw new Error(`This chat doesn't use '${name}'.`);\n c.host.close();\n this.contexts.delete(name);\n if (this.writeTo === name) this.writeTo = [...this.contexts.keys()][0];\n if (this.o.chat) setChatLink(this.dataDir, this.o.chat, this.contexts.size ? this.link() : null);\n this.offer();\n }\n\n /** The context a call acts on: the one it names (if this chat uses it), else the write context. */\n private async target(name?: string): Promise<Attached> {\n const c = name ? this.contexts.get(name) : this.writeTo ? this.contexts.get(this.writeTo) : undefined;\n if (name && !c)\n throw new Error(`This chat doesn't use '${name}': it uses ${[...this.contexts.keys()].map((n) => `'${n}'`).join(\", \") || \"no context\"}. use_context with mode 'add' adds one.`);\n if (!c) throw new Error(this.noContext());\n if (!c.host.closed) return c;\n // Renamed (by another chat): follow it to its new name, by its id.\n if (!this.localNames().includes(c.name) && c.d.graph_id) {\n const moved = localContexts(this.dataDir).find((l) => l.id === c.d.graph_id);\n if (moved) {\n const again = await this.reattach(c.name, moved.name);\n this.remember();\n this.offer();\n if (name && name !== moved.name) this.o.log?.(`'${name}' was renamed to '${moved.name}' on this machine`);\n return again;\n }\n }\n // Deleted from this machine (by another chat): reopening it would start an empty context under its name.\n if (!this.localNames().includes(c.name)) {\n this.contexts.delete(c.name);\n if (this.writeTo === c.name) this.writeTo = [...this.contexts.keys()][0];\n if (this.o.chat) setChatLink(this.dataDir, this.o.chat, this.contexts.size ? this.link() : null);\n this.offer();\n throw new Error(`The context '${c.name}' was deleted from this machine, so this chat no longer uses it.`);\n }\n c.host = await this.o.openLocal!(c.name);\n c.d = await c.host.request<Description>(\"describe\");\n return c;\n }\n\n /** What to do when the chat has no context: there's no default, so the agent asks the person. */\n private noContext(): string {\n const mine = this.localNames();\n return (\n \"This chat has no context yet, and there's no default. Ask the person which context this chat is for\" +\n (mine.length ? ` (on this machine: ${mine.map((n) => `'${n}'`).join(\", \")}), then use_context it.` : \", then start one with use_context.\") +\n \" use_context with a new name starts one (ask what it's for); join_context joins someone else's with their code. The chat keeps its context when reopened.\"\n );\n }\n\n private async request<T>(method: string, params?: unknown, name?: string): Promise<T> {\n const c = await this.target(name);\n try {\n return await c.host.request<T>(method, params);\n } catch (e) {\n if (!c.host.closed) throw e;\n // The host restarted: reconnect once.\n const again = await this.target(c.name);\n return again.host.request<T>(method, params);\n }\n }\n\n private where(name?: string): string {\n const c = this.contexts.get(name ?? this.writeTo ?? \"\");\n if (!c) return name ? `'${name}'` : \"no context\";\n if (c.d.creator) return `your context '${c.name}'`;\n return `'${c.name}' (${c.d.host}'s context${c.d.member === false ? \"; you were removed\" : `; you are a ${c.d.you.role}`})`;\n }\n\n private roleIn(c: Attached): Role {\n return c.d.member === false ? \"reader\" : c.d.you.role;\n }\n\n private get many(): boolean {\n return this.contexts.size > 1;\n }\n\n /** The chat's contexts, for tool descriptions: name, what it's for, and the write context. */\n private contextsLine(): string {\n const parts = [...this.contexts.values()].map((c) => `'${c.name}'${c.name === this.writeTo ? \" (writes go here by default)\" : \"\"}: ${c.d.description ?? \"no description yet\"}`);\n return ` This chat's contexts: ${parts.join(\"; \")}.`;\n }\n\n /**\n * What this server adds to two of the model's tools. `recent` can also give\n * the context's activity (what the panels poll), and `withdraw` first undoes\n * a write that is still only on this machine.\n */\n private modelTool(tool: Pick<ToolSpec, \"name\" | \"description\" | \"input\">): { description: string; shape: Record<string, z.ZodType> } {\n const shape = inputShape(tool.input, true);\n if (tool.name === \"recent\")\n return {\n description:\n tool.description +\n \" With `activity`, one context's latest activity instead (no `since` needed): who wrote what, what others' changes meant for you, joins and role changes, who is online.\",\n shape: {\n ...shape,\n since: z.string().meta({ format: \"date-time\" }).optional().describe(\"Changes after this time (ISO 8601). Required unless activity.\"),\n activity: z.boolean().optional(),\n snapshot: z.boolean().optional().describe(\"With activity: also its items and links\"),\n context: contextArg,\n },\n };\n if (tool.name === \"withdraw\")\n return {\n description:\n tool.description +\n \" A write still only on this machine (for a few seconds after it is made) is undone without trace instead and never reaches anyone: the result then says taken_back.\",\n shape: {\n ...shape,\n id: z.string().describe(\"The claim, question or reply; or, to undo a write just made, its `change` id\"),\n undo_only: z.boolean().optional().describe(\"Fail if it was already shared, rather than withdraw\"),\n },\n };\n return { description: tool.description, shape };\n }\n\n /** The `activity` form of `recent`. It never takes the agent's notices: the panels poll it. */\n private async activityCall(a: { limit?: number; snapshot?: boolean; context?: string }): Promise<Content> {\n try {\n if (!this.contexts.size) {\n const none = { using: \"no context\", context: null, contexts: [], your_contexts: this.localNames(), next: this.noContext() };\n return { ...text(none), structuredContent: none };\n }\n const out = await this.activity(a);\n return { ...text(out), structuredContent: out };\n } catch (e) {\n return failure((e as Error).message);\n }\n }\n\n /**\n * Undoes a write that is still only on this machine: it is removed and never\n * reaches anyone. Null when there is nothing to undo (it was shared already),\n * unless `must`, which fails instead. Without `must`, an item's own id only\n * undoes the write that made it (so withdrawing twice doesn't undo the\n * withdrawal), and only while nothing else links to it; a change id undoes\n * that change, whatever it was.\n */\n private async takeBack(id: string, context: string | undefined, must: boolean): Promise<Record<string, unknown> | null> {\n const names: (string | undefined)[] = context || !this.many ? [context] : [...this.contexts.keys()];\n let last: Error | undefined;\n for (const n of names) {\n try {\n const r = await this.request<Record<string, unknown>>(\"take_back\", { id, new_only: !must }, n);\n return { ...(this.many ? { context: n ?? this.writeTo } : {}), ...r, note: \"Undone before it was shared: it never left this machine and leaves no trace.\" };\n } catch (e) {\n last = e as Error;\n if (/already been shared/.test(last.message)) break;\n }\n }\n if (must) throw last ?? new Error(`No write ${id} from this machine.`);\n return null;\n }\n\n /** Registers the model's tools for the chat's contexts, as far as this machine's roles allow. */\n private offer(): void {\n for (const t of this.modelTools.values()) t.remove();\n this.modelTools.clear();\n const all = [...this.contexts.values()];\n if (!all.length) {\n // No context yet: the model's tools are still offered, and say what to do first.\n for (const tool of claimsPack().tools) {\n const { description, shape } = this.modelTool(tool);\n const registered = this.server.registerTool(\n tool.name,\n {\n title: tool.title,\n description: `${description} This chat has no context yet: this tells you how to choose one.`,\n inputSchema: shape,\n annotations: { readOnlyHint: tool.kind === \"read\", destructiveHint: false, idempotentHint: tool.kind === \"read\", openWorldHint: false },\n },\n async (raw: Record<string, unknown>) => (tool.name === \"recent\" && raw?.activity ? this.activityCall({}) : this.withNews(failure(this.noContext()))),\n );\n this.modelTools.set(tool.name, registered);\n }\n if (this.server.isConnected()) this.server.sendToolListChanged();\n return;\n }\n const many = this.many;\n for (const tool of all[0]!.d.tools) {\n const allowed = all.filter((c) => RANK[this.roleIn(c)] >= RANK[tool.role] && !(tool.kind === \"write\" && c.d.member === false));\n if (!allowed.length) continue;\n // With one context, nothing about routing: the tool just acts on it.\n const routing = !many\n ? \"\"\n : tool.kind === \"write\"\n ? ` Goes to the context named in \\`context\\`, else '${this.writeTo}'. Pick the context whose description fits; if none clearly does, ask the person.${this.contextsLine()}`\n : ` Without \\`context\\`, it runs on each of this chat's contexts and every result says which one it came from.${this.contextsLine()}`;\n const { description, shape } = this.modelTool(tool);\n const registered = this.server.registerTool(\n tool.name,\n {\n title: tool.title,\n description: description + routing,\n inputSchema: {\n ...shape,\n ...(many ? { context: contextArg.describe(tool.kind === \"write\" ? \"The context to write to (default: the write context)\" : \"Only this context (default: all of this chat's)\") } : {}),\n },\n annotations: { readOnlyHint: tool.kind === \"read\", destructiveHint: false, idempotentHint: tool.kind === \"read\", openWorldHint: false },\n ...(tool.view ? { _meta: uiMeta(tool.view) } : {}),\n },\n async (raw: Record<string, unknown>) => {\n const { context, ...args } = raw as Record<string, unknown> & { context?: string };\n if (tool.name === \"recent\") {\n const { activity, snapshot } = args as { activity?: boolean; snapshot?: boolean };\n if (activity) return this.activityCall({ limit: args.limit as number | undefined, snapshot, context });\n delete args.activity;\n delete args.snapshot;\n }\n try {\n await this.followRenames();\n if (tool.name === \"recent\" && !args.since) throw new Error(\"Give `since` (ISO 8601, for example 2026-03-01T09:00:00Z), or set `activity` for the context's latest activity.\");\n if (tool.name === \"withdraw\") {\n const must = Boolean(args.undo_only);\n delete args.undo_only;\n const undone = await this.takeBack(String(args.id), context, must);\n if (undone) return this.withNews(text(undone));\n }\n if (tool.kind === \"read\" && !context && this.many) return this.withNews(await this.readAll(tool.name, args));\n const c = await this.target(context);\n let result = await this.request<Record<string, unknown>>(\"call\", { tool: tool.name, args }, c.name);\n if (Array.isArray(result) && this.many) result = result.map((row) => ({ context: c.name, ...row })) as unknown as Record<string, unknown>;\n const out = text(result);\n const held =\n tool.kind === \"write\" && result && typeof result === \"object\" && result.shared_at\n ? tool.name === \"withdraw\"\n ? ` Withdrawn: it stays in the history. The withdrawal itself stays on this machine until ${result.shared_at}; until then withdraw with its \\`change\\` id undoes it.`\n : ` It stays on this machine until ${result.shared_at}; until then withdraw removes it without trace.`\n : \"\";\n out.content.push({ type: \"text\", text: `(${tool.kind === \"write\" ? \"in\" : \"from\"} ${this.where(c.name)})${held}` });\n if (tool.view)\n out.structuredContent = {\n view: tool.view,\n tool: tool.name,\n title: tool.title ?? tool.name,\n input: args,\n result,\n context: c.name,\n undo: tool.kind === \"write\" ? { held: true, withdraw: RANK[this.roleIn(c)] >= RANK.contributor } : null,\n where: this.where(c.name),\n };\n return this.withNews(out);\n } catch (e) {\n return this.withNews(failure((e as Error).message));\n }\n },\n );\n this.modelTools.set(tool.name, registered);\n }\n if (this.server.isConnected()) this.server.sendToolListChanged();\n }\n\n /** A read across the chat's contexts: lists are merged, each row saying its context; one item is looked for in each. */\n private async readAll(tool: string, args: Record<string, unknown>): Promise<Content> {\n const results: { name: string; value?: unknown; error?: string }[] = [];\n for (const c of this.contexts.values()) {\n try {\n results.push({ name: c.name, value: await this.request(\"call\", { tool, args }, c.name) });\n } catch (e) {\n results.push({ name: c.name, error: (e as Error).message });\n }\n }\n const ok = results.filter((r) => r.error === undefined);\n if (!ok.length) return failure(results.map((r) => `${r.name}: ${r.error}`).join(\"\\n\"));\n if (ok.every((r) => Array.isArray(r.value))) {\n let rows: Record<string, unknown>[] = ok.flatMap((r) => (r.value as Record<string, unknown>[]).map((row) => ({ context: r.name, ...row })));\n if (rows.some((r) => typeof r.score === \"number\")) rows = rows.sort((a, b) => Number(b.score ?? 0) - Number(a.score ?? 0));\n const out = text(rows);\n out.content.push({ type: \"text\", text: `(from ${ok.length} contexts: ${ok.map((r) => r.name).join(\", \")})` });\n return out;\n }\n // One item (history, thread): the context that has it.\n const hit = ok[0]!;\n const out = text(hit.value);\n out.content.push({ type: \"text\", text: `(from ${this.where(hit.name)})` });\n return out;\n }\n\n /** Puts any notices in front of a tool result, once. */\n private withNews(out: Content): Content {\n const lines = [...this.news.splice(0), ...this.freshDigests()];\n if (!lines.length) return out;\n out.content.unshift({ type: \"text\", text: `${lines.join(\"\\n\")}\\nTell the person this, briefly.` });\n return out;\n }\n\n /**\n * The digest lines the agent hasn't been given yet. The agent hook (`vine hook`)\n * gives the same digests beside the person's next prompt, so each one is\n * checked against the chat's marker, and the marker is moved past the ones\n * given here.\n */\n private freshDigests(): string[] {\n const waiting = this.digests.splice(0);\n if (!waiting.length) return [];\n const chat = this.o.chat;\n const seen = chat ? chatMarks(this.dataDir, chat).seen : {};\n const lines: string[] = [];\n for (const d of waiting) {\n if (d.at && seen[d.context] && d.at <= seen[d.context]!) continue;\n lines.push(...d.lines);\n if (chat && d.at) markSeen(this.dataDir, chat, d.context, d.at);\n }\n return lines;\n }\n\n /** One of this machine's contexts in full, whether or not the chat uses it: what the panel's details show. */\n private async details(name: string): Promise<Record<string, unknown>> {\n if (!this.localNames().includes(name)) throw new Error(`There's no context '${name}' on this machine.`);\n const attached = this.contexts.has(name);\n // One the chat doesn't use is opened just for this read.\n const host = attached ? (await this.target(name)).host : await this.o.openLocal!(name);\n try {\n const d = await host.request<Description>(\"describe\");\n const info = await host.request<Record<string, any>>(\"info\");\n const role: Role | null = d.member === false ? null : d.you.role;\n const people = ((info.people ?? []) as { role: Role | null; online?: boolean; you?: boolean }[]).filter((p) => p.role);\n let invites: number | null = null;\n if (role === \"admin\") {\n const s = await host.request<{ invites?: { state: string }[] }>(\"status\");\n invites = (s.invites ?? []).filter((i) => i.state === \"open\").length;\n }\n return {\n name,\n id: d.graph_id ?? null,\n description: d.description ?? null,\n role,\n yours: Boolean(d.creator),\n created_by: info.created_by ?? null,\n in_chat: attached,\n writes_here: attached && this.writeTo === name,\n sharing: Boolean(info.sharing?.sharing),\n members: people.length,\n online: people.filter((p) => p.online && !p.you).length,\n items: info.nodes ?? {},\n changes: info.log?.changes ?? 0,\n held: info.log?.held ?? 0,\n open_invites: invites,\n stored_at: join(this.dataDir, \"graphs\", name),\n };\n } finally {\n if (!attached) host.close();\n }\n }\n\n /** Deletes this machine's copy of a context: its items, change log, join codes and every link to it. */\n private async deleteLocal(name: string): Promise<Record<string, unknown>> {\n if (!this.localNames().includes(name)) throw new Error(`There's no context '${name}' on this machine.`);\n const id = readGroup(this.dataDir, name)?.id;\n if (this.contexts.has(name)) this.detach(name);\n // Out of the list first, so no chat on this machine reopens it (which would start an empty one) while its host stops.\n const store = join(this.dataDir, \"graphs\", name);\n let doomed = store;\n try {\n const aside = join(this.dataDir, \"graphs\", `.deleting-${name}-${Date.now()}`);\n renameSync(store, aside);\n doomed = aside;\n } catch {\n // Windows won't move a folder with open files: it goes once the host has stopped.\n }\n const sock = socketPath(this.dataDir, name);\n if (!(await this.stopHost(name))) {\n if (doomed !== store) renameSync(doomed, store);\n throw new Error(`The host for '${name}' didn't stop, so nothing was deleted. Try again in a moment.`);\n }\n const rm = (dir: string) => rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });\n rm(doomed);\n rm(join(this.dataDir, \"hosts\", name));\n if (process.platform !== \"win32\" && existsSync(sock)) rmSync(sock, { force: true });\n forgetContext(this.dataDir, name, id);\n return { deleted: name, id: id ?? null, contexts: this.list(), write_to: this.writeTo ?? null, your_contexts: this.localNames() };\n }\n\n /** Stops a context's host, if one runs (every chat's connection to it closes). False if it wouldn't stop. */\n private async stopHost(name: string): Promise<boolean> {\n const sock = socketPath(this.dataDir, name);\n if (!(await hostAlive(sock))) return true;\n try {\n const h = await LocalHost.connect(sock);\n await h.request(\"shutdown\").catch(() => undefined);\n h.close();\n } catch {\n // it stopped by itself\n }\n for (let i = 0; i < 40 && (await hostAlive(sock)); i++) await new Promise((r) => setTimeout(r, 150));\n if (await hostAlive(sock)) return false;\n await new Promise((r) => setTimeout(r, 200)); // let the host's process exit\n return true;\n }\n\n /** Gives a context on this machine a new local name: its store, its host's files, and every chat's and folder's link move with it. */\n private async renameLocal(from: string, to: string): Promise<Record<string, unknown>> {\n if (!this.localNames().includes(from)) throw new Error(`There's no context '${from}' on this machine.`);\n if (from === to) return { renamed: from, to, contexts: this.list() };\n if (this.localNames().includes(to)) throw new Error(`There's already a context '${to}' on this machine.`);\n const id = readGroup(this.dataDir, from)?.id;\n const attached = this.contexts.get(from);\n if (attached) attached.host.close();\n if (!(await this.stopHost(from))) throw new Error(`The host for '${from}' didn't stop, so it wasn't renamed. Try again in a moment.`);\n const sock = socketPath(this.dataDir, from);\n moveContext(this.dataDir, from, to);\n if (process.platform !== \"win32\" && existsSync(sock)) rmSync(sock, { force: true });\n renameInLinks(this.dataDir, from, to, id);\n if (attached) {\n await this.reattach(from, to);\n this.remember();\n this.offer();\n }\n return { renamed: from, to, id: id ?? null, contexts: this.list(), write_to: this.writeTo ?? null, your_contexts: this.localNames() };\n }\n\n /** Picks up contexts another chat renamed: their host stopped, and they're here under a new name with the same id. */\n private async followRenames(): Promise<void> {\n for (const c of [...this.contexts.values()]) {\n if (!c.host.closed || !c.d.graph_id || this.localNames().includes(c.name)) continue;\n const moved = localContexts(this.dataDir).find((l) => l.id === c.d.graph_id);\n if (!moved) continue;\n await this.reattach(c.name, moved.name);\n this.remember();\n this.offer();\n }\n }\n\n /** Reopens one of the chat's contexts under its new name, in its old place in the chat's list. */\n private async reattach(from: string, to: string): Promise<Attached> {\n const order = [...this.contexts.keys()].map((k) => (k === from ? to : k));\n this.contexts.delete(from);\n if (this.writeTo === from) this.writeTo = to;\n const c = await this.attach(to, false);\n const all = new Map(this.contexts);\n this.contexts.clear();\n for (const k of order) if (all.has(k)) this.contexts.set(k, all.get(k)!);\n return c;\n }\n\n /** Runs `fn` on a context's host: this chat's own connection if it uses it, else one opened just for this. */\n private async onContext<T>(name: string | undefined, fn: (host: LocalHost, name: string) => Promise<T>): Promise<T> {\n if (!name || this.contexts.has(name)) {\n const c = await this.target(name);\n try {\n return await fn(c.host, c.name);\n } catch (e) {\n if (!c.host.closed) throw e;\n // The host restarted: reconnect once.\n const again = await this.target(c.name);\n return fn(again.host, again.name);\n }\n }\n if (!this.localNames().includes(name)) throw new Error(`There's no context '${name}' on this machine.`);\n if (!this.o.openLocal) throw new Error(\"This session can't open other contexts.\");\n const host = await this.o.openLocal(name);\n try {\n return await fn(host, name);\n } finally {\n host.close();\n }\n }\n\n /** The catalogue of this machine's contexts. Relate and the embedder load on the first search, not when the chat starts. */\n private openCatalogue(): Promise<Catalogue> {\n this.catalogue ??= import(\"../core/catalogue.js\").then(({ Catalogue }) => Catalogue.open(this.dataDir, { log: this.o.log }));\n this.catalogue.catch(() => (this.catalogue = undefined)); // a failed open is tried again next time\n return this.catalogue;\n }\n\n private localNames(): string[] {\n return localContexts(this.dataDir).map((c) => c.name);\n }\n\n /** The chat's contexts, briefly. */\n private list() {\n return [...this.contexts.values()].map((c) => ({ name: c.name, description: c.d.description ?? null, role: c.d.member === false ? null : c.d.you.role, writes_here: c.name === this.writeTo }));\n }\n\n /** Whether the folder this chat started in (or a parent) starts new chats with exactly this chat's contexts. */\n private folderState(): { folder: string; linked: boolean; pinned: string[] } | null {\n if (!this.o.cwd) return null;\n const f = folderLink(this.dataDir, this.o.cwd);\n const mine = [...this.contexts.keys()].sort().join(\",\");\n const theirs = f ? f.contexts.map((r) => resolveRef(this.dataDir, r) ?? \"?\").sort().join(\",\") : \"\";\n const pinned = f ? f.contexts.map((r) => resolveRef(this.dataDir, r)).filter((n): n is string => !!n) : [];\n return { folder: f?.folder ?? this.o.cwd, linked: !!f && !!mine && mine === theirs, pinned };\n }\n\n /** One of this chat's contexts as the panels show it: recent changes, people, join codes and (with snapshot) its items. */\n private async activity(a: { limit?: number; snapshot?: boolean; context?: string }): Promise<Record<string, unknown>> {\n // A context the chat no longer uses falls back to the write context (the panel may ask for one just removed).\n const c = await this.target(a.context && this.contexts.has(a.context) ? a.context : undefined);\n const activity = await this.request<Record<string, unknown>>(\"activity\", { limit: a.limit }, c.name);\n const out: Record<string, unknown> = {\n using: this.where(c.name),\n context: c.name,\n contexts: this.list(),\n your_contexts: this.localNames(),\n folder: this.folderState(),\n ...activity,\n };\n // An admin's open join codes (who each is for, its role, when it expires): the panel lists them, to send or cancel.\n if ((activity.you as { role?: string } | undefined)?.role === \"admin\") {\n const s = await this.request<{ invites?: { state: string }[] }>(\"status\", undefined, c.name);\n out.invites = (s.invites ?? []).filter((i) => i.state === \"open\");\n }\n if (a.snapshot) out.snapshot = await this.request<Snapshot>(\"snapshot\", { limit: 300 }, c.name);\n return out;\n }\n\n private registerSessionTools(): void {\n const ro = { readOnlyHint: true, idempotentHint: true, openWorldHint: false };\n const wrap = (fn: (args: any) => Promise<unknown>) => async (args: any) => {\n try {\n await this.followRenames();\n return this.withNews(text(await fn(args)));\n } catch (e) {\n return this.withNews(failure((e as Error).message));\n }\n };\n const which = contextArg.describe(\"One of this chat's contexts (default: where writes go)\");\n const anyHere = contextArg.describe(\"Any context on this machine (default: where the chat's writes go)\");\n\n this.server.registerTool(\n \"context_info\",\n {\n title: \"Context info\",\n description:\n \"This chat's context: what it's for, your role, how much it holds, who is in it and online, and the sharing state; also the other contexts on this machine (your_contexts). \" +\n \"With `details`, a summary of any one context on this machine instead: id, who made it, members, items, whether it's syncing, where it's stored.\",\n inputSchema: {\n context: contextArg.describe(\"One of this chat's contexts (default: where writes go); with details, any on this machine\"),\n details: z.boolean().optional(),\n },\n annotations: ro,\n },\n async ({ context, details }: { context?: string; details?: boolean }) => {\n // The summary of one context: the panels read it too, so it never takes the agent's notices.\n if (details || (context && !this.contexts.has(context) && this.localNames().includes(context))) {\n try {\n const name = context ?? this.writeTo;\n if (!name) throw new Error(this.noContext());\n const out = await this.details(name);\n return { ...text(out), structuredContent: out };\n } catch (e) {\n return failure((e as Error).message);\n }\n }\n return wrap(async () => {\n if (!this.contexts.size) return { using: \"no context\", context: null, contexts: [], your_contexts: this.localNames(), next: this.noContext() };\n const c = await this.target(context);\n return {\n using: this.where(c.name),\n context: c.name,\n id: c.d.graph_id ?? null,\n description: c.d.description ?? null,\n role: c.d.member === false ? null : c.d.you.role,\n ...(await this.request<Record<string, unknown>>(\"info\", undefined, c.name)),\n contexts: this.list(),\n write_to: this.writeTo,\n your_contexts: this.localNames(),\n folder: this.folderState(),\n started_from: this.origin,\n next: this.many\n ? \"Reads search every context in this chat; put each write in the one whose description fits (the `context` argument), else it goes to write_to.\"\n : \"use_context switches this chat to another context, or with mode 'add' adds one alongside (the chat keeps them when reopened).\",\n };\n })({});\n },\n );\n\n this.server.registerTool(\n \"find_context\",\n {\n title: \"Find a context\",\n description:\n \"Search the contexts on this machine (whether or not this chat uses them) by name and what they are for. \" +\n \"Use it to find the context a topic belongs in, and before starting a new one. It searches contexts, not their contents: for claims and questions, use search.\",\n inputSchema: {\n query: z.string().min(1).max(500).describe(\"What the context would be about\"),\n limit: z.number().int().min(1).max(50).default(10).describe(\"How many contexts\"),\n },\n annotations: ro,\n },\n wrap(async ({ query, limit }: { query: string; limit?: number }) => {\n const names = this.localNames();\n if (!names.length) return { found: [], your_contexts: [], next: this.noContext() };\n const cat = await this.openCatalogue();\n await cat.sync(names);\n const found = (await cat.find(query, limit ?? 10)).map((h) => ({ ...h, in_chat: this.contexts.has(h.name), writes_here: this.writeTo === h.name }));\n return {\n found,\n searched: names.length,\n next: found.length\n ? \"Scores rank, they don't judge: read the descriptions. use_context switches this chat to one, or with mode 'add' adds it alongside; if none fits, ask the person before starting a new one.\"\n : \"No context here matches. If the person wants one for this, ask what it's for and start it with use_context and a description.\",\n };\n }),\n );\n\n this.server.registerTool(\n \"model_guide\",\n {\n title: \"Model guide\",\n description: \"How to use a context: what to record, when, and how to query it. Read it before writing.\",\n annotations: ro,\n },\n wrap(async () => {\n const first = [...this.contexts.values()][0];\n if (!first) return `${this.noContext()} Then call model_guide again.`;\n return (\n first.d.guide +\n (this.many\n ? `\\n\\n## Several contexts\\n\\nThis chat uses ${this.contexts.size} contexts.${this.contextsLine()} Reads search all of them. Put each write in the context whose description fits (the \\`context\\` argument); if none clearly fits, ask the person. Links (supports, answers, replies) stay inside one context.`\n : \"\")\n );\n }),\n );\n\n this.server.registerTool(\n \"update_context\",\n {\n title: \"Change a context's purpose or name, or your name\",\n description:\n \"Change what a context is for (`purpose`; admins only; every member's agent sees it), this machine's own name for it (`rename_to`; other members keep theirs), \" +\n \"or the name others see for you in every context on this machine (`my_name`). Ask the person for each; don't invent them.\",\n inputSchema: {\n purpose: z.string().min(1).max(500).optional().describe(\"A sentence or two: what goes in it and what doesn't\"),\n rename_to: contextArg.describe(\"Lower-case letters, digits and dashes\"),\n my_name: z.string().min(1).max(40).optional().describe(\"Letters, digits, spaces, dots, dashes or underscores\"),\n context: anyHere,\n },\n annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },\n },\n wrap(async (a: { purpose?: string; rename_to?: string; my_name?: string; context?: string }) => {\n if (!a.purpose && !a.rename_to && !a.my_name) throw new Error(\"Nothing to change: give `purpose`, `rename_to` or `my_name`.\");\n if (a.my_name && process.env.VINE_USER) throw new Error(`Your name is set by VINE_USER ('${process.env.VINE_USER}') in this agent's configuration; change it there.`);\n const out: Record<string, unknown> = {};\n if (a.my_name) {\n const n = setName(this.dataDir, a.my_name);\n for (const c of this.contexts.values()) await this.request(\"rename\", { name: n }, c.name);\n out.my_name = { name: n, fingerprint: fingerprint(this.o.identity().publicKey), note: \"This chat's contexts have it now; your other contexts take it when their hosts next start.\" };\n }\n if (a.purpose) {\n if (a.context && !this.contexts.has(a.context)) out.purpose = await this.onContext(a.context, (h) => h.request(\"describe_context\", { description: a.purpose }));\n else {\n const c = await this.target(a.context);\n out.purpose = await this.request(\"describe_context\", { description: a.purpose }, c.name);\n await this.refresh(c.name);\n }\n }\n if (a.rename_to) {\n const from = a.context ?? this.writeTo;\n if (!from) throw new Error(this.noContext());\n out.renamed = { ...(await this.renameLocal(from, a.rename_to)), note: \"Renamed on this machine. Other members keep their own name for it.\" };\n }\n return out;\n }),\n );\n\n this.server.registerTool(\n \"turn_server\",\n {\n title: \"Set or forget the TURN server\",\n description:\n \"Set (`set`) or forget (`clear`) the TURN server this machine's connections use when two members' networks block a direct connection (a join that fails with 'could not connect', or members who never link). \" +\n \"Most people need none. For `set`, ask the person for the server and their username on it; never invent them. \" +\n \"Never ask for the server's password or accept one in the chat: this tool takes none. It is read from VINE_TURN_PASSWORD where vine runs, or the person runs the result's `terminal_command` in their own terminal so vine keeps it.\",\n inputSchema: {\n action: z.enum([\"set\", \"clear\"]),\n host: z.string().min(1).max(255).optional().describe(\"For set, e.g. turn.example.org\"),\n port: z.number().int().min(1).max(65535).optional().describe(\"Default 3478 (5349 for tls)\"),\n username: z.string().min(1).max(255).optional().describe(\"For set\"),\n transport: z.enum([\"udp\", \"tcp\", \"tls\"]).optional().describe(\"Default udp\"),\n },\n annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },\n },\n wrap(async (a: { action: \"set\" | \"clear\"; host?: string; port?: number; username?: string; transport?: \"udp\" | \"tcp\" | \"tls\" }) => {\n if (a.action === \"clear\") return { removed: clearTurn(this.dataDir), note: \"Members whose networks block direct connections can no longer reach this machine directly. Links already open stay as they are.\" };\n if (!a.host || !a.username) throw new Error(\"To set a TURN server, give its `host` and the person's `username` on it.\");\n if (process.env.VINE_ICE !== undefined) throw new Error(\"VINE_ICE is set in this agent's configuration and replaces this setting; change it there, or remove it first.\");\n // A server whose password vine keeps is left alone: saving from here would drop that password.\n if (readCloudflare(this.dataDir))\n throw new Error(\n \"Cloudflare TURN is set up on this machine, and this tool would replace it. To change it, the person runs `vine turn set` in a terminal; or remove it first with turn_server and the action 'clear'.\",\n );\n const kept = readTurn(this.dataDir);\n if (kept && kept.store !== \"env\")\n throw new Error(\n `A TURN server is already set (${kept.host}:${kept.port}, user ${kept.username}) with its password kept by vine, and this tool can't replace it without losing that password. ` +\n \"To change it, the person runs `vine turn set` in a terminal; or remove it first with turn_server and the action 'clear'.\",\n );\n const t = saveTurn(this.dataDir, { host: a.host, port: a.port, username: a.username, transport: a.transport, store: \"env\" });\n const check = await checkStoredTurn(this.dataDir);\n const flag = t.transport === \"udp\" ? \"\" : ` --${t.transport}`;\n return {\n turn: `${t.host}:${t.port} (${t.transport})`,\n username: t.username,\n password_store: t.store,\n answered: check.ok,\n ...(check.ok ? {} : { problem: check.error }),\n terminal_command: `vine turn set ${t.host}:${t.port} --user ${t.username}${flag}`,\n note: check.ok\n ? \"Saved, and the server answered with the password from VINE_TURN_PASSWORD. New connections use it when a direct one isn't possible; if a join failed, try it again.\"\n : \"Saved, but the server hasn't answered yet. If VINE_TURN_PASSWORD isn't set where vine runs, give the person the terminal_command to run themselves: it asks for the password privately and keeps it. Don't ask them for the password.\",\n };\n }),\n );\n\n this.server.registerTool(\n \"share_context\",\n {\n title: \"Invite someone\",\n description:\n \"Invite one person to a context (admins only; default: the chat's context): makes a join code (vine1_…) that lets the first person to use it in, with the code's role and a full copy. \" +\n \"Your machine answers the code, so it must be online when they use it. Call it once per person, and only when the person asks to invite someone. \" +\n \"Unless they already said, ask first what the invitee may do: read and add (contributor), only read (reader), or read, add and invite (admin).\",\n inputSchema: {\n label: z.string().max(60).optional().describe(\"Who it's for, e.g. 'for Sam'\"),\n role: z.enum([\"reader\", \"contributor\", \"admin\"]).optional().describe(\"Default contributor\"),\n expires_hours: z.number().positive().max(720).optional().describe(\"How long an unused code works (default 24)\"),\n context: anyHere,\n },\n annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },\n },\n wrap(async ({ context, ...a }) => {\n if (context && !this.contexts.has(context)) return this.onContext(context, async (h, n) => this.invited(await h.request<Record<string, any>>(\"share\", a), n));\n const c = await this.target(context);\n return this.invited(await this.request<Record<string, any>>(\"share\", a, c.name), c.name);\n }),\n );\n\n this.server.registerTool(\n \"sharing\",\n {\n title: \"Sharing: status, go offline, go online\",\n description:\n \"`status`: whether a context is syncing, its invites (who each is for; open, used or expired), its members (name, key fingerprint, role, agent, online) and the links to them. \" +\n \"`off`: stop syncing it and answering its join codes until `on`; your copy keeps working and what you write is sent when you're back. Sharing is on by default.\",\n inputSchema: { action: z.enum([\"status\", \"on\", \"off\"]), context: anyHere },\n annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },\n },\n wrap(({ action, context }: { action: \"status\" | \"on\" | \"off\"; context?: string }) =>\n this.onContext(context, (h) => h.request(action === \"status\" ? \"status\" : action === \"on\" ? \"start_sharing\" : \"unshare\")),\n ),\n );\n\n this.server.registerTool(\n \"manage_member\",\n {\n title: \"Change a role, remove someone, cancel an invite\",\n description:\n \"For an admin of a context. `set_role`: change a member's role. \" +\n \"`remove`: take a member out; every machine stops syncing with them and refuses their later changes, but they keep the copy they already had. \" +\n \"`revoke_invite`: cancel a join code.\",\n inputSchema: {\n action: z.enum([\"set_role\", \"remove\", \"revoke_invite\"]),\n name: z.string().optional().describe(\"The member (set_role, remove)\"),\n role: z.enum([\"reader\", \"contributor\", \"admin\"]).optional(),\n invite: z.string().optional().describe(\"Invite id (inv_…) from sharing status\"),\n context: which,\n },\n annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },\n },\n wrap(({ action, name, role, invite, context }: { action: \"set_role\" | \"remove\" | \"revoke_invite\"; name?: string; role?: Role; invite?: string; context?: string }) => {\n if (action === \"revoke_invite\") {\n if (!invite) throw new Error(\"To cancel an invite, give its id as `invite` (inv_…, from sharing with the action 'status').\");\n return this.request(\"revoke_invite\", { id: invite }, context);\n }\n if (!name) throw new Error(\"Give the member's `name`.\");\n if (action === \"remove\") return this.request(\"remove\", { name }, context);\n if (!role) throw new Error(\"Give their new `role`: reader, contributor or admin.\");\n return this.request(\"set_role\", { name, role }, context);\n }),\n );\n\n this.server.registerTool(\n \"join_context\",\n {\n title: \"Join a shared context\",\n description:\n \"Join someone else's context with the join code they sent (vine1_…; it can be inside other text). Use it when the person pastes such a code. \" +\n \"The machine that made the code must be online. You get your own full copy, kept in step with the others, and everyone is told you joined. \" +\n \"It's added to this chat and writes go to it; the result includes a briefing. Other chats don't need the code: use_context with its name.\",\n inputSchema: { code: z.string().describe(\"The vine1_… join code, exactly as sent\") },\n annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },\n },\n wrap(async ({ code }: { code: string }) => this.join(code)),\n );\n\n const nameArg = z.string().regex(GRAPH_RE).describe(\"Lower-case letters, digits and dashes\");\n const descriptionArg = z.string().max(500).optional().describe(\"For a new context: what goes in it, in a sentence or two\");\n\n /** Starts a context of one's own if the name is new: describes it, and puts it online if sharing is on by default. It makes no join code: inviting is the person's step. */\n const created = async (name: string, isNew: boolean, description?: string) => {\n const c = this.contexts.get(name)!;\n if (isNew && description) {\n await this.request(\"describe_context\", { description }, name);\n c.d = await c.host.request<Description>(\"describe\");\n this.offer();\n }\n if (!isNew) return {};\n if (autoShare()) await this.request(\"start_sharing\", undefined, name);\n return {\n created: this.where(name),\n next:\n (c.d.description ? \"\" : \"Ask the person what this context is for and set it with update_context (`purpose`). \") +\n \"No one is invited yet and there is no join code. When the person wants someone in, ask who and what they may do (read and add, only read, or also invite), then call share_context for that one person. \" +\n \"Call model_guide before writing.\",\n };\n };\n\n this.server.registerTool(\n \"use_context\",\n {\n title: \"Choose this chat's contexts\",\n description:\n \"Make a context on this machine (context_info lists your_contexts) this chat's context, replacing the ones it had; the chat keeps it when reopened. \" +\n \"A name that isn't here yet starts a new context of your own: ask the person what it's for and pass that as `description`. \" +\n \"Mode `add` uses it alongside the chat's others (most chats need one). Mode `remove` takes it out of the chat (without a name, all of them); nothing is deleted.\",\n inputSchema: {\n name: contextArg.describe(\"Lower-case letters, digits and dashes\"),\n mode: z.enum([\"replace\", \"add\", \"remove\"]).default(\"replace\"),\n description: descriptionArg,\n write_here: z.boolean().optional().describe(\"With add: writes go to it by default\"),\n },\n annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },\n },\n wrap(async ({ name, mode, description, write_here }: { name?: string; mode?: \"replace\" | \"add\" | \"remove\"; description?: string; write_here?: boolean }) => {\n if (mode === \"remove\") {\n for (const n of name ? [name] : [...this.contexts.keys()]) this.detach(n);\n return { contexts: this.list(), write_to: this.writeTo ?? null, ...(this.contexts.size ? {} : { next: this.noContext() }) };\n }\n if (!name) throw new Error(\"Give the context's `name`.\");\n const isNew = !this.localNames().includes(name);\n await this.attach(name, false);\n if (mode === \"add\") {\n if (write_here) this.writeTo = name;\n this.remember();\n this.offer();\n return {\n contexts: this.list(),\n write_to: this.writeTo,\n next: this.many ? \"Call model_guide again: it says how to pick a context for each write.\" : \"Call model_guide before writing.\",\n ...(await created(name, isNew, description)),\n };\n }\n for (const other of [...this.contexts.keys()]) if (other !== name) (this.contexts.get(other)!.host.close(), this.contexts.delete(other));\n this.writeTo = name;\n this.origin = \"chosen\";\n this.remember();\n this.offer();\n const c = this.contexts.get(name)!;\n return { using: this.where(name), description: c.d.description ?? null, next: \"Call model_guide before writing to it.\", ...(await created(name, isNew, description)) };\n }),\n );\n\n this.server.registerTool(\n \"delete_context\",\n {\n title: \"Delete a context from this machine\",\n description:\n \"Permanently delete this machine's copy of a context: its claims, questions and replies, its change log, its join codes, and every chat's and folder's link to it. It can't be undone. \" +\n \"Other members keep their copies; with none, it is gone for good. \" +\n \"Only when the person asked to delete it: first tell them what it removes and ask them to confirm by name, then pass that name as `confirm`. To only stop using it in this chat, use_context with mode `remove`.\",\n inputSchema: { name: nameArg, confirm: z.string().describe(\"The context's name again, as the person confirmed it\") },\n annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },\n },\n wrap(async ({ name, confirm }: { name: string; confirm: string }) => {\n if (confirm !== name) throw new Error(`Not deleted: to confirm, pass the context's name ('${name}') as \\`confirm\\`, exactly.`);\n const r = await this.deleteLocal(name);\n return { ...r, note: \"Deleted from this machine. Other members keep their copies.\", ...(this.contexts.size ? {} : { next: this.noContext() }) };\n }),\n );\n\n this.server.registerTool(\n \"link_folder\",\n {\n title: \"Start this folder's chats here\",\n description:\n \"Make new chats started in this chat's folder (or below it) start with this chat's contexts; with `off`, stop that. \" +\n \"With `name`, pin (or with `off`, unpin) just that context, leaving the folder's others as they are. Kept on this machine, not in the folder. Ask the person first.\",\n inputSchema: {\n off: z.boolean().optional(),\n name: contextArg,\n },\n annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },\n },\n wrap(async ({ off, name }: { off?: boolean; name?: string }) => {\n if (!this.o.cwd) throw new Error(\"This session doesn't know which folder it started in.\");\n if (name) {\n if (!this.localNames().includes(name)) throw new Error(`There's no context '${name}' on this machine.`);\n // The folder's own link, or the one it gets from a parent folder.\n const f = folderLink(this.dataDir, this.o.cwd);\n const folder = f?.folder ?? this.o.cwd;\n const id = readGroup(this.dataDir, name)?.id;\n const rest: Ref[] = (f?.contexts ?? []).filter((r) => resolveRef(this.dataDir, r) !== name);\n const contexts: Ref[] = off ? rest : [...rest, { name, ...(id ? { id } : {}) }];\n const write_to = f?.write_to && contexts.some((r) => r.name === f.write_to) ? { write_to: f.write_to } : {};\n setFolderLink(this.dataDir, folder, contexts.length ? { contexts, ...write_to } : null);\n return {\n folder,\n pinned: contexts.map((r) => r.name),\n note: off ? `New chats in this folder no longer start with '${name}'.` : `New chats started in this folder, or below it, start with '${name}'.`,\n };\n }\n if (off) {\n const f = folderLink(this.dataDir, this.o.cwd);\n if (f) setFolderLink(this.dataDir, f.folder, null);\n return { folder: f?.folder ?? this.o.cwd, linked: null };\n }\n if (!this.contexts.size) throw new Error(this.noContext());\n setFolderLink(this.dataDir, this.o.cwd, this.link());\n return { folder: this.o.cwd, linked: [...this.contexts.keys()], note: \"New chats started in this folder, or below it, start with these contexts.\" };\n }),\n );\n\n }\n\n /** What the console shows. */\n private async consoleState(context?: string): Promise<Record<string, unknown>> {\n const c = await this.target(context);\n const status = await this.request<Record<string, any>>(\"status\", undefined, c.name);\n return {\n using: this.where(c.name),\n ...status,\n you: { ...status.you, name_from: nameSource(this.dataDir) },\n graphs: this.localNames(),\n };\n }\n\n private registerAppTools(): void {\n const ro = { readOnlyHint: true, idempotentHint: true, openWorldHint: false };\n const run = (fn: (args: any) => Promise<Content>) => async (args: any) => {\n try {\n return this.withNews(await fn(args));\n } catch (e) {\n return this.withNews(failure((e as Error).message));\n }\n };\n const both = (summary: unknown, structured: Record<string, unknown>): Content => ({ ...text(summary), structuredContent: structured });\n const which = contextArg.describe(\"One of this chat's contexts (default: where writes go)\");\n\n this.server.registerTool(\n \"open_view\",\n {\n title: \"Show a view of a context\",\n description:\n \"Show the person a view of this chat's context: `contexts` (the panel: what needs them, questions and threads, claims, people and join codes, and the chat's contexts), \" +\n \"`console` (sharing: members, key fingerprints, roles, who is online, join codes) or `explorer` (a picture of its items and links, as it stood `at` a moment). \" +\n \"For the person to look at and steer from; to read the context yourself, use search and the other read tools.\" +\n (this.o.browserView ? \" If this agent can't show views, pass `browser` for a link to them in a browser tab.\" : \"\"),\n inputSchema: {\n view: z.enum(OPEN_VIEWS).default(\"contexts\"),\n at: z.string().meta({ format: \"date-time\" }).optional().describe(\"Explorer: ISO 8601, default now\"),\n limit: z.number().int().min(1).max(1000).optional().describe(\"Explorer: most recent items (default 200)\"),\n ...(this.o.browserView ? { browser: z.boolean().optional() } : {}),\n context: which,\n },\n annotations: ro,\n _meta: uiMeta(\"view\", { beside: true }),\n },\n run(async ({ view = \"contexts\", at, limit, browser, context }: { view?: OpenView; at?: string; limit?: number; browser?: boolean; context?: string }) => {\n if (browser && this.o.browserView) {\n const url = await this.o.browserView();\n const opened = openInBrowser(url);\n const out = {\n url,\n opened,\n note: opened\n ? \"Opened in the default browser. If no tab appeared, open the link on this machine. Don't share it: it acts as you. It works only on this machine and while this session runs.\"\n : \"Open it in a browser on this machine. Don't share it: it acts as you. It works only on this machine and while this session runs.\",\n };\n return both(out, { view: \"browser\", ...out });\n }\n if (view === \"console\") {\n const state = await this.consoleState(context);\n return both(state, { view, ...state });\n }\n if (view === \"explorer\") {\n if (at !== undefined) {\n const ok = isoMoment().safeParse(at);\n if (!ok.success) throw new Error(`Invalid input:\\n- at: ${ok.error.issues[0]?.message}`);\n }\n const c = await this.target(context);\n const snap = await this.request<Snapshot>(\"snapshot\", { ...(at ? { at } : {}), limit: limit ?? 200 }, c.name);\n const counts: Record<string, number> = {};\n for (const n of snap.nodes) counts[n.label] = (counts[n.label] ?? 0) + 1;\n return both(\n {\n showing: this.where(c.name),\n at: snap.at,\n nodes: counts,\n links: snap.edges.length,\n truncated: snap.truncated,\n note: \"The explorer shows the picture to the person; this summary is all you get here.\",\n },\n { view, ...snap, where: this.where(c.name) } as unknown as Record<string, unknown>,\n );\n }\n if (!this.contexts.size) {\n const none = { using: \"no context\", context: null, contexts: [], your_contexts: this.localNames(), next: this.noContext() };\n return both(none, { view, ...none });\n }\n const state = await this.activity({ limit: 40, snapshot: true, context });\n const snap = state.snapshot as Snapshot;\n // The agent gets a line about what the person now sees, not the whole context.\n return both({ showing: state.using, context: state.context, items: snap.nodes.length, note: \"The person is looking at the contexts panel.\" }, { view, ...state });\n }),\n );\n }\n\n /** What share_context says about a new invite. */\n /** What to tell the person about the name others see, when they didn't choose it themselves. */\n private nameNote(): { your_name?: string } {\n const source = nameSource(this.dataDir);\n const { name } = this.o.identity();\n if (source === \"VINE_USER\" || source === \"chosen\") return {};\n if (isGuessedName(source))\n return {\n your_name: `Others see this person as '${name}', which is ${source === \"login\" ? \"only their login name\" : \"a made-up name\"}. If this chat hasn't asked yet, ask what name they want and save it with update_context (my_name); if they'd rather not say, '${name}' stays.`,\n };\n return {\n your_name: `Others see this person as '${name}' (${source === \"git\" ? \"from git's user.name\" : \"the full name on their computer account\"}). If this chat hasn't told them yet, do, and offer update_context (my_name) if they want another.`,\n };\n }\n\n private invited(r: Record<string, any>, context: string) {\n const identity = this.o.identity();\n return {\n context,\n code: r.code,\n send: `Join my context graph: /vine-context:join ${r.code}`,\n invite: { id: r.id, label: r.label, role: r.role, expires_at: r.expires_at },\n shared_as: { name: identity.name, fingerprint: fingerprint(identity.publicKey) },\n ...this.nameNote(),\n next:\n \"Give the person the 'send' line to pass on privately (not in a public channel). Agents without the plugin command can be told: join the context with this code. \" +\n \"This machine answers the code, so it must be online when they use it. Whoever uses it first is let in at once and gets a full copy, and everyone in the context is told who joined (name, key fingerprint, agent). \" +\n \"Each code is for one person: call share_context again for the next. manage_member takes anyone out.\",\n };\n }\n\n /** Joins a context with a code: gets its whole log from the machine that made the code, keeps a copy here, adds it to this chat (writes go to it) and briefs the agent. */\n private async join(codeText: string): Promise<unknown> {\n const link = parseCode(codeText);\n const identity = this.o.identity();\n const client = this.server.server.getClientVersion();\n const about = {\n agent: client?.name,\n agent_version: client?.version,\n vine: packageInfo().version,\n platform: `${OS[process.platform] ?? process.platform} ${process.arch}`,\n };\n const welcome = await joinWithCode(link, identity, { signal: this.o.signal, ice: this.o.ice, about, timeoutMs: this.o.joinWaitMs ?? 30_000, log: this.o.log });\n\n // Put it on this machine: under its own name if that's free, else name-2, name-3 …\n const base = GRAPH_RE.test(welcome.graph.name) ? welcome.graph.name : \"shared\";\n const here = this.localNames();\n let name: string | undefined;\n for (let i = 1; i < 100 && !name; i++) {\n const candidate = i === 1 ? base : `${base}-${i}`.slice(0, 63);\n const group = readGroup(this.dataDir, candidate);\n if (group?.id === welcome.graph.id) name = candidate; // already here: its host syncs it\n else if (!group && !here.includes(candidate)) {\n if (placeReplica(this.dataDir, candidate, welcome.graph, welcome.changes)) name = candidate;\n }\n }\n if (!name) throw new Error(\"Couldn't find a free name for this context on this machine.\");\n const c = await this.attach(name, false);\n this.writeTo = name;\n this.remember();\n this.offer();\n const brief = await this.request<Record<string, unknown>>(\"briefing\", undefined, name).catch(() => null);\n return {\n joined: `${welcome.host || c.d.host}'s context '${welcome.graph.name}'`,\n here_as: name,\n description: c.d.description ?? null,\n role: c.d.you.role,\n as: c.d.you.id,\n your_fingerprint: fingerprint(identity.publicKey),\n ...this.nameNote(),\n contexts: this.list(),\n copy: `You have your own full copy (${welcome.changes.length} changes), kept in step with the other members whenever you're both online. It works offline too.`,\n briefing: brief,\n told: \"Everyone in this context has been told you joined, with your name, key fingerprint and agent.\",\n next: `Tell the person what it's for and give them the briefing in a few lines. Call model_guide before writing. It's in this chat now (and stays when the chat is reopened); in other chats, use_context '${name}' (no code needed).`,\n };\n }\n}\n","// `vine ui`: the MCP App views in a browser tab, for agents that can't show\n// MCP Apps themselves. It serves a small host page and an MCP endpoint\n// (Streamable HTTP) on 127.0.0.1 only. Each browser tab gets its own MCP\n// session, a client of this machine's graph host like any agent session.\n//\n// The endpoint acts as you (the host's admin), so it is locked to whoever\n// holds the random token in the URL: it travels in the URL fragment and an\n// Authorization header, never in a query string. Host and Origin are checked\n// too, so a web page can't reach it through DNS rebinding.\n\nimport { randomBytes, randomUUID, timingSafeEqual } from \"node:crypto\";\nimport { readFileSync } from \"node:fs\";\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from \"node:http\";\nimport { join } from \"node:path\";\nimport { StreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/streamableHttp.js\";\nimport { isInitializeRequest } from \"@modelcontextprotocol/sdk/types.js\";\nimport { packageRoot } from \"../core/package-root.js\";\nimport type { Session } from \"../mcp/server.js\";\n\nexport interface UiServer {\n url: string;\n port: number;\n close(): Promise<void>;\n}\n\n// Inline scripts and styles only; the views' iframes (srcdoc) inherit this.\nconst CSP = [\n \"default-src 'none'\",\n \"script-src 'unsafe-inline'\",\n \"style-src 'unsafe-inline'\",\n \"img-src data:\",\n \"font-src data:\",\n \"connect-src 'self'\",\n \"frame-src 'self'\",\n \"base-uri 'none'\",\n \"form-action 'none'\",\n \"frame-ancestors 'none'\",\n].join(\"; \");\n\nfunction shellHtml(): string {\n try {\n return readFileSync(join(packageRoot(), \"dist\", \"apps\", \"shell.html\"), \"utf8\");\n } catch {\n return \"<!doctype html><meta charset=utf-8><p>The views aren't built. Run <code>npm run build</code> in vine-context.</p>\";\n }\n}\n\nconst MAX_BODY = 4 * 1024 * 1024;\nfunction readJson(req: IncomingMessage): Promise<unknown> {\n return new Promise((resolve, reject) => {\n let size = 0;\n const chunks: Buffer[] = [];\n req.on(\"data\", (c: Buffer) => {\n size += c.length;\n if (size > MAX_BODY) {\n reject(new Error(\"too large\"));\n req.destroy();\n } else chunks.push(c);\n });\n req.on(\"end\", () => {\n try {\n resolve(chunks.length ? JSON.parse(Buffer.concat(chunks).toString(\"utf8\")) : undefined);\n } catch (e) {\n reject(e);\n }\n });\n req.on(\"error\", reject);\n });\n}\n\nexport async function startUi(o: { session: () => Session; port?: number; log?(m: string): void }): Promise<UiServer> {\n const token = randomBytes(24).toString(\"base64url\");\n const expected = Buffer.from(`Bearer ${token}`);\n const sessions = new Map<string, { transport: StreamableHTTPServerTransport; session: Session }>();\n let port = 0;\n\n const authorized = (req: IncomingMessage) => {\n const got = Buffer.from(String(req.headers.authorization ?? \"\"));\n return got.length === expected.length && timingSafeEqual(got, expected);\n };\n const sameHost = (req: IncomingMessage) => req.headers.host === `127.0.0.1:${port}` || req.headers.host === `localhost:${port}`;\n const sameOrigin = (req: IncomingMessage) => {\n const origin = req.headers.origin;\n return !origin || origin === `http://127.0.0.1:${port}` || origin === `http://localhost:${port}`;\n };\n const send = (res: ServerResponse, status: number, body: string, type = \"text/plain; charset=utf-8\") => {\n res.writeHead(status, { \"content-type\": type, \"x-content-type-options\": \"nosniff\", \"cache-control\": \"no-store\" }).end(body);\n };\n\n const server: Server = createServer(async (req, res) => {\n try {\n if (!sameHost(req)) return send(res, 421, \"Wrong host.\");\n const path = new URL(req.url ?? \"/\", \"http://x\").pathname;\n if (path === \"/\" && req.method === \"GET\") {\n res.writeHead(200, {\n \"content-type\": \"text/html; charset=utf-8\",\n \"content-security-policy\": CSP,\n \"referrer-policy\": \"no-referrer\",\n \"x-content-type-options\": \"nosniff\",\n \"cache-control\": \"no-store\",\n });\n return res.end(shellHtml());\n }\n if (path !== \"/mcp\") return send(res, 404, \"Not found.\");\n if (!sameOrigin(req)) return send(res, 403, \"Wrong origin.\");\n if (!authorized(req)) return send(res, 401, \"Missing or wrong token.\");\n\n const id = req.headers[\"mcp-session-id\"];\n const existing = typeof id === \"string\" ? sessions.get(id) : undefined;\n if (req.method === \"POST\") {\n const body = await readJson(req);\n if (existing) return existing.transport.handleRequest(req, res, body);\n if (!isInitializeRequest(body)) return send(res, 400, \"No session: initialize first.\");\n const session = o.session();\n const transport: StreamableHTTPServerTransport = new StreamableHTTPServerTransport({\n sessionIdGenerator: () => randomUUID(),\n onsessioninitialized: (sid) => {\n sessions.set(sid, { transport, session });\n },\n });\n transport.onclose = () => {\n if (transport.sessionId) sessions.delete(transport.sessionId);\n session.close();\n };\n await session.start();\n await session.server.connect(transport);\n return transport.handleRequest(req, res, body);\n }\n if (!existing) return send(res, 404, \"No such session.\");\n return existing.transport.handleRequest(req, res);\n } catch (e) {\n o.log?.(`ui: ${(e as Error).message}`);\n if (!res.headersSent) send(res, 500, \"Something went wrong; see the vine log.\");\n }\n });\n\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(o.port ?? 0, \"127.0.0.1\", () => resolve());\n });\n port = (server.address() as { port: number }).port;\n return {\n port,\n url: `http://127.0.0.1:${port}/#token=${token}`,\n close: async () => {\n for (const { transport } of sessions.values()) await transport.close();\n await new Promise<void>((r) => server.close(() => r()));\n },\n };\n}\n","// The example story, in one place: three people (alice, bob, carol) planning\n// the office Christmas party, 17 to 19 Nov 2026. A contradiction appears and\n// is settled, a mistaken claim is withdrawn, two questions are answered, and\n// a third stays open. Three replies show a question's thread: messages that\n// are not answers.\n//\n// Two things play it: `scripts/make-examples.ts` writes it, backdated, into\n// the example store that ships with the package, and `vine demo` runs it live\n// through three replicating hosts. The project site tells the same story.\n\nexport interface Step {\n who: \"alice\" | \"bob\" | \"carol\";\n /** When it happened in the story: day of November 2026 and time, UTC. */\n day: number;\n time: string;\n tool: string;\n /** Tool arguments. A string \"@name\" (alone or in a list) is the id of the step that was saved as `name`. */\n args: Record<string, unknown>;\n /** Saves this step's result id under this name, for later steps. */\n as?: string;\n /** What to tell a watcher, in plain words. */\n note: string;\n}\n\nexport const GRAPH_NAME = \"party\";\nexport const GRAPH_DESCRIPTION = \"The office Christmas party 2026: who is coming, where it is, what it costs, and what we still have to decide\";\n\nexport const STEPS: Step[] = [\n {\n who: \"alice\", day: 17, time: \"09:10\", tool: \"add_claim\", as: \"headcount\",\n args: { text: \"48 people are coming to the Christmas party, from the RSVP sheet that closed on 14 Nov\", source: \"RSVP sheet (closed 14 Nov)\", about_from: \"2026-11-14\", about_to: \"2026-11-14\" },\n note: \"records that 48 people are coming, from the RSVP sheet\",\n },\n { who: \"alice\", day: 17, time: \"09:15\", tool: \"ask_question\", as: \"whichVenue\", args: { text: \"Which venue can take all of us on a Friday in December?\", about: [\"@headcount\"] }, note: \"asks which venue can take all of them on a Friday\" },\n {\n who: \"bob\", day: 17, time: \"10:40\", tool: \"reply\",\n args: { question: \"@whichVenue\", text: \"Riverside said yes on the phone. I'll get it in writing before we book.\" },\n note: \"replies in the thread: Riverside said yes on the phone, and he'll get it in writing. A reply is a message to the thread, not an answer, so the question stays open\",\n },\n {\n who: \"bob\", day: 17, time: \"11:30\", tool: \"add_claim\", as: \"riverside\",\n args: { text: \"The Riverside Room can take the whole party on Friday 12 Dec\", source: \"phone call with the Riverside Room\", about_from: \"2026-12-12\", about_to: \"2026-12-12\" },\n note: \"claims the Riverside Room can take the whole party on Friday 12 Dec\",\n },\n {\n who: \"carol\", day: 17, time: \"14:05\", tool: \"add_claim\",\n args: { text: \"The Riverside Room's licence caps it at 40 seated, eight short of our 48\", source: \"Riverside Room premises licence, on the council's register\", supports: [\"@headcount\"], contradicts: [\"@riverside\"] },\n note: \"finds the Riverside Room's licence caps it at 40 seated. That contradicts bob, and the graph now holds a conflict\",\n },\n { who: \"bob\", day: 17, time: \"15:20\", tool: \"add_claim\", as: \"budget\", args: { text: \"The budget is £2,400, which is £50 a head for 48\", source: \"finance: events budget 2026\" }, note: \"records the budget: £2,400, which is £50 a head\" },\n { who: \"alice\", day: 17, time: \"15:40\", tool: \"ask_question\", as: \"coversHire\", args: { text: \"Does the budget cover a venue hire fee as well as food?\", about: [\"@budget\"] }, note: \"asks whether that covers a venue hire fee as well as food\" },\n {\n who: \"bob\", day: 18, time: \"09:30\", tool: \"reply\",\n args: { question: \"@coversHire\", text: \"Checking each venue's terms now. Hire fees are the sticking point; food alone fits.\" },\n note: \"replies: he's checking each venue's terms, and hire fees are the sticking point\",\n },\n {\n who: \"carol\", day: 18, time: \"10:00\", tool: \"add_claim\", as: \"orangery\",\n args: { text: \"The Orangery holds 60 and is free on Friday 19 Dec\", source: \"the Orangery's bookings page\", about_from: \"2026-12-19\", about_to: \"2026-12-19\" },\n note: \"finds the Orangery holds 60 and is free on Friday 19 Dec\",\n },\n {\n who: \"carol\", day: 18, time: \"10:20\", tool: \"add_claim\", as: \"waiver\",\n args: { text: \"The Orangery waives its hire fee at a £1,800 minimum spend on food and drink, which fits the £2,400 budget\", source: \"the Orangery's events pack\", supports: [\"@budget\"], answers: [\"@coversHire\"] },\n note: \"claims the Orangery waives its hire fee at a £1,800 minimum spend, which fits the budget. That answers alice's second question, and closes its thread\",\n },\n { who: \"carol\", day: 18, time: \"10:21\", tool: \"link\", args: { from: \"@orangery\", relation: \"SUPPORTS\", to: \"@waiver\" }, note: \"links the Orangery's availability as support for that\" },\n {\n who: \"bob\", day: 18, time: \"12:05\", tool: \"add_claim\", as: \"lastYear\",\n args: { text: \"Last year's party cost £2,300, so £2,400 is plenty\", source: \"finance: events spend 2025\", about_from: \"2025-12-01\", about_to: \"2025-12-31\", supports: [\"@budget\"] },\n note: \"claims last year's party cost £2,300, as support for the budget\",\n },\n {\n who: \"bob\", day: 18, time: \"12:30\", tool: \"withdraw\", args: { id: \"@lastYear\", reason: \"That figure was the summer party\" },\n note: \"withdraws it: that figure was the summer party. Nothing is deleted: the claim and its link stay in the history, marked as ended, and drop out of the current view\",\n },\n {\n who: \"bob\", day: 18, time: \"16:45\", tool: \"add_claim\",\n args: { text: \"The party is at the Orangery on Friday 19 Dec, not the Riverside Room\", about_from: \"2026-12-19\", about_to: \"2026-12-19\", replaces: [\"@riverside\"], supports: [\"@waiver\"], answers: [\"@whichVenue\"] },\n note: \"replaces his Riverside claim: the party is at the Orangery on 19 Dec. The conflict settles, and alice's first question is answered\",\n },\n { who: \"alice\", day: 19, time: \"09:00\", tool: \"ask_question\", as: \"partners\", args: { text: \"Should partners be invited, and is there budget for them?\" }, note: \"asks whether partners should be invited, and whether there is budget for them\" },\n {\n who: \"carol\", day: 19, time: \"09:40\", tool: \"reply\",\n args: { question: \"@partners\", text: \"Finance can't stretch to partners this year. A January drinks evening for partners might work; I'll ask.\" },\n note: \"replies in the thread: not within this year's budget, but a January drinks evening might work. Still a reply, not an answer: the question stays open\",\n },\n];\n\n/** The step's moment in the story, as an ISO timestamp. */\nexport const storyTime = (s: Step): string => `2026-11-${String(s.day).padStart(2, \"0\")}T${s.time}:00.000Z`;\n\n/** Fills in \"@name\" references from the ids of earlier steps. */\nexport function resolveArgs(args: Record<string, unknown>, ids: Map<string, string>): Record<string, unknown> {\n const one = (v: unknown): unknown => {\n if (typeof v === \"string\" && v.startsWith(\"@\")) {\n const id = ids.get(v.slice(1));\n if (!id) throw new Error(`scenario: no step saved as ${v}`);\n return id;\n }\n return Array.isArray(v) ? v.map(one) : v;\n };\n return Object.fromEntries(Object.entries(args).map(([k, v]) => [k, one(v)]));\n}\n\n/**\n * Plays the story through `call`, which runs one tool as one person and\n * returns its result (with an `id` for writes that make something).\n */\nexport async function playScenario(call: (step: Step, args: Record<string, unknown>) => Promise<{ id?: string } | undefined | void>, onStep?: (step: Step, index: number) => void | Promise<void>): Promise<void> {\n const ids = new Map<string, string>();\n for (const [i, step] of STEPS.entries()) {\n await onStep?.(step, i);\n const r = await call(step, resolveArgs(step.args, ids));\n if (step.as) {\n if (!r?.id) throw new Error(`scenario: step ${i} (${step.tool}) gave no id to save as ${step.as}`);\n ids.set(step.as, r.id);\n }\n }\n}\n","// `vine demo`: three members, three hosts, one process. Alice creates the\n// example context and invites bob and carol, who join with real join codes.\n// Then the example story plays through each person's own host, so every\n// write is signed, held for undo, released and carried to the other two\n// over WebRTC, exactly as it is between three machines. Nothing of yours\n// is touched: each member has a temporary data folder of its own.\n//\n// With no network, the members find each other on an in-process signalling\n// bus. With `signal: nostrSignaller` they use the public relays, so a fourth\n// member on another machine can join with a code.\n\nimport { EventEmitter } from \"node:events\";\nimport { mkdtempSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { loadIdentity } from \"../core/identity.js\";\nimport { LocalHost } from \"../host/client.js\";\nimport { Host, placeReplica } from \"../host/host.js\";\nimport type { IceSource } from \"../p2p/ice.js\";\nimport { joinWithCode } from \"../p2p/join.js\";\nimport { parseCode } from \"../p2p/link.js\";\nimport { memorySignaller, type SignalFactory } from \"../p2p/signal.js\";\nimport { GRAPH_DESCRIPTION, GRAPH_NAME, playScenario, STEPS, type Step } from \"./scenario.js\";\n\nexport type Name = \"alice\" | \"bob\" | \"carol\";\nexport const NAMES: Name[] = [\"alice\", \"bob\", \"carol\"];\n\n/** What each member's install says about itself, as the console shows it. */\nconst ABOUT: Record<Name, { agent: string; platform: string }> = {\n alice: { agent: \"claude-code\", platform: `${process.platform} ${process.arch}` },\n bob: { agent: \"codex\", platform: \"linux x64\" },\n carol: { agent: \"claude-code\", platform: \"win32 x64\" },\n};\n\nexport interface Member {\n name: Name;\n dataDir: string;\n host: Host;\n local: LocalHost;\n call<T = Record<string, any>>(tool: string, args?: Record<string, unknown>): Promise<T>;\n}\n\nexport interface DemoOptions {\n /** Pause between steps of the story. */\n paceMs?: number;\n /** How long each write is held for undo before it is sent (normally 10 s). */\n holdMs?: number;\n /** How the members find each other. Default: an in-process bus, no network. */\n signal?: SignalFactory;\n /** STUN/TURN servers. Default: none, which is enough on one machine. */\n ice?: IceSource;\n /** Where the members' data folders are made. */\n tmp?: string;\n /** A line for the person watching. */\n narrate?(line: string): void;\n /** The hosts' own log lines. */\n log?(line: string): void;\n}\n\nexport interface Demo {\n members: Record<Name, Member>;\n /** Resolves when the whole story has played and reached every member. */\n story: Promise<void>;\n stop(): Promise<void>;\n}\n\nexport interface Narration {\n step(step: Step, index: number, total: number): void;\n}\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\nasync function waitFor(what: string, cond: () => boolean | Promise<boolean>, ms: number): Promise<void> {\n const end = Date.now() + ms;\n while (!(await cond())) {\n if (Date.now() > end) throw new Error(`Timed out waiting for ${what}.`);\n await sleep(100);\n }\n}\n\n/** Starts the three members, joined and linked, then plays the story. */\nexport async function startDemo(o: DemoOptions = {}): Promise<Demo> {\n const signal = o.signal ?? memorySignaller(new EventEmitter());\n const ice: IceSource = o.ice ?? [];\n const holdMs = o.holdMs ?? 1500;\n const paceMs = o.paceMs ?? 4000;\n const say = o.narrate ?? (() => undefined);\n const root = o.tmp ?? mkdtempSync(join(tmpdir(), \"vine-demo-\"));\n const hosts: Host[] = [];\n\n const start = async (name: Name, dataDir: string): Promise<Member> => {\n const host = await Host.start({ dataDir, graph: GRAPH_NAME, user: name, signal, ice, holdMs, log: o.log && ((m) => o.log!(`${name}: ${m}`)) });\n hosts.push(host);\n host.startSharing();\n const local = await LocalHost.connect(host.socket);\n return { name, dataDir, host, local, call: (tool, args = {}) => local.request(\"call\", { tool, args }) };\n };\n\n // Alice creates the context (a host with an empty log creates its graph).\n const aliceDir = join(root, \"alice\");\n const alice = await start(\"alice\", aliceDir);\n await alice.local.request(\"describe_context\", { description: GRAPH_DESCRIPTION });\n say(`alice starts a context called '${GRAPH_NAME}' and invites bob and carol.`);\n\n // Bob and carol join with codes, as anyone does: a full copy each, then their own host.\n const joinAs = async (name: Name): Promise<Member> => {\n const { code } = await alice.local.request<{ code: string }>(\"share\", { label: `for ${name}`, role: \"contributor\" });\n const dataDir = join(root, name);\n const welcome = await joinWithCode(parseCode(code), loadIdentity(dataDir, name), { signal, ice, about: ABOUT[name], log: o.log && ((m) => o.log!(`${name} (joining): ${m}`)) });\n if (!placeReplica(dataDir, welcome.graph.name, welcome.graph, welcome.changes)) throw new Error(`${name} could not place the copy`);\n const m = await start(name, dataDir);\n say(`${name} joins with a code and gets a full copy (${welcome.changes.length} changes).`);\n return m;\n };\n const bob = await joinAs(\"bob\");\n const carol = await joinAs(\"carol\");\n const members: Record<Name, Member> = { alice, bob, carol };\n\n // Everyone linked to everyone, before the story starts.\n const linked = (m: Member) => m.host.status().links.filter((l) => l.state === \"active\").length === 2;\n await waitFor(\"the three members to link up\", () => NAMES.every((n) => linked(members[n])), 30_000);\n say(\"all three machines are linked to each other.\");\n\n // Arrivals, as each member's agent would hear of them.\n for (const n of NAMES) {\n members[n].local.on(\"event\", (e: { event: string; data: any }) => {\n if (e.event === \"changed\" && e.data?.from) say(` ↳ reached ${n} (from ${e.data.from})`);\n if (e.event === \"digest\" && n === \"alice\") for (const line of e.data?.lines ?? []) say(` ↳ alice's agent is told: ${line}`);\n });\n }\n\n // Every copy the same: nothing held, and every member holding what alice holds.\n const have = (m: Member) => m.host.status().log.changes;\n const settled = () => NAMES.every((n) => have(members[n]) === have(alice) && members[n].host.status().log.held === 0);\n\n const story = (async () => {\n let first = true;\n await playScenario(\n (step, args) => members[step.who].call(step.tool, args),\n async (step, i) => {\n if (!first) await sleep(paceMs);\n first = false;\n // A step may answer or contradict what another member wrote: wait until that has reached its author.\n await waitFor(\"the last change to reach everyone\", settled, 30_000 + holdMs);\n say(`${i + 1}/${STEPS.length} ${step.who} ${step.note}: ${step.tool}${\"text\" in step.args ? ` “${String(step.args.text)}”` : \"\"}`);\n },\n );\n await waitFor(\"the last changes to reach everyone\", settled, 30_000 + holdMs);\n say(\"every copy now holds the same graph.\");\n })();\n story.catch(() => undefined);\n\n return {\n members,\n story,\n stop: async () => {\n for (const n of NAMES) members[n].local.close();\n for (const h of hosts) h.stop();\n },\n };\n}\n","// Questions at a terminal, for `vine setup` and `vine turn set`. Prompts go\n// to stderr, so stdout stays clean for --json. A hidden answer is typed\n// unseen and is never echoed, logged or put in a command line.\n//\n// Without a terminal, answers are read one per line from stdin.\n\nimport { createInterface } from \"node:readline\";\n\nexport interface Prompter {\n /** A free-text answer; empty takes the default. */\n ask(question: string, def?: string): Promise<string>;\n /** Typed unseen. */\n hidden(question: string): Promise<string>;\n /** One of the choices by number; empty takes the default (0-based). */\n choose(question: string, choices: string[], def?: number): Promise<number>;\n confirm(question: string, def?: boolean): Promise<boolean>;\n readonly interactive: boolean;\n}\n\n/** Lines of piped stdin, read as they're asked for. */\nclass Lines {\n private buf: string[] = [];\n private waiting: ((l: string) => void)[] = [];\n private ended = false;\n constructor(stream: NodeJS.ReadableStream) {\n const rl = createInterface({ input: stream });\n rl.on(\"line\", (l) => (this.waiting.length ? this.waiting.shift()!(l) : this.buf.push(l)));\n rl.on(\"close\", () => {\n this.ended = true;\n for (const w of this.waiting.splice(0)) w(\"\");\n });\n }\n next(): Promise<string> {\n if (this.buf.length) return Promise.resolve(this.buf.shift()!);\n if (this.ended) return Promise.resolve(\"\");\n return new Promise((r) => this.waiting.push(r));\n }\n}\n\nlet piped: Lines | undefined;\n\nfunction line(question: string): Promise<string> {\n const stdin = process.stdin;\n if (!stdin.isTTY) {\n process.stderr.write(question);\n piped ??= new Lines(stdin);\n return piped.next().then((l) => {\n process.stderr.write(\"\\n\");\n return l;\n });\n }\n const rl = createInterface({ input: stdin, output: process.stderr });\n return new Promise((resolve, reject) => {\n let answered = false;\n rl.question(question, (a) => {\n answered = true;\n rl.close();\n resolve(a);\n });\n rl.on(\"close\", () => {\n if (!answered) reject(new Error(\"Cancelled.\"));\n });\n });\n}\n\n/** Reads a secret: typed unseen at a terminal, or the next line of piped input. */\nexport function readHidden(question: string): Promise<string> {\n const stdin = process.stdin;\n if (!stdin.isTTY) {\n process.stderr.write(question);\n piped ??= new Lines(stdin);\n return piped.next().then((l) => {\n process.stderr.write(\"\\n\");\n return l.trim();\n });\n }\n process.stderr.write(question);\n stdin.setRawMode(true);\n stdin.resume();\n return new Promise((resolve, reject) => {\n let typed = \"\";\n const done = (fn: () => void) => {\n stdin.setRawMode(false);\n stdin.pause();\n stdin.off(\"data\", onData);\n process.stderr.write(\"\\n\");\n fn();\n };\n const onData = (buf: Buffer) => {\n for (const ch of buf.toString(\"utf8\")) {\n if (ch === \"\\r\" || ch === \"\\n\") return done(() => resolve(typed.trim()));\n if (ch === \"\\u0003\") return done(() => reject(new Error(\"Cancelled.\")));\n if (ch === \"\\u007f\" || ch === \"\\b\") typed = typed.slice(0, -1);\n else typed += ch;\n }\n };\n stdin.on(\"data\", onData);\n });\n}\n\nexport function terminalPrompter(): Prompter {\n return {\n interactive: Boolean(process.stdin.isTTY),\n async ask(q, def) {\n const a = (await line(`${q}${def ? ` [${def}]` : \"\"}: `)).trim();\n return a || def || \"\";\n },\n hidden: (q) => readHidden(`${q}: `),\n async choose(q, choices, def = 0) {\n process.stderr.write(`${q}\\n${choices.map((c, i) => ` ${i + 1}) ${c}${i === def ? \" (default)\" : \"\"}`).join(\"\\n\")}\\n`);\n for (;;) {\n const a = (await line(`Choose 1-${choices.length} [${def + 1}]: `)).trim();\n if (!a) return def;\n const n = Number(a);\n if (Number.isInteger(n) && n >= 1 && n <= choices.length) return n - 1;\n if (!process.stdin.isTTY) return def;\n }\n },\n async confirm(q, def = true) {\n const a = (await line(`${q} [${def ? \"Y/n\" : \"y/N\"}]: `)).trim().toLowerCase();\n return a ? a.startsWith(\"y\") : def;\n },\n };\n}\n\n/** Answers every question with its default (for --yes), and refuses hidden ones without a terminal. */\nexport function defaultsPrompter(inner: Prompter): Prompter {\n return {\n interactive: inner.interactive,\n ask: async (_q, def) => def ?? \"\",\n choose: async (_q, _c, def = 0) => def,\n confirm: async (_q, def = true) => def,\n hidden: (q) => inner.hidden(q),\n };\n}\n","// Setting up Cloudflare Realtime TURN on this machine, for `vine setup` and\n// `vine turn set --provider cloudflare`.\n//\n// Two ways in:\n// token the person makes an API token that may create TURN keys; Vine\n// creates a key with it (named after this machine) and forgets the\n// token. Fewest steps.\n// key the person creates a TURN key in the dashboard, and pastes its id\n// and secret.\n// Either way the key's secret goes only to the OS keychain (or, with the env\n// store, nowhere: the person sets VINE_CLOUDFLARE_TURN_SECRET). It is typed\n// unseen, and never put in a command line, a file, a log or the output.\n\nimport { spawn } from \"node:child_process\";\nimport { hostname } from \"node:os\";\nimport type { Prompter } from \"./prompt.js\";\n\nexport interface CloudflareSetupOptions {\n dataDir: string;\n prompt: Prompter;\n say(line: string): void;\n /** Skip the question of which way in. */\n via?: \"token\" | \"key\";\n keyId?: string;\n accountId?: string;\n store?: \"keychain\" | \"env\";\n /** Open dashboard pages in the browser (default: when interactive). */\n openPages?: boolean;\n /** Only say what would be done. */\n dryRun?: boolean;\n fetch?: typeof fetch;\n /** The relay check (tests stand in for the real TURN server). */\n checkTurn?: typeof import(\"../p2p/ice.js\").checkTurn;\n}\n\nexport interface CloudflareSetupResult {\n ok: boolean;\n keyId?: string;\n /** A key was created through the API. */\n created?: boolean;\n /** The relay check after saving. */\n relay?: string;\n error?: string;\n /** With dryRun: what would have been done. */\n wouldDo?: string[];\n}\n\n/** Opens a URL in the person's browser, best effort. Always prints it too. */\nexport function openUrl(url: string): void {\n const cmd = process.platform === \"darwin\" ? \"open\" : process.platform === \"win32\" ? \"cmd\" : \"xdg-open\";\n const args = process.platform === \"win32\" ? [\"/c\", \"start\", \"\", url] : [url];\n try {\n const p = spawn(cmd, args, { stdio: \"ignore\", detached: true });\n p.on(\"error\", () => {});\n p.unref();\n } catch {\n // printed anyway\n }\n}\n\nconst tail = (s: string) => `…${s.slice(-4)}`;\n\nexport async function setupCloudflare(o: CloudflareSetupOptions): Promise<CloudflareSetupResult> {\n const cf = await import(\"../p2p/cloudflare.js\");\n const ice = await import(\"../p2p/ice.js\");\n const { keychainTool } = await import(\"../core/secret.js\");\n const say = o.say;\n const store = o.store ?? (keychainTool() ? \"keychain\" : \"env\");\n const open = o.openPages ?? o.prompt.interactive;\n const page = (url: string) => {\n say(` ${url}`);\n if (open && !o.dryRun) openUrl(url);\n };\n\n if (store === \"keychain\" && !keychainTool())\n return { ok: false, error: \"This machine has no keychain Vine can use (macOS Keychain, or secret-tool on Linux). Use --store env and set VINE_CLOUDFLARE_TURN_SECRET instead.\" };\n\n let via = o.via ?? (o.keyId ? \"key\" : o.accountId ? \"token\" : undefined);\n // Creating a key hands Vine its secret: with nowhere to keep it, the person must create it and keep it themselves.\n if (store === \"env\") via = \"key\";\n if (!via) {\n const i = await o.prompt.choose(\n \"How do you want to give Vine a Cloudflare TURN key?\",\n [\"Make an API token, and let Vine create the key (fewest steps)\", \"I'll create the TURN key in the dashboard and paste it\"],\n 0,\n );\n via = i === 0 ? \"token\" : \"key\";\n }\n\n if (o.dryRun) {\n const wouldDo =\n via === \"token\"\n ? [\n `open ${cf.CLOUDFLARE_TOKENS_PAGE}`,\n \"ask (unseen) for your Cloudflare account id and an API token with the Realtime Admin (or Calls Write) permission\",\n `POST ${cf.CLOUDFLARE_API}/accounts/<account id>/calls/turn_keys {\"name\":\"vine-${hostname()}\"}`,\n `save the key's secret in the ${store === \"keychain\" ? \"OS keychain\" : \"environment (you set VINE_CLOUDFLARE_TURN_SECRET)\"}; forget the token`,\n \"write {provider: cloudflare, keyId} to network.json\",\n `POST ${cf.CLOUDFLARE_RTC}/turn/keys/<key id>/credentials/generate-ice-servers, then check a relay address (vine turn test)`,\n ]\n : [\n `open ${cf.CLOUDFLARE_TURN_KEYS_PAGE}`,\n \"ask for the TURN key id, and (unseen) its secret\",\n `save the secret in the ${store === \"keychain\" ? \"OS keychain\" : \"environment (you set VINE_CLOUDFLARE_TURN_SECRET)\"}`,\n \"write {provider: cloudflare, keyId} to network.json\",\n `POST ${cf.CLOUDFLARE_RTC}/turn/keys/<key id>/credentials/generate-ice-servers, then check a relay address (vine turn test)`,\n ];\n for (const w of wouldDo) say(` would ${w}`);\n return { ok: true, wouldDo };\n }\n\n let keyId = o.keyId;\n let secret: string | undefined;\n let created = false;\n let name: string | undefined;\n try {\n if (via === \"token\") {\n say(\"Make an API token on your Cloudflare account that may create TURN keys:\");\n page(cf.CLOUDFLARE_TOKENS_PAGE);\n say(' Create Token → Custom token → Permissions: Account · Realtime Admin · Edit (some accounts call it \"Calls\"). Vine uses it once and doesn\\'t keep it.');\n say(\" Your account id is on the dashboard's home page (Account details), and in its address: dash.cloudflare.com/<account id>.\");\n const accountId = o.accountId ?? (await o.prompt.hidden(\"Cloudflare account id (typed unseen)\"));\n if (!/^[0-9a-f]{32}$/i.test(accountId)) throw new Error(\"That doesn't look like a Cloudflare account id (32 hex characters).\");\n say(` account ${tail(accountId)}`);\n const token = await o.prompt.hidden(\"API token (typed unseen)\");\n if (!cf.looksLikeSecret(token)) throw new Error(\"That doesn't look like an API token.\");\n const k = await cf.createTurnKey(accountId, token, `vine-${hostname().split(\".\")[0]}`.slice(0, 60), o.fetch);\n ({ keyId, secret, name } = k);\n created = true;\n say(` Created TURN key \"${k.name}\" (${tail(k.keyId)}).`);\n } else {\n say(\"Create a TURN key on your Cloudflare account (Realtime → TURN Server → Create), then copy its id and secret:\");\n page(cf.CLOUDFLARE_TURN_KEYS_PAGE);\n keyId ??= await o.prompt.hidden(\"TURN key id (typed unseen)\");\n if (!cf.looksLikeKeyId(keyId)) throw new Error(\"That doesn't look like a TURN key id.\");\n say(` key ${tail(keyId)}`);\n if (store === \"keychain\") {\n secret = await o.prompt.hidden(\"TURN key secret (typed unseen)\");\n if (!cf.looksLikeSecret(secret)) throw new Error(\"That doesn't look like a TURN key secret.\");\n }\n }\n ice.saveCloudflareTurn(o.dataDir, { keyId: keyId!, store, ...(store === \"keychain\" ? { secret } : {}), ...(name ? { name } : {}) });\n } catch (e) {\n return { ok: false, keyId, created, error: (e as Error).message };\n } finally {\n secret = undefined;\n }\n say(\n store === \"keychain\"\n ? \" Saved. The key's secret is in your keychain; network.json only says to use Cloudflare.\"\n : ` Saved. Set ${ice.CLOUDFLARE_SECRET_ENV} to the key's secret wherever vine runs (your agent's MCP config, and your shell for \\`vine up\\`).`,\n );\n const r = await ice.checkStoredTurn(o.dataDir, undefined, o.checkTurn);\n return r.ok ? { ok: true, keyId, created, relay: r.relay } : { ok: false, keyId, created, error: r.error };\n}\n","// Does this network look like it needs a TURN server? A quick, read-only\n// check, for `vine doctor` and `vine setup`.\n//\n// - STUN over UDP, to two servers from one socket. No answer from either:\n// UDP is blocked here (common on corporate networks and some guest Wi-Fi),\n// and direct connections won't work. Both answer but report different\n// public ports for the same socket: the NAT gives each destination its own\n// mapping (\"symmetric\"), which defeats direct connections to most peers.\n// - The Nostr relays, which carry the handshakes: at least one must open.\n//\n// It decides \"likely\": two strict networks can still meet, a strict one often\n// reaches an open one, and only one machine in a pair needs TURN.\n\nimport { createSocket } from \"node:dgram\";\nimport { randomBytes } from \"node:crypto\";\nimport { networkInterfaces } from \"node:os\";\nimport WebSocket from \"ws\";\nimport { DEFAULT_STUN } from \"./ice.js\";\nimport { relayList } from \"./signal.js\";\n\nconst MAGIC = 0x2112a442;\n\nexport function bindingRequest(txid: Buffer): Buffer {\n const b = Buffer.alloc(20);\n b.writeUInt16BE(0x0001, 0); // Binding Request\n b.writeUInt16BE(0, 2);\n b.writeUInt32BE(MAGIC, 4);\n txid.copy(b, 8);\n return b;\n}\n\n/** The public address in a STUN Binding success response, or undefined. */\nexport function parseBindingResponse(msg: Buffer, txid: Buffer): { address: string; port: number } | undefined {\n if (msg.length < 20 || msg.readUInt16BE(0) !== 0x0101 || msg.readUInt32BE(4) !== MAGIC || !msg.subarray(8, 20).equals(txid)) return undefined;\n const len = msg.readUInt16BE(2);\n let off = 20;\n let mapped: { address: string; port: number } | undefined;\n while (off + 4 <= 20 + len && off + 4 <= msg.length) {\n const type = msg.readUInt16BE(off);\n const alen = msg.readUInt16BE(off + 2);\n const v = msg.subarray(off + 4, off + 4 + alen);\n if ((type === 0x0020 || type === 0x0001) && v.length >= 8 && v[1] === 0x01) {\n const xor = type === 0x0020;\n const port = v.readUInt16BE(2) ^ (xor ? MAGIC >>> 16 : 0);\n const raw = v.readUInt32BE(4) ^ (xor ? MAGIC : 0);\n const address = [raw >>> 24, (raw >>> 16) & 255, (raw >>> 8) & 255, raw & 255].join(\".\");\n if (xor) return { address, port }; // XOR-MAPPED-ADDRESS wins\n mapped = { address, port };\n }\n off += 4 + alen + ((4 - (alen % 4)) % 4);\n }\n return mapped;\n}\n\n/** \"stun:host:port\" → host and port. */\nexport function stunTarget(url: string): { host: string; port: number } | undefined {\n const m = /^stuns?:([^:?]+)(?::(\\d+))?/i.exec(url.trim());\n return m ? { host: m[1]!, port: m[2] ? Number(m[2]) : 3478 } : undefined;\n}\n\nexport interface StunAnswer {\n server: string;\n address?: string;\n port?: number;\n error?: string;\n}\n\n/** Asks each STUN server for this machine's public address, all from one UDP socket. */\nexport function probeStun(servers: string[] = DEFAULT_STUN, timeoutMs = 3000): Promise<StunAnswer[]> {\n return new Promise((resolve) => {\n const sock = createSocket(\"udp4\");\n const asks = servers.map((server) => ({ server, target: stunTarget(server), txid: randomBytes(12), answer: undefined as StunAnswer | undefined }));\n const timers: NodeJS.Timeout[] = [];\n let done = false;\n const finish = () => {\n if (done) return;\n done = true;\n timers.forEach(clearTimeout);\n try {\n sock.close();\n } catch {\n // closed\n }\n resolve(asks.map((a) => a.answer ?? { server: a.server, error: a.target ? \"no answer\" : \"not a stun: address\" }));\n };\n sock.on(\"error\", (e) => {\n for (const a of asks) a.answer ??= { server: a.server, error: e.message };\n finish();\n });\n sock.on(\"message\", (msg) => {\n for (const a of asks) {\n if (a.answer) continue;\n const r = parseBindingResponse(msg, a.txid);\n if (r) a.answer = { server: a.server, ...r };\n }\n if (asks.every((a) => a.answer || !a.target)) finish();\n });\n sock.bind(0, () => {\n const send = () => {\n for (const a of asks) {\n if (a.answer || !a.target) continue;\n sock.send(bindingRequest(a.txid), a.target.port, a.target.host, (e) => {\n if (e && !a.answer) a.answer = { server: a.server, error: e.message };\n });\n }\n };\n // UDP drops packets: ask again a couple of times.\n for (const at of [0, 400, 1200]) timers.push(setTimeout(send, at));\n timers.push(setTimeout(finish, timeoutMs));\n });\n });\n}\n\nexport interface RelayAnswer {\n relay: string;\n ok: boolean;\n ms?: number;\n error?: string;\n}\n\n/** Opens a WebSocket to each relay, and closes it. */\nexport function probeRelays(relays: string[] = relayList(), timeoutMs = 5000): Promise<RelayAnswer[]> {\n return Promise.all(\n relays.map(\n (relay) =>\n new Promise<RelayAnswer>((resolve) => {\n const start = Date.now();\n let ws: WebSocket;\n let settled = false;\n const end = (r: RelayAnswer) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n try {\n ws.terminate();\n } catch {\n // closed\n }\n resolve(r);\n };\n const timer = setTimeout(() => end({ relay, ok: false, error: \"timed out\" }), timeoutMs);\n try {\n ws = new WebSocket(relay, { handshakeTimeout: timeoutMs });\n } catch (e) {\n return end({ relay, ok: false, error: (e as Error).message });\n }\n ws.on(\"open\", () => end({ relay, ok: true, ms: Date.now() - start }));\n ws.on(\"error\", (e) => end({ relay, ok: false, error: e.message }));\n }),\n ),\n );\n}\n\nexport type NatVerdict = \"direct\" | \"public\" | \"symmetric\" | \"udp-blocked\" | \"unknown\";\n\nexport interface NetCheck {\n stun: StunAnswer[];\n relays: RelayAnswer[];\n nat: NatVerdict;\n /** Whether this network looks like it needs TURN. */\n needsTurn: boolean;\n /** The relays that opened. */\n relaysUp: number;\n /** Plain words, one or two sentences. */\n summary: string;\n}\n\nconst localAddresses = () =>\n new Set(\n Object.values(networkInterfaces())\n .flat()\n .filter(Boolean)\n .map((i) => i!.address),\n );\n\n/** The verdict from STUN answers alone. */\nexport function judgeNat(stun: StunAnswer[], local: Set<string> = localAddresses()): NatVerdict {\n const got = stun.filter((s) => s.address && s.port);\n if (!stun.length) return \"unknown\";\n if (!got.length) return \"udp-blocked\";\n if (got.length < 2) return got.some((s) => local.has(s.address!)) ? \"public\" : \"direct\";\n const first = got[0]!;\n if (got.some((s) => s.address !== first.address || s.port !== first.port)) return \"symmetric\";\n return local.has(first.address!) ? \"public\" : \"direct\";\n}\n\nexport function describeNet(nat: NatVerdict, relaysUp: number, relays: number): { needsTurn: boolean; summary: string } {\n const needsTurn = nat === \"udp-blocked\" || nat === \"symmetric\";\n const net = {\n public: \"This machine has a public address: direct connections should work.\",\n direct: \"STUN works and the NAT keeps one public address per connection: direct connections should work with most members.\",\n symmetric:\n \"The two STUN servers saw different public ports (a strict, \\\"symmetric\\\" NAT, common on corporate networks, VPNs and phone hotspots): direct connections will likely fail, so this network will likely need TURN.\",\n \"udp-blocked\":\n \"No STUN server answered over UDP, so UDP looks blocked here (common on corporate networks and guest Wi-Fi): direct connections won't work, so this network will need TURN.\",\n unknown: \"No STUN servers to ask, so the network wasn't checked.\",\n }[nat];\n const rel =\n relaysUp === 0\n ? ` None of the ${relays} Nostr relays opened, so members can't find each other from here (check the network, or set VINE_RELAYS).`\n : ` ${relaysUp} of ${relays} Nostr relays opened, enough to find members.`;\n return { needsTurn, summary: net + rel };\n}\n\n/** Both checks at once. Read-only: nothing is sent but STUN requests and WebSocket opens. */\nexport async function checkNetwork(o: { stun?: string[]; relays?: string[]; timeoutMs?: number } = {}): Promise<NetCheck> {\n const [stun, relays] = await Promise.all([probeStun(o.stun, o.timeoutMs), probeRelays(o.relays, o.timeoutMs)]);\n const nat = judgeNat(stun);\n const relaysUp = relays.filter((r) => r.ok).length;\n return { stun, relays, nat, relaysUp, ...describeNet(nat, relaysUp, relays.length) };\n}\n","// `vine doctor`: can this machine run vine, and will its network let members\n// connect? Also run inline by `vine setup`.\n\nimport { packageInfo } from \"../core/package-root.js\";\n\nexport type CheckLevel = \"ok\" | \"warn\" | \"fail\";\n\nexport interface CheckResult {\n name: string;\n level: CheckLevel;\n detail: string;\n}\n\nexport interface DoctorResult {\n checks: CheckResult[];\n failed: number;\n /** The network check, when it ran. */\n network?: import(\"../p2p/netcheck.js\").NetCheck;\n}\n\n/** A check that passes but wants a word said: shown as \"warn\", not counted as failed. */\nexport class Warn extends Error {}\n\nconst tag: Record<CheckLevel, string> = { ok: \"ok \", warn: \"warn \", fail: \"FAIL \" };\n\nexport async function runDoctor(o: { print?: (line: string) => void; network?: boolean } = {}): Promise<DoctorResult> {\n const checks: CheckResult[] = [];\n const out: DoctorResult = { checks, failed: 0 };\n const check = async (name: string, fn: () => Promise<string> | string) => {\n let r: CheckResult;\n try {\n r = { name, level: \"ok\", detail: await fn() };\n } catch (e) {\n r = { name, level: e instanceof Warn ? \"warn\" : \"fail\", detail: (e as Error).message };\n }\n checks.push(r);\n if (r.level === \"fail\") out.failed++;\n o.print?.(`${tag[r.level]} ${name}: ${r.detail}`);\n };\n const pkg = packageInfo();\n\n await check(\"node\", () => {\n const major = Number(process.versions.node.split(\".\")[0]);\n if (major < 20) throw new Error(`Node ${process.versions.node}; vine needs Node 20 or later`);\n return `${process.versions.node} on ${process.platform}-${process.arch}`;\n });\n await check(\"vine-context\", () => pkg.version);\n await check(\"relate\", async () => {\n const { loadRelate } = await import(\"../core/relate.js\");\n const R = await loadRelate();\n const conn = R.Database.open(\":memory:\").connect();\n conn.query(\"CREATE FULLTEXT INDEX t IF NOT EXISTS FOR (n:T) ON EACH [n.text]\");\n conn.query(\n \"CREATE VECTOR INDEX v IF NOT EXISTS FOR (n:T) ON (n.e) OPTIONS {indexConfig: {`vector.dimensions`: 2, `vector.similarity_function`: 'cosine'}}\",\n );\n conn.query(\"CREATE (:T {text: 'hello graph', e: [1.0, 0.0]})\");\n const r = conn.query(\n \"MATCH (n:T) SEARCH n IN (COMBINE (VECTOR INDEX v FOR [1.0, 0.0] LIMIT 5 WEIGHT 1, \" +\n \"FULLTEXT INDEX t FOR 'hello' LIMIT 5 WEIGHT 1) USING WRRF WITH CONSTANT 60 LIMIT 5) SCORE AS s RETURN count(n) AS n\",\n );\n if (Number(r.rows[0]?.n) !== 1) throw new Error(\"hybrid search returned nothing\");\n return \"embedded store, vector + full-text + COMBINE hybrid search\";\n });\n await check(\"node-datachannel\", async () => {\n const ndc = (await import(\"node-datachannel\")).default;\n const pc = new ndc.PeerConnection(\"doctor\", { iceServers: [] });\n pc.createDataChannel(\"probe\");\n pc.close();\n return \"WebRTC data channels available\";\n });\n await check(\"model\", async () => {\n const { claimsPack } = await import(\"../core/pack.js\");\n const p = claimsPack();\n return `${p.model.title}: ${p.tools.length} tools`;\n });\n await check(\"search embedder\", async () => {\n const { chooseEmbedder } = await import(\"../core/embed.js\");\n const { embedder: e, why } = chooseEmbedder();\n const v = e.embed(\"hello graph\");\n if (v?.length !== e.dim) throw new Error(`${e.name} returned ${v?.length ?? \"no\"} numbers, not ${e.dim}`);\n if (why) return why;\n return e.name === \"hash-256\" ? `${e.name} (VINE_EMBEDDER=hash; matches words, not meaning)` : `${e.name} (VINE_EMBEDDER; ${e.dim} dimensions, matches meaning)`;\n });\n await check(\"data directory\", async () => {\n const { defaultDataDir } = await import(\"../core/graph.js\");\n const { mkdirSync, accessSync, constants } = await import(\"node:fs\");\n const dir = defaultDataDir();\n mkdirSync(dir, { recursive: true });\n accessSync(dir, constants.W_OK);\n return dir;\n });\n\n const { defaultDataDir } = await import(\"../core/graph.js\");\n const ice = await import(\"../p2p/ice.js\");\n const summary = ice.resolveIce(defaultDataDir()).summary;\n\n if (o.network !== false) {\n await check(\"network\", async () => {\n const { checkNetwork } = await import(\"../p2p/netcheck.js\");\n const stun = summary.stun.length >= 2 ? summary.stun : ice.DEFAULT_STUN;\n const n = await checkNetwork({ stun });\n out.network = n;\n if (n.relaysUp === 0) throw new Error(n.summary);\n if (n.needsTurn && !summary.turn) throw new Warn(`${n.summary} Set one up with \\`vine turn set --provider cloudflare\\` (only one machine in a pair needs it).`);\n return n.needsTurn ? `${n.summary} A TURN server is set, so that's covered.` : n.summary;\n });\n }\n\n await check(\"turn server\", async () => {\n if (summary.source === \"env\") return `VINE_ICE is set (${summary.turn ?? \"no TURN server\"})`;\n if (!summary.turn) return \"none set: members connect directly (`vine turn set --provider cloudflare` adds one)\";\n const r = await ice.checkStoredTurn(defaultDataDir());\n if (!r.ok) throw new Error(`${summary.turn}: ${r.error}`);\n return `${summary.turn} answered and lent a relay address`;\n });\n return out;\n}\n","// `vine setup` (advertised as `npx vine-context setup`): everything a new\n// machine needs, in one go, and safe to run again: each step looks at what's\n// already there first, and only does what's missing or broken.\n//\n// 1. the global `vine` command (the plugin runs it)\n// 2. the plugin, for each agent found (Claude Code, Codex)\n// 3. your display name\n// 4. the `vine doctor` checks\n// 5. the network: does it look like it needs TURN?\n// 6. TURN: Cloudflare's (default when needed), your own, or none\n// 7. autostart at login (macOS)\n// 8. what to do next\n//\n// Every command it runs is printed first. --dry-run runs only the read-only\n// checks, and prints what it would do instead of doing it.\n\nimport { spawnSync } from \"node:child_process\";\nimport { packageInfo } from \"../core/package-root.js\";\nimport type { Prompter } from \"./prompt.js\";\n\nexport type Agent = \"claude\" | \"codex\";\nexport type TurnChoice = \"cloudflare\" | \"custom\" | \"none\";\n\nexport interface SetupOptions {\n yes?: boolean;\n /** Which agents to install the plugin for; none: no agent. Default: those found. */\n agents?: Agent[] | \"none\";\n turn?: TurnChoice;\n json?: boolean;\n dryRun?: boolean;\n}\n\nexport type StepStatus = \"ok\" | \"done\" | \"would\" | \"skipped\" | \"warn\" | \"failed\";\n\nexport interface StepResult {\n step: string;\n status: StepStatus;\n detail: string;\n /** Commands run (or, with dry-run, that would be). Never holds a secret. */\n commands?: string[];\n}\n\nexport interface RunResult {\n status: number | null;\n stdout: string;\n}\n\n/** What the wizard touches outside itself, so tests can stand in for it. */\nexport interface SetupDeps {\n prompt: Prompter;\n /** Human-readable output (stderr with --json). */\n say(line: string): void;\n /** Path of a command on PATH, or undefined. */\n which(cmd: string): string | undefined;\n /** Runs a command quietly and returns its output (read-only queries). */\n query(cmd: string, args: string[]): RunResult;\n /** Runs a command that changes something, its output shown to the person. */\n run(cmd: string, args: string[]): RunResult;\n platform: NodeJS.Platform;\n dataDir: string;\n /** Run through npx (so `vine` may not be installed yet). */\n viaNpx: boolean;\n version: string;\n doctor(): Promise<import(\"./doctor.js\").DoctorResult>;\n network(): Promise<import(\"../p2p/netcheck.js\").NetCheck>;\n name: { current(): { name: string; source: import(\"../core/identity.js\").NameSource }; set(name: string): void };\n turn: {\n summary(): import(\"../p2p/ice.js\").IceSummary;\n check(): Promise<{ ok: boolean; error?: string; relay?: string }>;\n cloudflare(o: { dryRun: boolean }): Promise<import(\"./cloudflare-setup.js\").CloudflareSetupResult>;\n custom(): Promise<{ ok: boolean; error?: string; relay?: string; label?: string }>;\n };\n autostartOn(): boolean;\n}\n\nconst quote = (a: string) => (/^[\\w@%+=:,./-]+$/.test(a) ? a : `'${a.replace(/'/g, \"'\\\\''\")}'`);\nconst shown = (cmd: string, args: string[]) => [cmd, ...args].map(quote).join(\" \");\n\n/** a < b, for plain x.y.z versions. */\nexport function older(a: string, b: string): boolean {\n const pa = a.split(/[.-]/).map((n) => parseInt(n, 10) || 0);\n const pb = b.split(/[.-]/).map((n) => parseInt(n, 10) || 0);\n for (let i = 0; i < 3; i++) if ((pa[i] ?? 0) !== (pb[i] ?? 0)) return (pa[i] ?? 0) < (pb[i] ?? 0);\n return false;\n}\n\nexport const MARKETPLACE = \"CraigDeverall/vine-context\";\nexport const PLUGIN = \"vine-context@vine-context\";\n\nconst AGENTS: Record<Agent, { title: string; marketplaceList: string[]; marketplaceAdd: string[]; pluginList: string[]; install: string[]; installed(out: string): boolean; hasMarket(out: string): boolean }> = {\n claude: {\n title: \"Claude Code\",\n marketplaceList: [\"plugin\", \"marketplace\", \"list\"],\n marketplaceAdd: [\"plugin\", \"marketplace\", \"add\", MARKETPLACE],\n pluginList: [\"plugin\", \"list\"],\n install: [\"plugin\", \"install\", PLUGIN],\n installed: (out) => out.includes(PLUGIN),\n hasMarket: (out) => /(^|\\s)vine-context(\\s|$)/m.test(out),\n },\n codex: {\n title: \"Codex\",\n marketplaceList: [\"plugin\", \"marketplace\", \"list\"],\n marketplaceAdd: [\"plugin\", \"marketplace\", \"add\", MARKETPLACE],\n pluginList: [\"plugin\", \"list\"],\n install: [\"plugin\", \"add\", PLUGIN],\n installed: (out) => new RegExp(`^${PLUGIN.replace(/[.@]/g, \"\\\\$&\")}\\\\s+installed`, \"m\").test(out),\n hasMarket: (out) => /^vine-context\\s/m.test(out),\n },\n};\n\nexport async function runSetup(o: SetupOptions, d: SetupDeps): Promise<{ steps: StepResult[]; exitCode: number }> {\n const steps: StepResult[] = [];\n const dry = Boolean(o.dryRun);\n const record = (r: StepResult) => {\n steps.push(r);\n const mark = { ok: \"ok \", done: \"done \", would: \"would\", skipped: \"skip \", warn: \"warn \", failed: \"FAIL \" }[r.status];\n d.say(`${mark} ${r.status === \"would\" ? r.detail.replace(/^would /, \"\") : r.detail}`);\n };\n const heading = (n: number, title: string) => d.say(`\\n${n}. ${title}`);\n /** Prints the command, then runs it (or, dry, doesn't). True if it ran and succeeded. */\n const act = (cmd: string, args: string[], commands: string[]): boolean => {\n const line = shown(cmd, args);\n commands.push(line);\n d.say(` $ ${line}`);\n if (dry) return true;\n return d.run(cmd, args).status === 0;\n };\n\n d.say(`vine setup ${d.version}${dry ? \" (dry run: nothing will be changed)\" : \"\"}`);\n\n // 1. The global vine command.\n heading(1, \"The vine command\");\n {\n const path = d.which(\"vine\");\n const have = path ? d.query(path, [\"--version\"]).stdout.trim() : \"\";\n const commands: string[] = [];\n if (path && have && !older(have, d.version)) record({ step: \"vine\", status: \"ok\", detail: `vine ${have} is installed (${path})` });\n else {\n const why = path\n ? `vine ${have || \"(unknown version)\"} is older than ${d.version}`\n : `vine isn't installed globally${d.viaNpx ? \" (this is a temporary npx copy)\" : \"\"}, and the plugin needs it on your PATH`;\n d.say(` ${why}.`);\n if (await d.prompt.confirm(` Install vine-context ${d.version} globally with npm?`, true)) {\n const ok = act(\"npm\", [\"install\", \"-g\", `vine-context@${d.version}`], commands);\n record({ step: \"vine\", status: dry ? \"would\" : ok ? \"done\" : \"failed\", detail: dry ? `would install vine-context ${d.version}` : ok ? `installed vine-context ${d.version}` : \"npm install failed (see above)\", commands });\n } else record({ step: \"vine\", status: \"skipped\", detail: `not installed: run \\`npm install -g vine-context\\` before using the plugin` });\n }\n }\n\n // 2. The plugin for each agent.\n heading(2, \"Your agents\");\n {\n const wanted: Agent[] = o.agents === \"none\" ? [] : (o.agents ?? ([\"claude\", \"codex\"] as Agent[]).filter((a) => d.which(a)));\n if (o.agents === \"none\") record({ step: \"agents\", status: \"skipped\", detail: \"no agent (--agent none)\" });\n else if (!wanted.length) record({ step: \"agents\", status: \"skipped\", detail: \"no Claude Code or Codex found on your PATH\" });\n for (const a of wanted) {\n const spec = AGENTS[a];\n if (!d.which(a)) {\n record({ step: `plugin:${a}`, status: \"skipped\", detail: `${spec.title} (\\`${a}\\`) isn't on your PATH` });\n continue;\n }\n if (spec.installed(d.query(a, spec.pluginList).stdout)) {\n record({ step: `plugin:${a}`, status: \"ok\", detail: `${spec.title}: the vine-context plugin is installed` });\n continue;\n }\n const commands: string[] = [];\n const needMarket = !spec.hasMarket(d.query(a, spec.marketplaceList).stdout);\n const plan = [...(needMarket ? [shown(a, spec.marketplaceAdd)] : []), shown(a, spec.install)];\n d.say(` ${spec.title} doesn't have the plugin yet. This runs:\\n${plan.map((p) => ` ${p}`).join(\"\\n\")}`);\n if (!(await d.prompt.confirm(` Install the plugin for ${spec.title}?`, true))) {\n record({ step: `plugin:${a}`, status: \"skipped\", detail: `${spec.title}: not installed (you can run the commands above yourself)` });\n continue;\n }\n const ok = (!needMarket || act(a, spec.marketplaceAdd, commands)) && act(a, spec.install, commands);\n record({\n step: `plugin:${a}`,\n status: dry ? \"would\" : ok ? \"done\" : \"failed\",\n detail: dry ? `${spec.title}: would install the plugin` : ok ? `${spec.title}: plugin installed (restart ${spec.title} to load it)` : `${spec.title}: install failed (see above)`,\n commands,\n });\n }\n d.say(\" Another MCP agent? Point it at the command `vine mcp` (stdio). For example: claude mcp add vine-context -- vine mcp\");\n }\n\n // 3. Display name.\n heading(3, \"Your name\");\n {\n const cur = d.name.current();\n if (cur.source === \"VINE_USER\") record({ step: \"name\", status: \"ok\", detail: `${cur.name} (from VINE_USER)` });\n else {\n const from = { chosen: \"set before\", git: \"from git\", os: \"from your computer account\", login: \"your login name\", generated: \"made up\" }[cur.source] ?? cur.source;\n // A found name is offered to keep or change; a guess is only the fallback, so ask for theirs.\n const guessed = cur.source === \"login\" || cur.source === \"generated\";\n const question = guessed ? ` Your name, as others will see it (Enter keeps ${cur.name}, ${from})` : ` The name others see you as (${from})`;\n const name = (await d.prompt.ask(question, cur.name)).trim().slice(0, 60);\n if (cur.source === \"chosen\" && name === cur.name) record({ step: \"name\", status: \"ok\", detail: `${name}` });\n else if (!name) record({ step: \"name\", status: \"skipped\", detail: `kept ${cur.name}` });\n // A kept guess isn't saved, so a better name found later (or given here next time) replaces it.\n else if (guessed && name === cur.name) record({ step: \"name\", status: \"skipped\", detail: `using ${cur.name} for now (${from}); set your own with \\`vine setup\\`` });\n else {\n if (!dry) d.name.set(name);\n record({ step: \"name\", status: dry ? \"would\" : \"done\", detail: dry ? `would save ${name} as your name` : `saved ${name} as your name` });\n }\n }\n }\n\n // 4. Doctor.\n heading(4, \"This machine\");\n {\n const r = await d.doctor();\n const bad = r.checks.filter((c) => c.level === \"fail\");\n record(\n bad.length\n ? { step: \"doctor\", status: \"failed\", detail: `${bad.length} check(s) failed: ${bad.map((c) => c.name).join(\", \")} (\\`vine doctor\\` shows them)` }\n : { step: \"doctor\", status: \"ok\", detail: `all ${r.checks.length} checks passed` },\n );\n }\n\n // 5. Network.\n heading(5, \"Your network\");\n let needsTurn = false;\n {\n const n = await d.network();\n needsTurn = n.needsTurn;\n d.say(` ${n.summary}`);\n record({\n step: \"network\",\n status: n.relaysUp === 0 ? \"failed\" : n.needsTurn ? \"warn\" : \"ok\",\n detail: n.relaysUp === 0 ? \"no Nostr relay reachable\" : n.needsTurn ? \"this network will likely need TURN\" : \"direct connections should work from here\",\n });\n }\n\n // 6. TURN.\n heading(6, \"TURN (a relay for networks that block direct connections)\");\n {\n d.say(\n \" Vine connects members directly when it can. A TURN server only relays the encrypted connection when it can't, and only one machine in a pair needs one.\\n\" +\n \" Changes are forwarded between members, so you only need it if you can reach no member at all.\",\n );\n const s = d.turn.summary();\n let choice: TurnChoice | undefined = o.turn;\n let working = false;\n if (s.source === \"env\") {\n record({ step: \"turn\", status: \"ok\", detail: `VINE_ICE is set and replaces the TURN setting (${s.turn ?? \"no TURN server\"})` });\n choice = \"none\";\n working = true;\n } else if (s.turn && !choice) {\n const c = await d.turn.check();\n if (c.ok) {\n record({ step: \"turn\", status: \"ok\", detail: `${s.turn} is set and lent a relay address` });\n working = true;\n } else {\n d.say(` ${s.turn} is set, but it doesn't work: ${c.error}`);\n choice = s.provider === \"cloudflare\" ? \"cloudflare\" : undefined; // repair it\n }\n }\n if (!working) {\n if (!choice) {\n d.say(needsTurn ? \" This network looks like it needs TURN.\" : \" This network looks fine without TURN; you can add it later with `vine turn set --provider cloudflare`.\");\n const i = await d.prompt.choose(\n \" Set up TURN?\",\n [\"Set up Cloudflare TURN (free for this use; your own Cloudflare account)\", \"Use my own TURN server\", \"Skip\"],\n needsTurn ? 0 : 2,\n );\n choice = ([\"cloudflare\", \"custom\", \"none\"] as const)[i];\n }\n if (choice === \"none\") record({ step: \"turn\", status: needsTurn ? \"warn\" : \"skipped\", detail: needsTurn ? \"no TURN server: members on stricter networks may not connect\" : \"no TURN server (not needed here)\" });\n else if (choice === \"cloudflare\") {\n if (!dry && !d.prompt.interactive)\n record({ step: \"turn\", status: \"failed\", detail: \"Cloudflare TURN needs a terminal to type the key in unseen: run `vine turn set --provider cloudflare` in one\" });\n else {\n const r = await d.turn.cloudflare({ dryRun: dry });\n record(\n dry\n ? { step: \"turn\", status: \"would\", detail: \"would set up Cloudflare TURN\" }\n : r.ok\n ? { step: \"turn\", status: \"done\", detail: `Cloudflare TURN set up${r.created ? \" (a new TURN key)\" : \"\"}, and it lent a relay address (${r.relay})` }\n : { step: \"turn\", status: \"failed\", detail: `Cloudflare TURN: ${r.error}` },\n );\n }\n } else if (choice === \"custom\") {\n if (dry) record({ step: \"turn\", status: \"would\", detail: \"would ask for your TURN server, username and (unseen) password, save them, and test it\" });\n else {\n const r = await d.turn.custom();\n record(r.ok ? { step: \"turn\", status: \"done\", detail: `${r.label} set, and it lent a relay address (${r.relay})` } : { step: \"turn\", status: \"failed\", detail: `TURN server: ${r.error}` });\n }\n }\n }\n }\n\n // 7. Autostart.\n heading(7, \"Sync after a reboot\");\n {\n if (d.platform !== \"darwin\") record({ step: \"autostart\", status: \"skipped\", detail: \"autostart is for macOS; elsewhere run `vine up` from your login scripts\" });\n else if (d.autostartOn()) record({ step: \"autostart\", status: \"ok\", detail: \"`vine up` already runs at login\" });\n else if (await d.prompt.confirm(\" Run `vine up` at login, so your shared contexts sync after a reboot?\", true)) {\n const commands: string[] = [];\n // The global vine, not this (possibly npx) copy: the launch agent must outlive it.\n const vine = d.which(\"vine\");\n const ok = vine || dry ? act(vine ?? \"vine\", [\"autostart\", \"on\"], commands) : false;\n record({ step: \"autostart\", status: dry ? \"would\" : ok ? \"done\" : \"failed\", detail: dry ? \"would turn autostart on\" : ok ? \"autostart on\" : \"couldn't turn autostart on (is vine installed?)\", commands });\n } else record({ step: \"autostart\", status: \"skipped\", detail: \"autostart off (`vine autostart on` turns it on)\" });\n }\n\n // 8. Next.\n heading(8, \"Next\");\n d.say(\" See it with an example: vine demo\");\n d.say(' Or tell your agent: \"start a context called <name> for <what it\\'s for>\", then \"share it with Sam\".');\n const failed = steps.filter((s) => s.status === \"failed\").length;\n d.say(failed ? `\\n${failed} step(s) need attention (above). Run \\`npx vine-context setup\\` again to repair.` : dry ? \"\\nDry run done: nothing was changed.\" : \"\\nAll set.\");\n return { steps, exitCode: failed ? 1 : 0 };\n}\n\n/** Real dependencies. */\nexport async function realDeps(o: SetupOptions, prompt: Prompter): Promise<SetupDeps> {\n const [{ defaultDataDir }, identity, ice, { existsSync }, { homedir }, { join, delimiter }] = await Promise.all([\n import(\"../core/graph.js\"),\n import(\"../core/identity.js\"),\n import(\"../p2p/ice.js\"),\n import(\"node:fs\"),\n import(\"node:os\"),\n import(\"node:path\"),\n ]);\n const dataDir = defaultDataDir();\n const say = (l: string) => (o.json ? process.stderr : process.stdout).write(`${l}\\n`);\n const which = (cmd: string) => {\n for (const dir of (process.env.PATH ?? \"\").split(delimiter)) {\n // npx (npm exec) puts its throwaway install, and the project's, first on PATH: those aren't installed.\n if (/[\\\\/]_npx[\\\\/]|node_modules[\\\\/]\\.bin/.test(dir)) continue;\n for (const ext of process.platform === \"win32\" ? [\".cmd\", \".exe\", \"\"] : [\"\"]) {\n const p = join(dir, cmd + ext);\n if (dir && existsSync(p)) return p;\n }\n }\n return undefined;\n };\n return {\n prompt,\n say,\n which,\n query: (cmd, args) => {\n const r = spawnSync(cmd, args, { encoding: \"utf8\", timeout: 30_000, stdio: [\"ignore\", \"pipe\", \"pipe\"], shell: process.platform === \"win32\" });\n return { status: r.status, stdout: r.stdout ?? \"\" };\n },\n run: (cmd, args) => {\n // Output goes to the person (stderr with --json, so stdout stays JSON).\n const r = spawnSync(cmd, args, { stdio: [\"inherit\", o.json ? 2 : \"inherit\", \"inherit\"], shell: process.platform === \"win32\" });\n return { status: r.status, stdout: \"\" };\n },\n platform: process.platform,\n dataDir,\n viaNpx: process.env.npm_command === \"exec\" || /[\\\\/]_npx[\\\\/]/.test(process.argv[1] ?? \"\"),\n version: packageInfo().version,\n doctor: async () => {\n const { runDoctor } = await import(\"./doctor.js\");\n return runDoctor({ network: false, print: (l) => say(` ${l}`) });\n },\n network: async () => {\n const { checkNetwork } = await import(\"../p2p/netcheck.js\");\n return checkNetwork();\n },\n name: {\n current: () => identity.resolveName(dataDir),\n set: (n) => void identity.setName(dataDir, n),\n },\n turn: {\n summary: () => ice.resolveIce(dataDir).summary,\n check: () => ice.checkStoredTurn(dataDir),\n cloudflare: async ({ dryRun }) => {\n const { setupCloudflare } = await import(\"./cloudflare-setup.js\");\n return setupCloudflare({ dataDir, prompt, say: (l) => say(` ${l}`), dryRun });\n },\n custom: async () => {\n const { keychainTool } = await import(\"../core/secret.js\");\n try {\n const where = await prompt.ask(\" TURN server (host or host:port)\");\n const { host, port } = ice.parseHostPort(where);\n const username = await prompt.ask(\" Username\");\n const transport = ([\"udp\", \"tcp\", \"tls\"] as const)[await prompt.choose(\" How is it reached?\", [\"UDP (usual)\", \"TCP\", \"TLS\"], 0)];\n const store = keychainTool() ? \"keychain\" : \"file\";\n const password = await prompt.hidden(` Password for ${username} on ${host} (typed unseen)`);\n const t = ice.saveTurn(dataDir, { host, port, username, transport, store, password });\n const c = await ice.checkStoredTurn(dataDir);\n return { ...c, label: `${t.host}:${t.port} (${t.transport})` };\n } catch (e) {\n return { ok: false, error: (e as Error).message };\n }\n },\n },\n autostartOn: () => existsSync(join(homedir(), \"Library\", \"LaunchAgents\", \"dev.vine.up.plist\")),\n };\n}\n\nexport const SETUP_USAGE = `Usage: vine setup [--yes] [--agent claude|codex|none] [--turn cloudflare|custom|none] [--json] [--dry-run]\n (or, before vine is installed: npx vine-context setup)\n\nSets this machine up for Vine Context, and repairs it when run again:\ninstalls the vine command and your agents' plugin, confirms your name, checks\nthe machine and the network, sets up TURN if the network needs it, and offers\nautostart at login (macOS).\n\n --yes take the default answer to every question (secrets are still typed, unseen)\n --agent which agents get the plugin (comma-separated); default: those found\n --turn cloudflare, custom or none, instead of asking\n --json print the steps' results as JSON on stdout (the rest goes to stderr)\n --dry-run run the read-only checks only, and print what would be done`;\n\nexport async function setupCommand(args: string[]): Promise<number> {\n const { parseArgs } = await import(\"node:util\");\n let values: Record<string, string | boolean | undefined>;\n try {\n ({ values } = parseArgs({\n args,\n options: { yes: { type: \"boolean\", short: \"y\" }, agent: { type: \"string\" }, turn: { type: \"string\" }, json: { type: \"boolean\" }, \"dry-run\": { type: \"boolean\" }, help: { type: \"boolean\", short: \"h\" } },\n }));\n } catch (e) {\n console.error(`${(e as Error).message}\\n\\n${SETUP_USAGE}`);\n return 2;\n }\n if (values.help) {\n console.log(SETUP_USAGE);\n return 0;\n }\n const agentArg = values.agent as string | undefined;\n const agents = agentArg === undefined ? undefined : agentArg === \"none\" ? (\"none\" as const) : (agentArg.split(\",\").map((s) => s.trim()) as Agent[]);\n const turn = values.turn as TurnChoice | undefined;\n if ((Array.isArray(agents) && agents.some((a) => !(a in AGENTS))) || (turn && ![\"cloudflare\", \"custom\", \"none\"].includes(turn))) {\n console.error(SETUP_USAGE);\n return 2;\n }\n const o: SetupOptions = { yes: Boolean(values.yes), agents, turn, json: Boolean(values.json), dryRun: Boolean(values[\"dry-run\"]) };\n const { terminalPrompter, defaultsPrompter } = await import(\"./prompt.js\");\n const prompt = o.yes ? defaultsPrompter(terminalPrompter()) : terminalPrompter();\n const deps = await realDeps(o, prompt);\n try {\n const r = await runSetup(o, deps);\n if (o.json) console.log(JSON.stringify({ version: deps.version, dryRun: Boolean(o.dryRun), steps: r.steps }, null, 2));\n return r.exitCode;\n } catch (e) {\n console.error((e as Error).message);\n return 1;\n }\n}\n","// `vine hook <event>`: what an agent's lifecycle hook runs. It reads the hook's\n// JSON from stdin (the chat's id and folder), and answers with text for the\n// model's context:\n//\n// session-start what the chat's context is for, and that decisions and\n// open questions from the chat belong in it\n// prompt what other members' changes meant since the agent was last\n// told (the sync digest), and a one-line reminder of where\n// the chat records\n//\n// The agent then knows the context is there without first calling one of its\n// tools. Everything is read from this machine's data folder: no host is\n// started or asked, so it adds a few milliseconds to a prompt and works\n// offline. It never fails a prompt: on any error it says nothing and exits 0.\n//\n// Claude Code and Codex share one hook format (and Gemini CLI's is the same):\n// the answer is `{ hookSpecificOutput: { hookEventName, additionalContext } }`.\n// The text states facts rather than giving orders: agents treat hook text that\n// reads as commands with suspicion.\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { Change } from \"../core/changes.js\";\nimport { Members } from \"../core/members.js\";\nimport { defaultDataDir } from \"../core/paths.js\";\nimport { chatMarks, markSeen, unseenNews, updateChatMarks } from \"../host/news.js\";\nimport { chatIdFromEnv, chatLink, folderLink, resolveRef, type Ref } from \"../mcp/links.js\";\n\nexport type HookEvent = \"session-start\" | \"prompt\";\n\nexport interface HookOptions {\n event: HookEvent;\n /** The hook's stdin, parsed: field names differ by agent, so several are read. */\n input: Record<string, unknown>;\n dataDir: string;\n env?: NodeJS.ProcessEnv;\n cwd?: string;\n now?: Date;\n}\n\nconst MAX_NEWS_LINES = 8;\nconst str = (v: unknown): string | undefined => (typeof v === \"string\" && v ? v : undefined);\nconst first = (v: unknown): string | undefined => (Array.isArray(v) ? str(v[0]) : undefined);\nconst plural = (n: number, one: string) => `${n} ${one}${n === 1 ? \"\" : \"s\"}`;\n\n/** The chat's contexts on this machine (local names), and where its writes go. */\nfunction chatContexts(o: HookOptions, chat: string | undefined, cwd: string): { names: string[]; writeTo?: string } {\n const env = o.env ?? process.env;\n const configured = env.VINE_CONTEXT ?? env.VINE_GRAPH;\n // The same order the MCP server uses: the chat's own, else its folder's, else the configured one.\n const link = (chat ? chatLink(o.dataDir, chat) : undefined) ?? folderLink(o.dataDir, cwd) ?? (configured ? { contexts: [{ name: configured } as Ref], write_to: configured } : undefined);\n if (!link) return { names: [] };\n const names: string[] = [];\n let writeTo: string | undefined;\n for (const ref of link.contexts) {\n const name = resolveRef(o.dataDir, ref);\n if (!name || names.includes(name)) continue;\n names.push(name);\n if (ref.name === link.write_to) writeTo = name;\n }\n return { names, writeTo: writeTo ?? names[0] };\n}\n\n/** What a context is for and how much it holds, from its change log. */\nfunction summary(dataDir: string, name: string): { description: string | null; members: number; claims: number; questions: number } {\n const file = join(dataDir, \"hosts\", name, \"changes.jsonl\");\n const changes: Change[] = [];\n if (existsSync(file))\n for (const line of readFileSync(file, \"utf8\").split(\"\\n\")) {\n if (!line.trim()) continue;\n try {\n changes.push(JSON.parse(line) as Change);\n } catch {\n // a torn last line: skip it\n }\n }\n const members = new Members(changes);\n const ids = (kind: string) => new Set(changes.filter((c) => c.kind === kind).map((c) => c.id)).size;\n return { description: members.description, members: members.current().length, claims: ids(\"claim\"), questions: ids(\"question\") };\n}\n\nfunction briefing(dataDir: string, names: string[], writeTo: string | undefined): string {\n const lines: string[] = [];\n for (const name of names) {\n const s = summary(dataDir, name);\n const who = s.members > 1 ? `shared with ${plural(s.members - 1, \"other member\")}` : \"only this machine's person so far\";\n lines.push(`Vine Context: this chat uses the shared context \"${name}\" (${who}).`);\n lines.push(s.description ? `What it is for: ${s.description}` : \"It has no description yet (update_context sets one).\");\n lines.push(`${plural(s.claims, \"claim\")} and ${plural(s.questions, \"question\")} have been recorded in it.`);\n }\n if (names.length > 1 && writeTo) lines.push(`Writes from this chat go to \"${writeTo}\" unless a call names another.`);\n lines.push(\n \"Decisions reached, facts established and questions left open in this chat that fit a context's purpose belong in it, so the other members' agents can use them: \" +\n \"the vine-context tools add_claim and ask_question record them (search first for what is already there; model_guide explains how).\",\n );\n return lines.join(\"\\n\");\n}\n\n/** The text to add to the model's context, or nothing. */\nexport function hookText(o: HookOptions): string | undefined {\n const env = o.env ?? process.env;\n const mode = (env.VINE_HOOKS ?? \"\").toLowerCase();\n if (/^(0|off|false|no)$/.test(mode)) return undefined;\n const quiet = mode === \"quiet\";\n\n const i = o.input;\n const chat = str(i.session_id) ?? str(i.sessionId) ?? str(i.conversation_id) ?? str(i.conversationId) ?? chatIdFromEnv(env);\n const cwd = str(i.cwd) ?? first(i.workspace_roots) ?? first(i.workspacePaths) ?? str(i.workspaceRoot) ?? o.cwd ?? process.cwd();\n const { names, writeTo } = chatContexts(o, chat, cwd);\n if (!names.length) return undefined;\n const now = (o.now ?? new Date()).toISOString();\n\n const marks = chat ? chatMarks(o.dataDir, chat) : { seen: {}, briefed: [] };\n const parts: string[] = [];\n\n // What it's for: at the start of a session (and again after a compaction or a resume, when the earlier telling is gone), and for a context the chat picked up since.\n const unbriefed = o.event === \"session-start\" ? names : names.filter((n) => !marks.briefed.includes(n));\n if (unbriefed.length) parts.push(briefing(o.dataDir, o.event === \"session-start\" ? names : unbriefed, writeTo));\n\n if (o.event === \"prompt\" && chat) {\n let shown = 0;\n let more = 0;\n for (const name of names) {\n const fresh = unseenNews(o.dataDir, chat, name);\n if (!fresh.length) continue;\n const lines = fresh.flatMap((e) => e.lines);\n const room = Math.max(0, MAX_NEWS_LINES - shown);\n if (room) parts.push([`Vine Context, new from other members of \"${name}\":`, ...lines.slice(0, room).map((l) => `- ${l}`)].join(\"\\n\"));\n shown += Math.min(room, lines.length);\n more += Math.max(0, lines.length - room);\n markSeen(o.dataDir, chat, name, fresh.at(-1)!.at);\n }\n if (more) parts.push(`…and ${more} more (the recent tool lists them).`);\n }\n\n if (o.event === \"prompt\" && !unbriefed.length && !quiet && writeTo) {\n parts.push(`Vine Context: this chat records to \"${writeTo}\". Decisions and open questions from this work that fit its purpose belong there (add_claim, ask_question).`);\n }\n\n if (chat) {\n updateChatMarks(o.dataDir, chat, (m) => {\n // A chat is told news from when it first has the context, not the context's whole past.\n for (const n of names) m.seen[n] ??= now;\n for (const n of unbriefed) if (!m.briefed.includes(n)) m.briefed.push(n);\n });\n }\n return parts.length ? parts.join(\"\\n\\n\") : undefined;\n}\n\nconst EVENT_NAMES: Record<HookEvent, string> = { \"session-start\": \"SessionStart\", prompt: \"UserPromptSubmit\" };\n\n/** The hook's stdout: the text in the shape Claude Code, Codex and Gemini CLI read. Empty when there is nothing to say. */\nexport function hookOutput(o: HookOptions): string {\n const text = hookText(o);\n if (!text) return \"\";\n return JSON.stringify({ hookSpecificOutput: { hookEventName: str(o.input.hook_event_name) ?? EVENT_NAMES[o.event], additionalContext: text } });\n}\n\nasync function readStdin(): Promise<string> {\n if (process.stdin.isTTY) return \"\";\n const chunks: Buffer[] = [];\n for await (const c of process.stdin) chunks.push(c as Buffer);\n return Buffer.concat(chunks).toString(\"utf8\");\n}\n\nexport async function hookCommand(args: string[]): Promise<number> {\n const event = args[0];\n if (event !== \"session-start\" && event !== \"prompt\") {\n console.error(\"Usage: vine hook session-start|prompt (reads the agent's hook JSON on stdin)\");\n return 0; // never a failing hook: a non-zero exit can block the person's prompt\n }\n try {\n let input: Record<string, unknown> = {};\n try {\n const parsed = JSON.parse(await readStdin());\n if (parsed && typeof parsed === \"object\") input = parsed as Record<string, unknown>;\n } catch {\n // no stdin, or not JSON: the chat's id may still come from the environment\n }\n const out = hookOutput({ event, input, dataDir: defaultDataDir() });\n if (out) process.stdout.write(out + \"\\n\");\n } catch {\n // say nothing\n }\n return 0;\n}\n","import { parseArgs } from \"node:util\";\nimport { packageInfo } from \"../core/package-root.js\";\n\nconst pkg = packageInfo();\nconst [command, ...rest] = process.argv.slice(2);\n\nconst USAGE = `vine ${pkg.version}: a shared context graph of claims and questions, replicated peer to peer between people's AI agents\n\nUsage: vine <command> [options]\n\nCommands:\n setup [--yes] [--agent claude|codex|none] [--turn cloudflare|custom|none] [--json] [--dry-run]\n Set this machine up, or repair it: vine, your agents' plugin, your name, checks, TURN, autostart\n mcp [--context NAME] Run the MCP server on stdio (a chat keeps the context it chose; a new chat starts with its folder's linked context, else NAME, else none until one is chosen)\n host [--context NAME] [--share] [--idle SECONDS]\n Run a context's host in the foreground (--share prints a new join code)\n host stop [--context NAME] Stop a context's host\n up Start the host of every context on this machine that is sharing (in the background)\n autostart on|off Run \\`vine up\\` at login (macOS), so your contexts sync after a reboot\n demo [--pace SECONDS] [--join] [--port N] [--no-open] [--verbose]\n Three members in one process replay the example, syncing peer to peer (nothing of yours changes; --join lets your agent join)\n ui [--context NAME] [--port N] [--open]\n Show the console and explorer in a browser\n status [--context NAME] Show a context's host: sharing, members, links, relays, invites\n turn set --provider cloudflare [--key-id ID | --account ID]\n Use Cloudflare's TURN server, with a TURN key on your own Cloudflare account (kept in your keychain)\n turn set HOST[:PORT] --user NAME [--tcp | --tls] [--store file|keychain|env]\n Set a TURN server of your own, for members whose networks block direct connections (asks for the password)\n turn show | test | clear Show, check or remove the TURN server\n whoami Show your name and key fingerprint\n hook session-start|prompt What an agent's hook runs: reads the hook's JSON on stdin, prints the chat's context and other members' news for the model\n doctor Check that this machine can run vine\n --version Print the version\n\nEnvironment:\n VINE_USER Your name in contexts (default: the name you set (update_context, or vine setup), else git's user.name, else your computer account's full name, else your login name, else a made-up one)\n VINE_CONTEXT The context a new chat starts with when its folder has none linked (default: none; the agent asks)\n VINE_CHAT The chat's id, to remember its context (default: Claude Code's session id)\n VINE_DATA_DIR Where contexts live (default: ~/.local/share/vine-context)\n VINE_EMBEDDER How search turns text into vectors: auto (default: bge-small when its package works here, else hash), hash, bge-small, or minilm once built with \\`npm run build:embedder\\`\n VINE_AUTO_SHARE off: new contexts don't sync until you share them\n VINE_HOOKS off: the agent hooks say nothing; quiet: no reminder beside each prompt (the session's briefing and others' news stay)\n VINE_HOLD_MS How long a write stays on this machine (Undo) before it is sent (default 10000)\n VINE_RELAYS Nostr relays for signalling, comma-separated\n VINE_ICE STUN/TURN servers, comma-separated; replaces the defaults and the \\`vine turn\\` setting\n VINE_TURN_PASSWORD The TURN server's password, when it was set with --store env\n VINE_CLOUDFLARE_TURN_SECRET The Cloudflare TURN key's secret, when it was set with --store env`;\n\n// USAGE's lines for one command: the line that starts with its name, and the lines that continue it.\nfunction commandUsage(cmd: string): string | undefined {\n const lines = USAGE.split(\"\\n\");\n const out: string[] = [];\n let inCmd = false;\n for (const line of lines.slice(lines.indexOf(\"Commands:\") + 1)) {\n if (line === \"\") break;\n if (/^ \\S/.test(line)) inCmd = line.startsWith(` ${cmd} `);\n if (inCmd) out.push(line);\n }\n return out.length ? `Usage: vine <command> [options]\\n\\n${out.join(\"\\n\")}\\n\\nRun \\`vine help\\` for every command and the environment variables.` : undefined;\n}\n\nconst graphOpts = { graph: { type: \"string\" }, context: { type: \"string\" } } as const;\nconst graphName = (v?: string): string => {\n const name = v ?? process.env.VINE_CONTEXT ?? process.env.VINE_GRAPH;\n if (name) return name;\n console.error(\"Name a context with --context NAME (there's no default context).\");\n process.exit(2);\n};\n\nasync function sessionFactory(values: { graph?: string; context?: string }) {\n const [{ Session }, { chatIdFromEnv }, { ensureHost }, { defaultDataDir }, { loadIdentity, defaultName }, signal] = await Promise.all([\n import(\"../mcp/server.js\"),\n import(\"../mcp/links.js\"),\n import(\"../host/client.js\"),\n import(\"../core/graph.js\"),\n import(\"../core/identity.js\"),\n import(\"../p2p/signal.js\"),\n ]);\n const { storedIce } = await import(\"../p2p/ice.js\");\n const dataDir = defaultDataDir();\n // A chat keeps the context it chose (by its id); a new one starts with its folder's linked context, or one named here; there's no default.\n const graph = values.context ?? values.graph ?? process.env.VINE_CONTEXT ?? process.env.VINE_GRAPH;\n const log = (m: string) => console.error(`vine: ${m}`);\n let ui: Promise<{ url: string }> | undefined;\n const make = (withBrowserView: boolean): InstanceType<typeof Session> =>\n new Session({\n local: graph ? () => ensureHost({ dataDir, graph }) : undefined,\n cwd: process.cwd(),\n chat: chatIdFromEnv(),\n openLocal: (g) => ensureHost({ dataDir, graph: g }),\n dataDir,\n identity: () => loadIdentity(dataDir, defaultName(dataDir)),\n signal: signal.nostrSignaller,\n ice: storedIce(dataDir),\n log,\n browserView: withBrowserView\n ? async () => {\n ui ??= import(\"../ui/server.js\").then(({ startUi }) => startUi({ session: () => make(false), log }));\n return (await ui).url;\n }\n : undefined,\n });\n return { make, graph, log };\n}\n\nasync function mcp(args: string[]) {\n const { values } = parseArgs({ args, options: graphOpts });\n const { StdioServerTransport } = await import(\"@modelcontextprotocol/sdk/server/stdio.js\");\n const { make, graph, log } = await sessionFactory(values);\n const session = make(true);\n await session.start();\n await session.server.connect(new StdioServerTransport());\n log(`session ready on stdio${graph ? ` (context '${graph}')` : \"\"}`);\n}\n\nasync function demo(args: string[]): Promise<number> {\n const { values } = parseArgs({\n args,\n options: { port: { type: \"string\" }, \"no-open\": { type: \"boolean\" }, pace: { type: \"string\" }, join: { type: \"boolean\" }, verbose: { type: \"boolean\" } },\n });\n const [{ startDemo }, { GRAPH_NAME }, { nostrSignaller }, { storedIce }, { defaultDataDir }] = await Promise.all([import(\"../demo/live.js\"), import(\"../demo/scenario.js\"), import(\"../p2p/signal.js\"), import(\"../p2p/ice.js\"), import(\"../core/graph.js\")]);\n const pace = values.pace === undefined ? 4 : Number(values.pace);\n if (!Number.isFinite(pace) || pace < 0) {\n console.error(\"--pace is seconds between steps, 0 or more.\");\n return 2;\n }\n console.log(`vine-context demo: three people, three hosts, one process\n alice, bob and carol plan the office Christmas party, each from their own copy of the context 'party'.\n Every write goes through its author's host: signed, held for undo, then carried to the other two over WebRTC.\n ${values.join ? \"They find each other through the public Nostr relays, so your agent can join too.\" : \"They find each other in this process: no network is needed, and nothing leaves this machine.\"}\n`);\n const demo = await startDemo({\n paceMs: pace * 1000,\n narrate: (line) => console.log(line),\n log: values.verbose ? (m) => console.error(` [${m}]`) : undefined,\n // With --join the members use the relays and this machine's STUN/TURN setting, as any host does.\n ...(values.join ? { signal: nostrSignaller, ice: storedIce(defaultDataDir()) } : {}),\n });\n const alice = demo.members.alice;\n\n // The browser shows alice's point of view: her console, explorer and conflicts.\n process.env.VINE_DATA_DIR = alice.dataDir;\n process.env.VINE_USER = \"alice\";\n const { make, log } = await sessionFactory({ graph: GRAPH_NAME });\n const { startUi } = await import(\"../ui/server.js\");\n const server = await startUi({ session: () => make(false), port: values.port ? Number(values.port) : undefined, log });\n console.log(`\nOpen this on this machine (it acts as alice; don't share it):\n${server.url}\n\nSharing console: the three members and their live links. Explore a context: the graph as it grows; drag the time slider back to replay it. Conflicts: bob and carol, until bob gives way.\n`);\n if (!values[\"no-open\"]) {\n const { spawn } = await import(\"node:child_process\");\n const cmd = process.platform === \"darwin\" ? \"open\" : process.platform === \"win32\" ? \"explorer\" : \"xdg-open\";\n spawn(cmd, [server.url], { stdio: \"ignore\", detached: true }).on(\"error\", () => undefined).unref();\n }\n\n let stopping = false;\n const stop = async () => {\n if (stopping) return;\n stopping = true;\n await server.close();\n await demo.stop();\n process.exit(0);\n };\n process.on(\"SIGINT\", () => void stop());\n process.on(\"SIGTERM\", () => void stop());\n\n try {\n await demo.story;\n } catch (e) {\n console.error(`The story stopped: ${(e as Error).message}`);\n await stop();\n return 1;\n }\n console.log(`\nThe story is over, and the three hosts stay up. To point an agent at alice's copy:\n VINE_DATA_DIR=${alice.dataDir} vine mcp --context ${GRAPH_NAME}`);\n if (values.join) {\n const { code } = await alice.local.request<{ code: string }>(\"share\", { label: \"demo guest\", role: \"contributor\" });\n console.log(`\nTo join as a fourth member from any machine, tell your agent:\n /vine-context:join ${code}`);\n }\n console.log(\"\\nCtrl-C stops the demo.\");\n return -1;\n}\n\nasync function ui(args: string[]): Promise<number> {\n const { values } = parseArgs({ args, options: { ...graphOpts, port: { type: \"string\" }, open: { type: \"boolean\" } } });\n const { make, log } = await sessionFactory(values);\n const { startUi } = await import(\"../ui/server.js\");\n const server = await startUi({ session: () => make(false), port: values.port ? Number(values.port) : undefined, log });\n console.log(`Open this on this machine (it acts as you; don't share it):\\n${server.url}`);\n if (values.open) {\n const { spawn } = await import(\"node:child_process\");\n const cmd = process.platform === \"darwin\" ? \"open\" : process.platform === \"win32\" ? \"explorer\" : \"xdg-open\";\n spawn(cmd, [server.url], { stdio: \"ignore\", detached: true }).unref();\n }\n const stop = () => void server.close().then(() => process.exit(0));\n process.on(\"SIGINT\", stop);\n process.on(\"SIGTERM\", stop);\n return -1;\n}\n\nasync function host(args: string[]): Promise<number> {\n if (args[0] === \"stop\") {\n const { values } = parseArgs({ args: args.slice(1), options: graphOpts });\n const [{ LocalHost }, { socketPath }, { defaultDataDir }] = await Promise.all([\n import(\"../host/client.js\"),\n import(\"../host/state.js\"),\n import(\"../core/graph.js\"),\n ]);\n try {\n const c = await LocalHost.connect(socketPath(defaultDataDir(), graphName(values.context ?? values.graph)));\n await c.request(\"shutdown\");\n c.close();\n console.log(\"Host stopped.\");\n return 0;\n } catch {\n console.log(\"No host is running for that context.\");\n return 1;\n }\n }\n const { values } = parseArgs({ args, options: { ...graphOpts, share: { type: \"boolean\" }, idle: { type: \"string\" } } });\n const [{ Host, HostRunningError }, { defaultDataDir }, { defaultName }] = await Promise.all([\n import(\"../host/host.js\"),\n import(\"../core/graph.js\"),\n import(\"../core/identity.js\"),\n ]);\n const log = (m: string) => console.error(`[${new Date().toISOString()}] ${m}`);\n try {\n const h = await Host.start({\n dataDir: defaultDataDir(),\n graph: graphName(values.context ?? values.graph),\n user: defaultName(defaultDataDir()),\n idleSeconds: values.idle ? Number(values.idle) : 0,\n log,\n onStop: () => process.exit(0),\n });\n log(`host for graph '${h.graph.name}' on ${h.socket}`);\n if (values.share) console.log(h.share().code);\n const stop = () => h.stop();\n process.on(\"SIGINT\", stop);\n process.on(\"SIGTERM\", stop);\n return -1; // keep running\n } catch (e) {\n if (e instanceof HostRunningError) {\n console.error(e.message);\n return 3;\n }\n throw e;\n }\n}\n\nasync function status(args: string[]): Promise<number> {\n const { values } = parseArgs({ args, options: graphOpts });\n const [{ LocalHost }, { socketPath }, { defaultDataDir }] = await Promise.all([\n import(\"../host/client.js\"),\n import(\"../host/state.js\"),\n import(\"../core/graph.js\"),\n ]);\n try {\n const c = await LocalHost.connect(socketPath(defaultDataDir(), graphName(values.context ?? values.graph)));\n const st = await c.request<Record<string, any>>(\"status\");\n console.log(JSON.stringify(st, null, 2));\n // The one thing in there a person should act on, in words (on stderr: stdout stays JSON).\n if (typeof st.advice === \"string\") console.error(`\\n${st.advice}`);\n c.close();\n return 0;\n } catch {\n console.log(\"No host is running for that context.\");\n return 1;\n }\n}\n\nasync function whoami(): Promise<number> {\n const [{ loadIdentity, defaultName, fingerprint }, { defaultDataDir }] = await Promise.all([\n import(\"../core/identity.js\"),\n import(\"../core/graph.js\"),\n ]);\n const id = loadIdentity(defaultDataDir(), defaultName(defaultDataDir()));\n console.log(`${id.name} ${fingerprint(id.publicKey)}`);\n return 0;\n}\n\n/** Reads a password: typed unseen at a terminal, or the first line of piped input. */\nasync function readPassword(prompt: string): Promise<string> {\n const { readHidden } = await import(\"./prompt.js\");\n return readHidden(prompt);\n}\n\nconst TURN_USAGE = `Usage:\n vine turn set --provider cloudflare [--key-id ID | --account ID] [--store keychain|env]\n vine turn set HOST[:PORT] --user NAME [--tcp | --tls] [--store file|keychain|env]\n vine turn show\n vine turn test\n vine turn clear`;\n\n/** The TURN server this machine's links may go through when a direct connection isn't possible. */\nasync function turn(args: string[]): Promise<number> {\n const [ice, { SECRET_STORES }, { defaultDataDir }] = await Promise.all([import(\"../p2p/ice.js\"), import(\"../core/secret.js\"), import(\"../core/graph.js\")]);\n const dataDir = defaultDataDir();\n const report = async (): Promise<number> => {\n const r = await ice.checkStoredTurn(dataDir);\n console.log(r.ok ? `ok The server answered and lent a relay address (${r.relay}).` : `FAIL ${r.error}`);\n return r.ok ? 0 : 1;\n };\n switch (args[0]) {\n case \"set\": {\n const { values, positionals } = parseArgs({\n args: args.slice(1),\n allowPositionals: true,\n options: {\n user: { type: \"string\" },\n tcp: { type: \"boolean\" },\n tls: { type: \"boolean\" },\n store: { type: \"string\" },\n provider: { type: \"string\" },\n \"key-id\": { type: \"string\" },\n account: { type: \"string\" },\n },\n });\n if (values.provider !== undefined && values.provider !== \"custom\") {\n if (values.provider !== \"cloudflare\" || positionals.length || values.user || values.tcp || values.tls || (values.store && ![\"keychain\", \"env\"].includes(values.store))) {\n console.error(TURN_USAGE);\n return 2;\n }\n const [{ setupCloudflare }, { terminalPrompter }] = await Promise.all([import(\"./cloudflare-setup.js\"), import(\"./prompt.js\")]);\n const r = await setupCloudflare({\n dataDir,\n prompt: terminalPrompter(),\n say: (l) => console.log(l),\n keyId: values[\"key-id\"],\n accountId: values.account,\n ...(values.account ? { via: \"token\" as const } : values[\"key-id\"] ? { via: \"key\" as const } : {}),\n store: values.store as \"keychain\" | \"env\" | undefined,\n });\n if (!r.ok) {\n console.log(`FAIL ${r.error}`);\n return 1;\n }\n console.log(`ok Cloudflare lent a relay address (${r.relay}). New connections use it when a direct one isn't possible; nothing needs restarting.`);\n return 0;\n }\n const store = (values.store ?? \"file\") as (typeof SECRET_STORES)[number];\n if (positionals.length !== 1 || !values.user || (values.tcp && values.tls) || !SECRET_STORES.includes(store)) {\n console.error(TURN_USAGE);\n return 2;\n }\n try {\n const { host, port } = ice.parseHostPort(positionals[0]!);\n const password = store === \"env\" ? undefined : await readPassword(`Password for ${values.user} on ${host}: `);\n const t = ice.saveTurn(dataDir, { host, port, username: values.user, transport: values.tls ? \"tls\" : values.tcp ? \"tcp\" : \"udp\", store, password });\n const kept = { file: \"in a file only you can read\", keychain: \"in your keychain\", env: `nowhere: set ${ice.TURN_PASSWORD_ENV} where vine runs` }[t.store];\n console.log(`TURN server set: ${t.host}:${t.port} (${t.transport}), user ${t.username}. Password kept ${kept}.`);\n console.log(\"New connections use it from now on; nothing needs restarting.\");\n } catch (e) {\n console.error((e as Error).message);\n return 1;\n }\n return report();\n }\n case \"show\": {\n await ice.refreshIce(dataDir);\n const s = ice.resolveIce(dataDir).summary;\n const t = ice.readTurn(dataDir);\n const cf = ice.readCloudflare(dataDir);\n if (s.source === \"env\") console.log(`VINE_ICE is set, and replaces the setting here: ${[...s.stun, ...(s.turn ? [s.turn] : [])].join(\", \") || \"no servers\"}`);\n else if (cf)\n console.log(\n `TURN server: ${s.turn}. Provider: Cloudflare, key ${cf.name ? `\"${cf.name}\" ` : \"\"}…${cf.keyId.slice(-4)}, secret in ${cf.store === \"keychain\" ? \"your keychain\" : ice.CLOUDFLARE_SECRET_ENV}.` +\n (s.expires ? `\\nShort-lived credentials minted, valid until ${s.expires}; renewed automatically.` : \"\") +\n (s.problem ? `\\nNot in use: ${s.problem}.` : \"\"),\n );\n else if (!t) console.log(\"No TURN server is set. Members connect directly. If a member can't connect, `vine turn set --provider cloudflare` sets up Cloudflare's on your own account.\");\n else console.log(`TURN server: ${s.turn}, user ${t.username}, password store: ${t.store}. Provider: your own server.${s.problem ? `\\nNot in use: ${s.problem}.` : \"\"}`);\n return 0;\n }\n case \"test\":\n return report();\n case \"clear\": {\n const cf = ice.readCloudflare(dataDir);\n console.log(ice.clearTurn(dataDir) ? \"TURN server removed. New connections are direct only.\" : \"No TURN server was set.\");\n if (cf) console.log(`The TURN key itself (…${cf.keyId.slice(-4)}) is still on your Cloudflare account: delete it in the dashboard if you won't use it again.`);\n return 0;\n }\n default:\n console.log(TURN_USAGE);\n return args[0] ? 2 : 0;\n }\n}\n\nasync function doctor(): Promise<number> {\n const { runDoctor } = await import(\"./doctor.js\");\n const r = await runDoctor({ print: (l) => console.log(l) });\n console.log(r.failed ? `\\n${r.failed} check(s) failed.` : \"\\nAll checks passed.\");\n return r.failed ? 1 : 0;\n}\n\n/** Starts the host of every graph here that is sharing, so they sync without an agent open. */\nasync function up(): Promise<number> {\n const [{ existsSync, readdirSync, readFileSync }, { join }, { ensureHost }, { defaultDataDir }] = await Promise.all([\n import(\"node:fs\"),\n import(\"node:path\"),\n import(\"../host/client.js\"),\n import(\"../core/graph.js\"),\n ]);\n const { autoShare } = await import(\"../core/paths.js\");\n const dataDir = defaultDataDir();\n const dir = join(dataDir, \"graphs\");\n const graphs = existsSync(dir) ? readdirSync(dir).filter((n) => /^[a-z0-9][a-z0-9-]{0,62}$/.test(n)) : [];\n let started = 0;\n for (const g of graphs) {\n let on = autoShare();\n try {\n on = JSON.parse(readFileSync(join(dataDir, \"hosts\", g, \"sharing.json\"), \"utf8\")).on === true;\n } catch {\n // no setting: the default\n }\n if (!on) continue;\n try {\n // idle 0: a sharing host stays up anyway; this keeps it up for the members.\n const c = await ensureHost({ dataDir, graph: g, idleSeconds: 0 });\n c.close();\n started++;\n console.log(`up: ${g}`);\n } catch (e) {\n console.error(`${g}: ${(e as Error).message}`);\n }\n }\n console.log(`${started} graph host(s) running.`);\n return 0;\n}\n\n/** A macOS launch agent that runs `vine up` at login. */\nasync function autostart(args: string[]): Promise<number> {\n const [sub] = args;\n const [{ existsSync, mkdirSync, unlinkSync, writeFileSync }, { homedir }, { join }] = await Promise.all([import(\"node:fs\"), import(\"node:os\"), import(\"node:path\")]);\n const label = \"dev.vine.up\";\n if (process.platform !== \"darwin\") {\n console.log(\"autostart is for macOS. Elsewhere, run `vine up` from your login scripts (for example a systemd user service).\");\n return sub === \"on\" || sub === \"off\" ? 1 : 2;\n }\n const plist = join(homedir(), \"Library\", \"LaunchAgents\", `${label}.plist`);\n if (sub === \"off\") {\n if (existsSync(plist)) unlinkSync(plist);\n console.log(`Removed ${plist}. Your graphs sync only while an agent (or \\`vine up\\`) runs them.`);\n return 0;\n }\n if (sub !== \"on\") {\n console.error(\"Usage: vine autostart on|off\");\n return 2;\n }\n const esc = (v: string) => v.replace(/&/g, \"&\").replace(/</g, \"<\");\n const args2 = [process.execPath, ...process.execArgv, process.argv[1]!, \"up\"];\n mkdirSync(join(homedir(), \"Library\", \"LaunchAgents\"), { recursive: true });\n writeFileSync(\n plist,\n `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\"><dict>\n <key>Label</key><string>${label}</string>\n <key>ProgramArguments</key><array>${args2.map((a) => `<string>${esc(a)}</string>`).join(\"\")}</array>\n <key>RunAtLoad</key><true/>\n <key>EnvironmentVariables</key><dict>${process.env.VINE_DATA_DIR ? `<key>VINE_DATA_DIR</key><string>${esc(process.env.VINE_DATA_DIR)}</string>` : \"\"}</dict>\n</dict></plist>\n`,\n );\n console.log(`Wrote ${plist}: \\`vine up\\` runs at each login. \\`vine autostart off\\` removes it.`);\n return 0;\n}\n\nconst helpFlag = (a: string) => a === \"--help\" || a === \"-h\";\nconst isParseArgsError = (e: unknown) => String((e as { code?: unknown })?.code ?? \"\").startsWith(\"ERR_PARSE_ARGS\");\n\n// `vine setup` prints its own, longer help.\nconst help = command && command !== \"setup\" && rest.some(helpFlag) ? commandUsage(command) : undefined;\nif (help) {\n console.log(help);\n} else {\n try {\n await run();\n } catch (e) {\n if (!isParseArgsError(e)) throw e;\n // A mistyped option: say which, and how the command is used, without a stack trace.\n console.error(`${(e as Error).message}\\n\\n${(command && commandUsage(command)) ?? USAGE}`);\n process.exitCode = 2;\n }\n}\n\nasync function run(): Promise<void> {\nswitch (command) {\n case \"--version\":\n case \"-v\":\n console.log(pkg.version);\n break;\n case \"mcp\":\n await mcp(rest);\n break;\n case \"host\": {\n const code = await host(rest);\n if (code >= 0) process.exitCode = code;\n break;\n }\n case \"demo\": {\n const code = await demo(rest);\n if (code >= 0) process.exitCode = code;\n break;\n }\n case \"ui\": {\n const code = await ui(rest);\n if (code >= 0) process.exitCode = code;\n break;\n }\n case \"status\":\n process.exitCode = await status(rest);\n break;\n case \"whoami\":\n process.exitCode = await whoami();\n break;\n case \"setup\": {\n const { setupCommand } = await import(\"./setup.js\");\n process.exitCode = await setupCommand(rest);\n break;\n }\n case \"doctor\":\n process.exitCode = await doctor();\n break;\n case \"hook\": {\n const { hookCommand } = await import(\"./hook.js\");\n process.exitCode = await hookCommand(rest);\n break;\n }\n case \"turn\":\n process.exitCode = await turn(rest);\n break;\n case \"up\":\n process.exitCode = await up();\n break;\n case \"autostart\":\n process.exitCode = await autostart(rest);\n break;\n default:\n console.log(USAGE);\n if (command && command !== \"help\" && !helpFlag(command)) process.exitCode = 2;\n}\n}\n"],"mappings":";;;;;;;;;;;;AAAA,SAAS,YAAY,oBAAoB;AACzC,SAAS,SAAS,YAAY;AAC9B,SAAS,qBAAqB;AAMvB,SAAS,cAAsB;AACpC,MAAI,KAAM,QAAO;AACjB,MAAI,MAAM,QAAQ,cAAc,YAAY,GAAG,CAAC;AAChD,aAAS;AACP,UAAMA,QAAO,KAAK,KAAK,cAAc;AACrC,QAAI,WAAWA,KAAI,KAAK,KAAK,MAAM,aAAaA,OAAM,MAAM,CAAC,EAAE,SAAS,eAAgB,QAAQ,OAAO;AACvG,UAAM,SAAS,QAAQ,GAAG;AAC1B,QAAI,WAAW,IAAK,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Q;AACX,YAAM,EAAE,aAAAC,aAAY,IAAI,MAAM;AAC9B,cAAQ,WAAW,MAAMA,aAAY,IAAI;AACzC;AAAA,IACF;AAAA,IACA,KAAK;AACH,cAAQ,WAAW,MAAM,KAAK,IAAI;AAClC;AAAA,IACF,KAAK;AACH,cAAQ,WAAW,MAAM,GAAG;AAC5B;AAAA,IACF,KAAK;AACH,cAAQ,WAAW,MAAM,UAAU,IAAI;AACvC;AAAA,IACF;AACE,cAAQ,IAAI,KAAK;AACjB,UAAI,WAAW,YAAY,UAAU,CAAC,SAAS,OAAO,EAAG,SAAQ,WAAW;AAAA,EAChF;AACA;","names":["file","text","tag","createHash","existsSync","readFileSync","dirname","join","file","randomBytes","rest","createHash","existsSync","dirname","join","text","spec","sign","existsSync","readFileSync","join","text","file","label","join","v","mkdirSync","join","z","db","label","text","q","run","toolName","rest","digest","names","host","line","resolve","createHash","randomBytes","chmodSync","existsSync","mkdirSync","readFileSync","writeFileSync","join","h","join","resolve","existsSync","mkdirSync","readFileSync","renameSync","writeFileSync","dirname","join","line","h","text","platform","account","run","hostname","relayType","turn","chmodSync","mkdirSync","readFileSync","renameSync","writeFileSync","join","file","stamp","turn","usable","problem","resolve","randomBytes","nodeDataChannel","resolve","randomBytes","nodeDataChannel","fresh","resolve","EventEmitter","tag","text","shown","mkdirSync","readFileSync","renameSync","writeFileSync","dirname","join","file","createHash","randomBytes","chmodSync","existsSync","mkdirSync","readFileSync","renameSync","writeFileSync","createConnection","dirname","join","resolve","file","host","run","fresh","text","label","write","line","held","turn","randomBytes","nodeDataChannel","resolve","existsSync","readFileSync","statSync","join","existsSync","mkdirSync","readdirSync","readFileSync","renameSync","writeFileSync","dirname","join","resolve","NAME_RE","root","existsSync","statSync","join","run","names","text","spawn","existsSync","renameSync","rmSync","join","z","failure","host","tag","names","out","Catalogue","first","rest","status","run","summary","state","snap","server_exports","randomBytes","timingSafeEqual","readFileSync","createServer","join","readJson","resolve","status","init_server","EventEmitter","tmpdir","join","root","host","m","line","first","resolve","q","spawn","keychainTool","randomBytes","WebSocket","resolve","first","pkg","loadRelate","claimsPack","chooseEmbedder","defaultDataDir","mkdirSync","summary","checkNetwork","spawnSync","line","defaultDataDir","existsSync","homedir","join","runDoctor","checkNetwork","setupCloudflare","keychainTool","host","parseArgs","turn","terminalPrompter","defaultsPrompter","existsSync","readFileSync","join","names","file","line","briefing","str","shown","fresh","text","line","Session","chatIdFromEnv","ensureHost","defaultDataDir","loadIdentity","defaultName","storedIce","ui","startUi","startDemo","GRAPH_NAME","nostrSignaller","demo","spawn","values","LocalHost","socketPath","Host","HostRunningError","fingerprint","readHidden","SECRET_STORES","setupCloudflare","terminalPrompter","host","runDoctor","existsSync","readdirSync","readFileSync","join","autoShare","mkdirSync","unlinkSync","writeFileSync","homedir","label","run","setupCommand","hookCommand"]}
|