pi-studio 0.11.6 → 0.11.7

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-studio",
3
- "version": "0.11.6",
3
+ "version": "0.11.7",
4
4
  "description": "Two-pane browser workspace for pi with prompt/response editing, annotations, critiques, active quiz, prompt/response history, live previews, and tmux-backed REPL/literate REPL workflows",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -8,6 +8,7 @@ Compatible clients inspect two tmux session options:
8
8
 
9
9
  - `@pi_repl_record_id`: 32 lowercase hexadecimal characters
10
10
  - `@pi_repl_record_version`: `1`
11
+ - `@pi_repl_record_root_key`: which record directory holds the record (see "One record directory per session")
11
12
 
12
13
  A client creating metadata uses tmux `set-option -o`, so concurrent first writers cannot replace an ID already chosen by another client. The option contains an opaque ID, never a filesystem path.
13
14
 
@@ -53,6 +54,59 @@ The record is a bounded JSON snapshot:
53
54
 
54
55
  Each entry has a stable `id`, optional `requestId`, timestamps, session/runtime identity, `origin` (`pi-repl` or `pi-studio`), a presentation `label`, `mode` (`raw`, `literate`, or `agent`), prose, code, cleaned output, status, and skipped/truncation metadata.
55
56
 
57
+ ## One record directory per session
58
+
59
+ The record directory is under the operating system's temporary directory, which can differ between terminals of one account: an ssh login and a desktop terminal can have different `TMPDIR` values. Clients in each would otherwise keep separate records and separate send leases for one session. So a session records which directory holds its record, and clients refuse a different one. This adds a tmux option, not a record field, and keeps version 1.
60
+
61
+ **The key.** `@pi_repl_record_root_key` holds `v1:` and the first 32 lowercase hexadecimal characters of the SHA-256 of `<device>:<inode>` of the record directory, both written as exact decimal integers (from a `bigint` stat), after the directory passes the checks above. It is not a path, and different spellings of one directory give the same key. Any other value is malformed: clients refuse it and never replace it. Test vectors:
62
+
63
+ | `<device>:<inode>` | Key |
64
+ |---|---|
65
+ | `0:0` | `v1:ac72368a586a18c19088393573ce0307` |
66
+ | `16777232:1234567` | `v1:1e42c564492d3e74e2ef33a98ea2fc21` |
67
+ | `18446744073709551615:9223372036854775813` | `v1:eb75db16e5ba9caa199d69d116a8ac77` |
68
+
69
+ **Writers,** clients that set a session's metadata, write its record or take its lease:
70
+
71
+ 1. **Fresh metadata.** The key comes first. A writer sets it with `set-option -o` before the record ID, the record or the lease, then reads it back and compares it with its own: a set that succeeds doesn't prove it won. So an upgraded writer never leaves a record ID without a key.
72
+ 2. **A record ID without a key** was made by an older client. A writer sets the key, as in 1, only if its own directory already holds a valid record for this exact session (name, tmux session ID and creation time, as stored, not normalised), read without creating, locking or repairing anything, its directory included. Otherwise it refuses, and it never creates a directory or an empty record to claim the session. This doesn't prove that no split happened earlier: if older clients made valid copies in two directories, either qualifies, and the key chooses where upgraded writers go from then on.
73
+ 3. **A key** that doesn't name the writer's own directory, or is malformed, is refused. This holds even when the rest of the metadata can't be used (an invalid record ID, an unsupported version), which the writer leaves as it is.
74
+
75
+ A read of the metadata that fails is never taken for metadata that isn't there: only tmux's answer that an option is unset counts as unset.
76
+
77
+ Reads of the key are bound to the session's exact lifetime (session ID and creation time). A writer checks the key again where it uses the record or lease, including after waiting for the lease, and recomputes its own key there, so a replaced directory is found. On any failure it refuses before sending, and never falls back to an unsynchronised send.
78
+
79
+ **Readers,** such as status views, exports, previews and history tools, never set the key, create a directory, record or lock, or change a mode. With a matching key, they read as usual. With a different or malformed key, they refuse, with a notice. With no key, they may show a strictly validated local record, with a "record directory not verified" notice.
80
+
81
+ **What it guarantees.** It detects a client whose record directory is a different directory from the one the session's record was made in. A replaced directory, for example after temporary-file cleanup, almost always has a new inode, so it is refused too, but reuse of the same device and inode can't be detected. Refusals say "different or replaced record directory" rather than naming one cause. The remedy is the person's: use a terminal with the same temporary directory, or restart the session, which discards its state. Clients never move a session between directories or repair its key.
82
+
83
+ **Rollout.** Older clients ignore the key, so the check holds only among upgraded clients until every client is updated.
84
+
85
+ ## People's sends
86
+
87
+ These are conventions within version 1. They add no fields, so older writers keep them.
88
+
89
+ **The route rule.** An entry with `mode: "agent"` came through an agent's tool. `raw` and `literate` came through a person's command or editor. The rule describes the route, not who was at the keyboard: an agent that runs `agent-repl send` through its shell takes the person's route. A mode that a writer normalised from an unknown value is evidence of neither.
90
+
91
+ **A person's name and channel.** A person's send records the name the person chose as its `label`, and a `requestId` whose prefix gives the channel:
92
+
93
+ | `requestId` prefix | `origin` | Written by | Channel |
94
+ |---|---|---|---|
95
+ | `pi:send:<uuid>`, `pi:env:<uuid>` | `pi-repl` | Pi's `/repl send` and `/repl env` | Pi |
96
+ | `cli:send:<uuid>`, `cli:env:<uuid>` | `pi-repl` | `agent-repl send` and `agent-repl env` | terminal |
97
+ | `studio:send:<uuid>` | `pi-studio` | Pi Studio's editor sends | Pi Studio |
98
+ | `studio:note:<uuid>` | `pi-studio` | both of Pi Studio's note routes, assigned when the note is created | Pi Studio |
99
+
100
+ The label is a chosen name only under one of these prefixes, on its matching origin. The prefix is a hint for display, not identity, authorisation or idempotency, and request IDs stay unique. Names are self-declared, so they suit collaborators who trust each other, not auditing. pi-repl's clients take the name from `PI_REPL_USER_NAME`, then the account's shared setting (`person.json` in `$XDG_CONFIG_HOME/pi-repl/`, else `~/.config/pi-repl/`), then `User`. Names are trimmed, at most 80 characters, with no control characters. Older person entries, with `command:send:` or `command:env:` and labels such as `/repl send`, keep them; records aren't rewritten.
101
+
102
+ **How a reader shows an entry,** in this order:
103
+
104
+ 1. `mode: "agent"`: its label, the agent's name.
105
+ 2. One of the prefixes above, on its matching origin: `<label> · via <channel>`.
106
+ 3. Anything else from a person's route: `User`, with "via Pi Studio" when `origin` is `pi-studio`, and no channel otherwise. Older labels such as `/repl send`, `/repl env`, `REPL send` and Studio's descriptions of what was sent aren't names.
107
+
108
+ Readers escape labels for HTML and for terminals.
109
+
56
110
  ## Concurrency and bounds
57
111
 
58
112
  Record updates take a short cross-process directory lock, read the latest snapshot, upsert by stable entry ID, and replace the snapshot atomically. A stale lock can be recovered. The implementation retains at most 300 entries, bounds individual prose/code/output fields, and caps the serialized record at 16 MiB by dropping the oldest entries first.
@@ -0,0 +1,140 @@
1
+ // The name a person's sends are recorded under, and the request-ID prefixes
2
+ // that say which route they came by (REPL_SESSION_RECORD_PROTOCOL.md,
3
+ // "People's sends"). The name comes from PI_REPL_USER_NAME, then the account's
4
+ // shared setting, then "User". Names are self-declared: they suit
5
+ // collaborators who trust each other, not auditing.
6
+
7
+ import { randomUUID } from "node:crypto";
8
+ import { chmodSync, closeSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
9
+ import { homedir } from "node:os";
10
+ import { dirname, isAbsolute, join } from "node:path";
11
+
12
+ export const DEFAULT_PERSON_NAME = "User";
13
+ export const PERSON_NAME_MAX_CHARS = 80;
14
+ export const PERSON_NAME_ENV = "PI_REPL_USER_NAME";
15
+
16
+ // Control characters, line and paragraph separators, and Unicode's bidirectional controls,
17
+ // which could break or disguise a name where it is shown.
18
+ const UNSHOWABLE = /[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}]/u;
19
+
20
+ /** The shared setting: person.json in $XDG_CONFIG_HOME/pi-repl, else ~/.config/pi-repl. */
21
+ export function getPersonSettingPath(env = process.env) {
22
+ const xdg = env.XDG_CONFIG_HOME;
23
+ const base = xdg && isAbsolute(xdg) ? xdg : join(homedir(), ".config");
24
+ return join(base, "pi-repl", "person.json");
25
+ }
26
+
27
+ /** A name trimmed, or why it can't be one. */
28
+ export function validatePersonName(value) {
29
+ if (typeof value !== "string") return { error: "a name must be text" };
30
+ const name = value.trim();
31
+ if (!name) return { error: "the name is empty" };
32
+ if ([...name].length > PERSON_NAME_MAX_CHARS) return { error: `the name is longer than ${PERSON_NAME_MAX_CHARS} characters` };
33
+ if (UNSHOWABLE.test(name)) return { error: "the name has control characters" };
34
+ return { name };
35
+ }
36
+
37
+ /** The saved name, if the setting holds a valid one. Never writes anything. */
38
+ export function readPersonSetting(env = process.env) {
39
+ const path = getPersonSettingPath(env);
40
+ let text;
41
+ try {
42
+ text = readFileSync(path, "utf8");
43
+ } catch (error) {
44
+ if (error?.code === "ENOENT") return { path };
45
+ return { path, warning: `${path} couldn't be read (${error?.message ?? error}), so it was ignored.` };
46
+ }
47
+ let parsed;
48
+ try {
49
+ parsed = JSON.parse(text);
50
+ } catch {
51
+ return { path, warning: `${path} isn't valid JSON, so it was ignored.` };
52
+ }
53
+ const checked = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? validatePersonName(parsed.name) : { error: "it isn't an object with a name" };
54
+ if (checked.error) return { path, warning: `${path} has no usable name (${checked.error}), so it was ignored.` };
55
+ return { path, name: checked.name };
56
+ }
57
+
58
+ /**
59
+ * The name a person's sends are recorded under, and where it comes from:
60
+ * "environment" (PI_REPL_USER_NAME), "setting" (the shared file) or "default".
61
+ * `saved` is the setting's name when the environment hides it.
62
+ * @returns {{ name: string, source: "environment" | "setting" | "default", path: string, saved?: string, warning?: string }}
63
+ */
64
+ export function resolvePersonName(env = process.env) {
65
+ const setting = readPersonSetting(env);
66
+ const warnings = setting.warning ? [setting.warning] : [];
67
+ const raw = env[PERSON_NAME_ENV];
68
+ if (typeof raw === "string" && raw.trim()) {
69
+ const checked = validatePersonName(raw);
70
+ if (!checked.error) return { name: checked.name, source: "environment", path: setting.path, saved: setting.name, warning: warnings.join(" ") || undefined };
71
+ warnings.unshift(`${PERSON_NAME_ENV} was ignored: ${checked.error}.`);
72
+ }
73
+ if (setting.name) return { name: setting.name, source: "setting", path: setting.path, warning: warnings.join(" ") || undefined };
74
+ return { name: DEFAULT_PERSON_NAME, source: "default", path: setting.path, warning: warnings.join(" ") || undefined };
75
+ }
76
+
77
+ /** Saves the name as the account's shared setting, replacing the file atomically with mode 0600. */
78
+ export function savePersonName(value, env = process.env) {
79
+ const checked = validatePersonName(value);
80
+ if (checked.error) throw new Error(`Not saved: ${checked.error}.`);
81
+ const path = getPersonSettingPath(env);
82
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
83
+ const tempPath = join(dirname(path), `.person.json.${process.pid}.${randomUUID()}.tmp`);
84
+ let fd = -1;
85
+ try {
86
+ fd = openSync(tempPath, "wx", 0o600);
87
+ writeFileSync(fd, `${JSON.stringify({ name: checked.name }, null, 2)}\n`, "utf8");
88
+ fsyncSync(fd);
89
+ closeSync(fd);
90
+ fd = -1;
91
+ renameSync(tempPath, path);
92
+ if (process.platform !== "win32") chmodSync(path, 0o600);
93
+ } finally {
94
+ if (fd >= 0) closeSync(fd);
95
+ rmSync(tempPath, { force: true });
96
+ }
97
+ return { name: checked.name, path };
98
+ }
99
+
100
+ /** Removes the shared setting, so sends without PI_REPL_USER_NAME are recorded as "User". */
101
+ export function clearPersonName(env = process.env) {
102
+ const path = getPersonSettingPath(env);
103
+ try {
104
+ rmSync(path);
105
+ return { path, removed: true };
106
+ } catch (error) {
107
+ if (error?.code === "ENOENT") return { path, removed: false };
108
+ throw error;
109
+ }
110
+ }
111
+
112
+ /** A person's request ID: its prefix says the route ("pi" or "cli") and what was sent ("send" or "env"). */
113
+ export function personRequestId(channel, kind) {
114
+ if (channel !== "pi" && channel !== "cli") throw new Error(`Unknown person channel: ${channel}`);
115
+ if (kind !== "send" && kind !== "env") throw new Error(`Unknown person request: ${kind}`);
116
+ return `${channel}:${kind}:${randomUUID()}`;
117
+ }
118
+
119
+ /**
120
+ * What `name` says with no argument: the name used and where it comes from,
121
+ * and the saved one when PI_REPL_USER_NAME hides it. `command` is how this
122
+ * client sets it, such as "/repl name" or "agent-repl name".
123
+ */
124
+ export function formatPersonNameStatus(resolved, command) {
125
+ const lines = [];
126
+ if (resolved.source === "environment") {
127
+ lines.push(`Your sends are recorded as ${JSON.stringify(resolved.name)}, from ${PERSON_NAME_ENV}.`);
128
+ lines.push(resolved.saved
129
+ ? `The saved name, ${JSON.stringify(resolved.saved)} (${resolved.path}), applies where ${PERSON_NAME_ENV} isn't set.`
130
+ : `No name is saved in ${resolved.path}.`);
131
+ } else if (resolved.source === "setting") {
132
+ lines.push(`Your sends are recorded as ${JSON.stringify(resolved.name)}, saved in ${resolved.path} for everyone on this account without ${PERSON_NAME_ENV}.`);
133
+ lines.push(`Change it with ${command} <name>, or remove it with ${command} --clear.`);
134
+ } else {
135
+ lines.push(`Your sends are recorded as ${JSON.stringify(DEFAULT_PERSON_NAME)}: no name is set.`);
136
+ lines.push(`Set one with ${command} <name>. It's saved in ${resolved.path}, for everyone on this account without ${PERSON_NAME_ENV}.`);
137
+ }
138
+ if (resolved.warning) lines.push(resolved.warning);
139
+ return lines.join("\n");
140
+ }
@@ -1,8 +1,10 @@
1
- import { randomUUID } from "node:crypto";
1
+ import { createHash, randomUUID } from "node:crypto";
2
2
  import {
3
3
  chmodSync,
4
4
  closeSync,
5
+ constants,
5
6
  existsSync,
7
+ fstatSync,
6
8
  fsyncSync,
7
9
  lstatSync,
8
10
  mkdirSync,
@@ -20,6 +22,7 @@ export const REPL_SESSION_RECORD_PROTOCOL = "pi-repl-session-record";
20
22
  export const REPL_SESSION_RECORD_VERSION = 1;
21
23
  export const REPL_SESSION_RECORD_ID_OPTION = "@pi_repl_record_id";
22
24
  export const REPL_SESSION_RECORD_VERSION_OPTION = "@pi_repl_record_version";
25
+ export const REPL_SESSION_RECORD_ROOT_KEY_OPTION = "@pi_repl_record_root_key";
23
26
  export const REPL_SESSION_RECORD_MAX_ENTRIES = 300;
24
27
  export const REPL_SESSION_RECORD_MAX_CODE_CHARS = 200_000;
25
28
  export const REPL_SESSION_RECORD_MAX_PROSE_CHARS = 80_000;
@@ -27,6 +30,7 @@ export const REPL_SESSION_RECORD_MAX_OUTPUT_CHARS = 200_000;
27
30
  export const REPL_SESSION_RECORD_MAX_BYTES = 16 * 1024 * 1024;
28
31
 
29
32
  const RECORD_ID_PATTERN = /^[a-f0-9]{32}$/;
33
+ const ROOT_KEY_PATTERN = /^v1:[a-f0-9]{32}$/;
30
34
  const RECORD_LOCK_WAIT_MS = 5_000;
31
35
  const RECORD_LOCK_STALE_MS = 30_000;
32
36
  const SEND_LEASE_STALE_MS = 30_000;
@@ -51,6 +55,23 @@ export function getReplSessionRecordRoot(options = {}) {
51
55
  return resolve(options.root || join(tmpdir(), `pi-repl-session-records-${getRootSuffix()}`));
52
56
  }
53
57
 
58
+ // Every derived key starts with this, and no request ID is used as it is when it does, so the two kinds never meet.
59
+ const DERIVED_KEY_PREFIX = "hashed:";
60
+
61
+ /**
62
+ * A stable entry-ID key for a send's request ID, as `pi-repl:<key>`. A
63
+ * request ID an entry ID can hold is its own key. Any other, such as a Pi
64
+ * nested tool call's with its slash, is derived: `hashed:`, its characters made
65
+ * safe, and a hash of the whole, so that two request IDs never share a key. A
66
+ * request ID that itself starts with `hashed:` is always derived, so that it
67
+ * can't be taken for another's derived key.
68
+ */
69
+ export function recordEntryKey(requestId) {
70
+ if (/^[A-Za-z0-9_.:-]{1,200}$/.test(requestId) && !requestId.startsWith(DERIVED_KEY_PREFIX)) return requestId;
71
+ const hash = createHash("sha256").update(requestId).digest("hex").slice(0, 20);
72
+ return `${DERIVED_KEY_PREFIX}${requestId.replace(/[^A-Za-z0-9_.:-]/g, "_").slice(0, 160)}.${hash}`;
73
+ }
74
+
54
75
  export function createReplSessionRecordId() {
55
76
  return randomUUID().replace(/-/g, "").toLowerCase();
56
77
  }
@@ -481,6 +502,249 @@ export function clearReplSessionRecord(recordId, identity, options = {}) {
481
502
  }
482
503
  }
483
504
 
505
+ /**
506
+ * The record-directory key for a directory's device and inode: `v1:` and the
507
+ * first 32 hex characters of the SHA-256 of `<device>:<inode>`, both exact
508
+ * decimal integers. Take them from a bigint stat; a number must be a safe integer.
509
+ */
510
+ export function replSessionRecordRootKeyFor(dev, ino) {
511
+ const decimal = (value) => {
512
+ if (typeof value === "number" && !Number.isSafeInteger(value)) throw new Error("A record directory's device and inode must be exact integers.");
513
+ const text = typeof value === "bigint" || typeof value === "number" ? value.toString() : "";
514
+ if (!/^(?:0|[1-9][0-9]*)$/.test(text)) throw new Error("A record directory's device and inode must be non-negative integers.");
515
+ return text;
516
+ };
517
+ return `v1:${createHash("sha256").update(`${decimal(dev)}:${decimal(ino)}`).digest("hex").slice(0, 32)}`;
518
+ }
519
+
520
+ export function isValidReplSessionRecordRootKey(value) {
521
+ return typeof value === "string" && ROOT_KEY_PATTERN.test(value);
522
+ }
523
+
524
+ // Checks the root as writers leave it, changing nothing: a real directory of
525
+ // the current user's, mode 0700. Throws ENOENT's error when it is missing.
526
+ function checkedRootStat(root) {
527
+ const info = lstatSync(root, { bigint: true });
528
+ if (!info.isDirectory() || info.isSymbolicLink()) {
529
+ throw new Error(`Shared REPL record root is not a real directory: ${root}`);
530
+ }
531
+ const uid = currentUid();
532
+ if (uid != null && Number(info.uid) !== uid) {
533
+ throw new Error(`Refusing shared REPL state not owned by the current user: ${root}`);
534
+ }
535
+ if (process.platform !== "win32" && (Number(info.mode) & 0o777) !== 0o700) {
536
+ throw new Error(`Shared REPL record root is not private (mode 0700): ${root}`);
537
+ }
538
+ return info;
539
+ }
540
+
541
+ function isMissing(error) {
542
+ return Boolean(error && typeof error === "object" && error.code === "ENOENT");
543
+ }
544
+
545
+ /** This client's record-directory key, for a writer: creates the private root if it is missing. */
546
+ export function getReplSessionRecordRootKey(options = {}) {
547
+ const info = checkedRootStat(ensurePrivateRoot(options));
548
+ return replSessionRecordRootKeyFor(info.dev, info.ino);
549
+ }
550
+
551
+ /**
552
+ * This client's record-directory key, for a reader: never creates the root or
553
+ * changes its mode. Null when there is no root, so no local record either.
554
+ */
555
+ export function readReplSessionRecordRootKey(options = {}) {
556
+ let info;
557
+ try {
558
+ info = checkedRootStat(getReplSessionRecordRoot(options));
559
+ } catch (error) {
560
+ if (isMissing(error)) return null;
561
+ throw error;
562
+ }
563
+ return replSessionRecordRootKeyFor(info.dev, info.ino);
564
+ }
565
+
566
+ /**
567
+ * A session's record as this client's directory holds it, for readers and for
568
+ * a writer's adoption check. It never creates the root, takes the lock or
569
+ * changes a mode, and refuses what writers would repair: a file that isn't a
570
+ * private, single-link regular file, or a record of another session lifetime.
571
+ * Null when this directory has no record with that ID.
572
+ */
573
+ export function readReplSessionRecordStrict(recordId, identity, options = {}) {
574
+ assertRecordId(recordId);
575
+ const expected = normalizeRecordIdentity(identity);
576
+ try {
577
+ checkedRootStat(getReplSessionRecordRoot(options));
578
+ } catch (error) {
579
+ if (isMissing(error)) return null;
580
+ throw error;
581
+ }
582
+ const path = getReplSessionRecordPath(recordId, options);
583
+ let fd;
584
+ try {
585
+ // Nonblocking, so a FIFO at the path is refused by the checks below rather than waited on.
586
+ fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
587
+ } catch (error) {
588
+ if (isMissing(error)) return null;
589
+ if (error && typeof error === "object" && error.code === "ELOOP") throw new Error(`Shared REPL record is not a regular file: ${path}`);
590
+ throw error;
591
+ }
592
+ let text;
593
+ try {
594
+ const info = fstatSync(fd);
595
+ if (!info.isFile()) throw new Error(`Shared REPL record is not a regular file: ${path}`);
596
+ if (info.nlink !== 1) throw new Error(`Shared REPL record has an unsafe hard-link count: ${path}`);
597
+ assertOwnedByCurrentUser(path, info);
598
+ if (process.platform !== "win32" && (info.mode & 0o777) !== 0o600) throw new Error(`Shared REPL record is not private (mode 0600): ${path}`);
599
+ if (info.size > REPL_SESSION_RECORD_MAX_BYTES * 2) throw new Error(`Shared REPL record exceeds the safe read limit: ${path}`);
600
+ text = readFileSync(fd, "utf8");
601
+ } finally {
602
+ closeSync(fd);
603
+ }
604
+ let parsed;
605
+ try {
606
+ parsed = JSON.parse(text);
607
+ } catch (error) {
608
+ throw new Error(`Could not parse shared REPL record ${path}: ${error instanceof Error ? error.message : String(error)}`);
609
+ }
610
+ // Checked as stored, before normalising: normalising would round, trim or fill in what isn't there.
611
+ const isObject = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
612
+ if (!isObject(parsed) || !Array.isArray(parsed.entries) || !parsed.entries.every(isObject)) {
613
+ throw new Error(`Shared REPL record ${path} is not a record with a list of entries.`);
614
+ }
615
+ const session = parsed.session;
616
+ if (
617
+ !isObject(session)
618
+ || session.sessionName !== expected.sessionName
619
+ || session.tmuxSessionId !== expected.tmuxSessionId
620
+ || session.tmuxSessionCreatedAt !== expected.tmuxSessionCreatedAt
621
+ ) {
622
+ throw new Error(`Shared REPL record ${path} belongs to another tmux session or session lifetime.`);
623
+ }
624
+ return normalizeRecord(parsed, recordId);
625
+ }
626
+
627
+ const ROOT_KEY_REMEDY = "Use it from a terminal with the same temporary directory (TMPDIR) as its other clients. Restarting the session also fixes this, but discards its state, so that is the user's decision.";
628
+
629
+ /**
630
+ * What a client says about a session's record directory, as
631
+ * classifyReplSessionRecordRoot or a writer's check found it: a refusal for
632
+ * "different", "malformed", "missing", "elsewhere" and "unusable", the
633
+ * "not verified" notice for "unverified", and nothing for "verified".
634
+ */
635
+ export function describeReplSessionRecordRoot(state, sessionName, options = {}, detail = "") {
636
+ const root = getReplSessionRecordRoot(options);
637
+ switch (state) {
638
+ case "verified":
639
+ return undefined;
640
+ case "unverified":
641
+ return `${sessionName}'s record directory is not verified: the session has no record-directory key yet, so this terminal's record may not be the one other clients use.`;
642
+ case "different":
643
+ return `${sessionName}'s shared record is in a different or replaced record directory, not this terminal's (${root}). ${ROOT_KEY_REMEDY}`;
644
+ case "malformed":
645
+ return `${sessionName}'s record-directory key (${REPL_SESSION_RECORD_ROOT_KEY_OPTION}) isn't one this version understands, so it's left as it is and the record isn't used from here.`;
646
+ case "missing":
647
+ return `${sessionName}'s record-directory key couldn't be set or has gone, so its record isn't used from here.`;
648
+ case "elsewhere":
649
+ return `${sessionName}'s record isn't in this terminal's record directory (${root}), and the session has no record-directory key to say which directory holds it, so this terminal won't claim it; the session may have been started from a terminal with a different temporary directory (TMPDIR). ${ROOT_KEY_REMEDY}`;
650
+ case "unusable":
651
+ return `${sessionName}'s record in this terminal's record directory can't be checked (${detail}), and the session has no record-directory key, so this terminal won't claim it. ${ROOT_KEY_REMEDY}`;
652
+ default:
653
+ throw new Error(`Unknown record-directory state: ${state}`);
654
+ }
655
+ }
656
+
657
+ /**
658
+ * How a reader may treat a session's record, from the record-directory key the
659
+ * session holds (undefined when it has none): "verified" when it names this
660
+ * client's record directory, "unverified" when there is none, "malformed" when
661
+ * it isn't a key this version knows, and "different" otherwise, including when
662
+ * this client has no record directory. Readers never set the key or create anything.
663
+ */
664
+ export function classifyReplSessionRecordRoot(storedKey, options = {}) {
665
+ if (storedKey === undefined) return "unverified";
666
+ if (!isValidReplSessionRecordRootKey(storedKey)) return "malformed";
667
+ return readReplSessionRecordRootKey(options) === storedKey ? "verified" : "different";
668
+ }
669
+
670
+ /**
671
+ * A writer's record-directory check, before it creates a session's record
672
+ * metadata, writes its record or takes its lease. `tmux.readKey()` resolves to
673
+ * the key the session holds, or undefined when it has none, and rejects when
674
+ * it can't read that exact session lifetime; `tmux.setKeyIfAbsent(key)` sets
675
+ * it only if it is unset (tmux `set-option -o`). `recordId` is the record ID the
676
+ * session already holds, if any. With an ID and no key, an older client made
677
+ * the metadata, and the key is set only if this directory already holds that
678
+ * session's record, checked before anything is created or repaired. Only a
679
+ * fresh session's writer creates its record directory. A set is always read
680
+ * back: the key that stuck decides.
681
+ * Resolves to { ok: true, key, adopted } or { ok: false, reason }.
682
+ */
683
+ export async function bindReplSessionRecordRoot(tmux, { sessionName, recordId, identity }, options = {}) {
684
+ let stored = await tmux.readKey();
685
+ // Only a writer setting a fresh session's key may create its record directory.
686
+ if (stored !== undefined) return checkStoredRootKey(stored, readReplSessionRecordRootKey(options), sessionName, options, false);
687
+ let own;
688
+ if (recordId) {
689
+ // Adoption is checked first, creating and repairing nothing.
690
+ let local;
691
+ try {
692
+ local = readReplSessionRecordStrict(recordId, identity, options);
693
+ } catch (error) {
694
+ return { ok: false, reason: describeReplSessionRecordRoot("unusable", sessionName, options, error instanceof Error ? error.message : String(error)) };
695
+ }
696
+ own = local ? readReplSessionRecordRootKey(options) : null;
697
+ if (!own) return { ok: false, reason: describeReplSessionRecordRoot("elsewhere", sessionName, options) };
698
+ } else {
699
+ own = getReplSessionRecordRootKey(options);
700
+ }
701
+ await tmux.setKeyIfAbsent(own);
702
+ stored = await tmux.readKey();
703
+ return checkStoredRootKey(stored, own, sessionName, options, Boolean(recordId));
704
+ }
705
+
706
+ /**
707
+ * A writer's check where it uses the record or lease, such as after waiting
708
+ * for the lease: the session's key must still name this client's record
709
+ * directory, which must not have been replaced. Never sets or creates anything.
710
+ */
711
+ export async function verifyReplSessionRecordRoot(tmux, sessionName, options = {}) {
712
+ const own = readReplSessionRecordRootKey(options);
713
+ return checkStoredRootKey(await tmux.readKey(), own, sessionName, options, false);
714
+ }
715
+
716
+ /**
717
+ * The `tmux` that bindReplSessionRecordRoot and verifyReplSessionRecordRoot
718
+ * take, for one session lifetime. `run(args)` runs tmux with those arguments
719
+ * and resolves to { code, stdout, stderr }. An unset key is undefined; a read
720
+ * that fails, or finds another session lifetime, rejects.
721
+ */
722
+ export function replSessionRecordRootKeyTmux(run, identity) {
723
+ return {
724
+ async readKey() {
725
+ const result = await run(["show-options", "-v", "-t", identity.tmuxSessionId, REPL_SESSION_RECORD_ROOT_KEY_OPTION]);
726
+ // A space, not a tab: tmux prints a tab as `_` without -u or a UTF-8 locale.
727
+ const lifetime = await run(["display-message", "-p", "-t", identity.tmuxSessionId, "#{session_id} #{session_created}"]);
728
+ if (lifetime.code !== 0 || lifetime.stdout.trim() !== `${identity.tmuxSessionId} ${identity.tmuxSessionCreatedAt}`) {
729
+ throw new Error(`${identity.sessionName} changed while its record-directory key was read.`);
730
+ }
731
+ if (result.code === 0) return result.stdout.replace(/\r?\n$/, "");
732
+ if (/invalid option|unknown option/i.test(result.stderr)) return undefined;
733
+ throw new Error(`Could not read ${identity.sessionName}'s record-directory key: ${result.stderr.trim() || `tmux exited with ${result.code}`}.`);
734
+ },
735
+ async setKeyIfAbsent(key) {
736
+ await run(["set-option", "-qo", "-t", identity.tmuxSessionId, REPL_SESSION_RECORD_ROOT_KEY_OPTION, key]);
737
+ },
738
+ };
739
+ }
740
+
741
+ function checkStoredRootKey(stored, own, sessionName, options, adopted) {
742
+ if (stored === undefined) return { ok: false, reason: describeReplSessionRecordRoot("missing", sessionName, options) };
743
+ if (!isValidReplSessionRecordRootKey(stored)) return { ok: false, reason: describeReplSessionRecordRoot("malformed", sessionName, options) };
744
+ if (stored !== own) return { ok: false, reason: describeReplSessionRecordRoot("different", sessionName, options) };
745
+ return { ok: true, key: own, adopted };
746
+ }
747
+
484
748
  async function removeStaleLease(lockPath, staleMs) {
485
749
  try {
486
750
  const info = await lstat(lockPath);
@@ -581,6 +845,36 @@ export async function acquireReplSessionSendLease(recordId, options = {}) {
581
845
  };
582
846
  }
583
847
 
848
+ /**
849
+ * Who holds the session's send lease, read only: the owner it was taken for,
850
+ * its process, when it was taken and last renewed, and whether the next send
851
+ * would treat it as abandoned. Null when no send holds it.
852
+ */
853
+ export function readReplSessionSendLease(recordId, options = {}) {
854
+ assertRecordId(recordId);
855
+ const lockPath = getSendLeasePath(recordId, options);
856
+ let info;
857
+ try {
858
+ info = lstatSync(lockPath);
859
+ } catch (error) {
860
+ if (error && typeof error === "object" && error.code === "ENOENT") return null;
861
+ throw error;
862
+ }
863
+ let owner = {};
864
+ try {
865
+ owner = JSON.parse(readFileSync(join(lockPath, "owner.json"), "utf8"));
866
+ } catch {
867
+ // Taken a moment ago, or left unreadable: its holder is unknown.
868
+ }
869
+ return {
870
+ owner: typeof owner.owner === "string" ? owner.owner : "unknown",
871
+ pid: Number.isSafeInteger(owner.pid) ? owner.pid : undefined,
872
+ createdAt: Number.isFinite(owner.createdAt) ? owner.createdAt : undefined,
873
+ renewedAt: info.mtimeMs,
874
+ stale: Date.now() - info.mtimeMs > SEND_LEASE_STALE_MS,
875
+ };
876
+ }
877
+
584
878
  function markdownFence(text, language = "") {
585
879
  const value = String(text || "").replace(/\s+$/, "");
586
880
  let fence = "```";