pi-better-server 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/README.md +615 -2
  2. package/codex-plugin/.agents/plugins/marketplace.json +17 -0
  3. package/codex-plugin/plugins/pi-remote/.codex-plugin/plugin.json +20 -0
  4. package/codex-plugin/plugins/pi-remote/.mcp.json +13 -0
  5. package/codex-plugin/plugins/pi-remote/server.mjs +118 -0
  6. package/codex-plugin/plugins/pi-remote/skills/pi-remote/SKILL.md +19 -0
  7. package/package.json +60 -4
  8. package/scripts/bootstrap-host.sh +107 -0
  9. package/scripts/private-runtime/format.ts +65 -0
  10. package/scripts/private-runtime/installer.ts +166 -0
  11. package/scripts/private-runtime/package-lock.json +1491 -0
  12. package/scripts/private-runtime/package.json +17 -0
  13. package/scripts/test-on-pi.sh +34 -0
  14. package/src/cli-args.ts +38 -0
  15. package/src/cli.ts +90 -0
  16. package/src/client.ts +152 -0
  17. package/src/codex/adapter.ts +299 -0
  18. package/src/codex/app-server.ts +112 -0
  19. package/src/codex/daemon.ts +232 -0
  20. package/src/codex/deliver.ts +103 -0
  21. package/src/codex/preflight.ts +15 -0
  22. package/src/codex/provider.ts +55 -0
  23. package/src/codex/return.ts +110 -0
  24. package/src/codex/rollout.ts +160 -0
  25. package/src/codex/runtime.ts +126 -0
  26. package/src/codex/ws-unix.ts +112 -0
  27. package/src/companion.ts +96 -0
  28. package/src/control.ts +85 -0
  29. package/src/core/adapter.ts +109 -0
  30. package/src/core/bundle.ts +764 -0
  31. package/src/core/exclusions.ts +53 -0
  32. package/src/core/move-host.ts +268 -0
  33. package/src/core/ownership.ts +135 -0
  34. package/src/core/transfer.ts +73 -0
  35. package/src/daemon-owner.ts +130 -0
  36. package/src/detach/detach.ts +150 -0
  37. package/src/detach/extension.ts +244 -0
  38. package/src/detach/local-sink.ts +203 -0
  39. package/src/detach/local-source.ts +133 -0
  40. package/src/detach/local-state.ts +87 -0
  41. package/src/detach/recover.ts +53 -0
  42. package/src/event-log.ts +163 -0
  43. package/src/git.ts +35 -0
  44. package/src/handshake.ts +57 -0
  45. package/src/hosted-session.ts +576 -0
  46. package/src/index.ts +31 -0
  47. package/src/lifecycle-config.ts +29 -0
  48. package/src/maintenance.ts +317 -0
  49. package/src/move/auth.ts +16 -0
  50. package/src/move/orchestrate.ts +163 -0
  51. package/src/move/pi-adapter.ts +181 -0
  52. package/src/move/preflight.ts +197 -0
  53. package/src/move/service.ts +16 -0
  54. package/src/paths.ts +52 -0
  55. package/src/protocol.ts +212 -0
  56. package/src/registry.ts +559 -0
  57. package/src/remote/answer.ts +95 -0
  58. package/src/remote/attach-codex.ts +41 -0
  59. package/src/remote/attach.ts +41 -0
  60. package/src/remote/console.ts +126 -0
  61. package/src/remote/context.ts +75 -0
  62. package/src/remote/cursors.ts +36 -0
  63. package/src/remote/ls.ts +44 -0
  64. package/src/remote/move.ts +85 -0
  65. package/src/remote/new.ts +37 -0
  66. package/src/remote/process-runner.ts +51 -0
  67. package/src/remote/recover.ts +35 -0
  68. package/src/remote/return.ts +49 -0
  69. package/src/remote/sessions.ts +33 -0
  70. package/src/remote/steer.ts +40 -0
  71. package/src/remote/tail.ts +91 -0
  72. package/src/remote/target.ts +313 -0
  73. package/src/remote-cli.ts +73 -0
  74. package/src/remote-client/connection-progress.ts +62 -0
  75. package/src/remote-client/extension.ts +368 -0
  76. package/src/remote-client/folder-browser.ts +165 -0
  77. package/src/remote-client/host.ts +127 -0
  78. package/src/remote-client/local-work.ts +62 -0
  79. package/src/remote-client/menu.ts +68 -0
  80. package/src/remote-client/packages.ts +331 -0
  81. package/src/remote-client/pi-1.2-bridge.ts +482 -0
  82. package/src/remote-client/profiles.ts +38 -0
  83. package/src/remote-client/remote-progress.ts +39 -0
  84. package/src/remote-client/session-browser.ts +267 -0
  85. package/src/remote-client/session.ts +1205 -0
  86. package/src/remote-client/ssh-hosts.ts +185 -0
  87. package/src/remote-client/transfer-command.ts +189 -0
  88. package/src/remote-client/upgrade-transport.ts +105 -0
  89. package/src/server.ts +398 -0
  90. package/src/session-activity.ts +173 -0
  91. package/src/shared-ssh-core/index.ts +950 -0
  92. package/src/startup/activation.ts +621 -0
  93. package/src/startup/admission.ts +98 -0
  94. package/src/startup/artifact.ts +65 -0
  95. package/src/startup/commands.ts +37 -0
  96. package/src/startup/ensure.ts +137 -0
  97. package/src/startup/install.ts +115 -0
  98. package/src/startup/managed-types.ts +61 -0
  99. package/src/startup/runtime.ts +138 -0
  100. package/src/ui-bridge.ts +124 -0
@@ -0,0 +1,160 @@
1
+ /**
2
+ * Codex stores a thread as one append-only rollout file,
3
+ * `<CODEX_HOME>/sessions/YYYY/MM/DD/rollout-<timestamp>-<threadId>.jsonl`. The app-server
4
+ * rebuilds its own indexes (state db, paginated history) from that file, so the rollout
5
+ * is the whole portable thread. This module finds, reads and re-homes it.
6
+ */
7
+ import { closeSync, existsSync, openSync, readdirSync, readFileSync, readSync } from "node:fs";
8
+ import { join } from "node:path";
9
+
10
+ export const ROLLOUT_NAME = /^rollout-.+-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/;
11
+
12
+ export interface RolloutMeta {
13
+ id: string;
14
+ cwd: string;
15
+ createdAt?: string;
16
+ cliVersion?: string;
17
+ modelProvider?: string;
18
+ }
19
+
20
+ function dirs(parent: string): string[] {
21
+ try {
22
+ return readdirSync(parent, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort().reverse();
23
+ } catch {
24
+ return [];
25
+ }
26
+ }
27
+
28
+ /** Absolute path of the thread's rollout under `<root>` (sessions/ or archived_sessions/), or undefined. */
29
+ export function findRollout(root: string, threadId: string): string | undefined {
30
+ if (!existsSync(root)) return undefined;
31
+ const suffix = `-${threadId}.jsonl`;
32
+ const check = (dir: string): string | undefined => {
33
+ try {
34
+ return readdirSync(dir).find((name) => name.startsWith("rollout-") && name.endsWith(suffix));
35
+ } catch {
36
+ return undefined;
37
+ }
38
+ };
39
+ // archived_sessions is flat; sessions/ is year/month/day.
40
+ const flat = check(root);
41
+ if (flat) return join(root, flat);
42
+ for (const year of dirs(root)) for (const month of dirs(join(root, year))) for (const day of dirs(join(root, year, month))) {
43
+ const found = check(join(root, year, month, day));
44
+ if (found) return join(root, year, month, day, found);
45
+ }
46
+ return undefined;
47
+ }
48
+
49
+ /** First line of a rollout, without reading the whole file. */
50
+ export function readFirstLine(file: string): string {
51
+ const fd = openSync(file, "r");
52
+ try {
53
+ const chunks: Buffer[] = [];
54
+ const buffer = Buffer.alloc(64 * 1024);
55
+ for (;;) {
56
+ const read = readSync(fd, buffer, 0, buffer.length, null);
57
+ if (read === 0) break;
58
+ const newline = buffer.subarray(0, read).indexOf(10);
59
+ chunks.push(Buffer.from(buffer.subarray(0, newline === -1 ? read : newline)));
60
+ if (newline !== -1) break;
61
+ }
62
+ return Buffer.concat(chunks).toString("utf8");
63
+ } finally {
64
+ closeSync(fd);
65
+ }
66
+ }
67
+
68
+ export function readRolloutMeta(file: string): RolloutMeta {
69
+ const first = JSON.parse(readFirstLine(file)) as { type?: string; payload?: Record<string, any> };
70
+ const payload = first.payload ?? {};
71
+ if (first.type !== "session_meta" || typeof payload.id !== "string" || typeof payload.cwd !== "string") throw new Error(`${file} does not start with a Codex session_meta record`);
72
+ return {
73
+ id: payload.id,
74
+ cwd: payload.cwd,
75
+ ...(typeof payload.timestamp === "string" ? { createdAt: payload.timestamp } : {}),
76
+ ...(typeof payload.cli_version === "string" ? { cliVersion: payload.cli_version } : {}),
77
+ ...(typeof payload.model_provider === "string" ? { modelProvider: payload.model_provider } : {}),
78
+ };
79
+ }
80
+
81
+ /** The object holding the workspace fields in a record, if it is one that does. */
82
+ function workspaceHolder(record: { type?: string; payload?: Record<string, any> }): Record<string, unknown> | undefined {
83
+ if (record.type === "session_meta" || record.type === "turn_context") return record.payload;
84
+ // The app-server resumes a thread with the last settings it recorded, and those name the workspace too.
85
+ if (record.type === "event_msg" && record.payload?.type === "thread_settings_applied") return record.payload.thread_settings;
86
+ return undefined;
87
+ }
88
+
89
+ /**
90
+ * Point a rollout at the workspace's new location. Only the structured working
91
+ * directory fields (`cwd`, `runtime_workspace_roots`, `workspace_roots`) of the
92
+ * session_meta, turn_context and thread_settings_applied records change; conversation content stays byte for
93
+ * byte what was said, even where it mentions the old path.
94
+ */
95
+ export function rewriteRolloutCwd(text: string, from: string, to: string): { text: string; changed: number } {
96
+ if (from === to) return { text, changed: 0 };
97
+ let changed = 0;
98
+ const swap = (value: unknown): unknown => (value === from ? ((changed += 1), to) : value);
99
+ const lines = text.split("\n").map((line) => {
100
+ if (!line || !line.includes(from)) return line;
101
+ let record: { type?: string; payload?: Record<string, any> };
102
+ try {
103
+ record = JSON.parse(line);
104
+ } catch {
105
+ return line;
106
+ }
107
+ const holder = workspaceHolder(record);
108
+ if (!holder) return line;
109
+ holder.cwd = swap(holder.cwd);
110
+ for (const key of ["runtime_workspace_roots", "workspace_roots"]) {
111
+ const roots = holder[key];
112
+ if (Array.isArray(roots)) holder[key] = roots.map(swap);
113
+ }
114
+ return JSON.stringify(record);
115
+ });
116
+ return { text: lines.join("\n"), changed };
117
+ }
118
+
119
+ /**
120
+ * Bind a rollout to another model provider. Two records carry it: `model_provider` of session_meta, and
121
+ * `model_provider_id` of every `thread_settings_applied` event (the app-server resumes a thread with the last
122
+ * settings it recorded, so leaving them behind would keep the old provider). Everything else, including the
123
+ * turns already recorded under the old provider, stays byte for byte.
124
+ */
125
+ export function rewriteRolloutProvider(text: string, provider: string): { text: string; changed: number } {
126
+ let changed = 0;
127
+ const lines = text.split("\n").map((line) => {
128
+ if (!line.includes("model_provider")) return line;
129
+ let record: { type?: string; payload?: Record<string, any> };
130
+ try {
131
+ record = JSON.parse(line);
132
+ } catch {
133
+ return line;
134
+ }
135
+ const holder = record.type === "session_meta" ? record.payload : record.type === "event_msg" && record.payload?.type === "thread_settings_applied" ? record.payload.thread_settings : undefined;
136
+ const key = record.type === "session_meta" ? "model_provider" : "model_provider_id";
137
+ if (!holder || typeof holder[key] !== "string" || holder[key] === provider) return line;
138
+ holder[key] = provider;
139
+ changed += 1;
140
+ return JSON.stringify(record);
141
+ });
142
+ return { text: lines.join("\n"), changed };
143
+ }
144
+
145
+ /** Latest name recorded for a thread in session_index.jsonl, if any. */
146
+ export function readThreadName(home: string, threadId: string): string | undefined {
147
+ const file = join(home, "session_index.jsonl");
148
+ if (!existsSync(file)) return undefined;
149
+ let name: string | undefined;
150
+ for (const line of readFileSync(file, "utf8").split("\n")) {
151
+ if (!line.includes(threadId)) continue;
152
+ try {
153
+ const entry = JSON.parse(line) as { id?: string; thread_name?: string };
154
+ if (entry.id === threadId && entry.thread_name) name = entry.thread_name;
155
+ } catch {
156
+ /* skip a damaged line */
157
+ }
158
+ }
159
+ return name;
160
+ }
@@ -0,0 +1,126 @@
1
+ /**
2
+ * The local Codex installation: which `codex` binary, which CODEX_HOME, its pinned
3
+ * version, and its app-server daemon (`codex app-server daemon start`). The daemon is
4
+ * reached only through its unix control socket.
5
+ */
6
+ import { execFile, execFileSync } from "node:child_process";
7
+ import { homedir } from "node:os";
8
+ import { join } from "node:path";
9
+ import { CodexAppServerClient } from "./app-server.ts";
10
+ import { findRollout } from "./rollout.ts";
11
+
12
+ export interface CodexRuntimeOptions {
13
+ /** The `codex` executable. Default: `$PI_CODEX_BIN` or `codex` from PATH. */
14
+ bin?: string;
15
+ /** CODEX_HOME. Default: `$CODEX_HOME` or `~/.codex`. */
16
+ home?: string;
17
+ /** Refuse to work unless `codex --version` is exactly this. Default: `$PI_CODEX_VERSION`. */
18
+ pinnedVersion?: string;
19
+ }
20
+
21
+ export interface DaemonStatus {
22
+ status: string;
23
+ socketPath: string;
24
+ cliVersion: string;
25
+ appServerVersion?: string;
26
+ }
27
+
28
+ export class CodexRuntime {
29
+ readonly bin: string;
30
+ readonly home: string;
31
+ readonly pinnedVersion: string | undefined;
32
+ private cachedVersion: string | undefined;
33
+ private connection: Promise<CodexAppServerClient> | undefined;
34
+
35
+ constructor(options: CodexRuntimeOptions = {}) {
36
+ this.bin = options.bin ?? process.env.PI_CODEX_BIN ?? "codex";
37
+ this.home = options.home ?? process.env.CODEX_HOME ?? join(homedir(), ".codex");
38
+ this.pinnedVersion = options.pinnedVersion ?? process.env.PI_CODEX_VERSION;
39
+ }
40
+
41
+ get env(): NodeJS.ProcessEnv {
42
+ return { ...process.env, CODEX_HOME: this.home };
43
+ }
44
+
45
+ get sessionsDir(): string {
46
+ return join(this.home, "sessions");
47
+ }
48
+
49
+ get archivedDir(): string {
50
+ return join(this.home, "archived_sessions");
51
+ }
52
+
53
+ /** `codex --version` ("codex-cli 0.159.2" -> "0.159.2"). Throws if the binary is missing. */
54
+ version(): string {
55
+ if (this.cachedVersion) return this.cachedVersion;
56
+ let output: string;
57
+ try {
58
+ output = execFileSync(this.bin, ["--version"], { encoding: "utf8", env: this.env, stdio: ["ignore", "pipe", "pipe"] });
59
+ } catch (error) {
60
+ throw new Error(`Cannot run \`${this.bin} --version\`: ${error instanceof Error ? error.message : String(error)}. Install Codex CLI or set PI_CODEX_BIN.`);
61
+ }
62
+ const match = /(\d+\.\d+\.\d+(?:[-+][\w.]+)?)/.exec(output);
63
+ if (!match) throw new Error(`Unrecognized \`${this.bin} --version\` output: ${output.trim()}`);
64
+ this.cachedVersion = match[1]!;
65
+ return this.cachedVersion;
66
+ }
67
+
68
+ /** Throws unless the installed Codex CLI is the pinned version (when one is pinned). */
69
+ assertPinned(): void {
70
+ const version = this.version();
71
+ if (this.pinnedVersion && version !== this.pinnedVersion) {
72
+ throw new Error(`Codex CLI version mismatch: this host runs codex-cli ${version} but ${this.pinnedVersion} is pinned (PI_CODEX_VERSION).`);
73
+ }
74
+ }
75
+
76
+ rolloutPath(threadId: string): string | undefined {
77
+ return findRollout(this.sessionsDir, threadId);
78
+ }
79
+
80
+ archivedRolloutPath(threadId: string): string | undefined {
81
+ return findRollout(this.archivedDir, threadId);
82
+ }
83
+
84
+ /** `codex app-server daemon start` (idempotent): the daemon the Codex TUI attaches to. */
85
+ ensureDaemon(): Promise<DaemonStatus> {
86
+ return new Promise((resolve, reject) => {
87
+ execFile(this.bin, ["app-server", "daemon", "start"], { env: this.env, timeout: 120_000, encoding: "utf8" }, (error, stdout, stderr) => {
88
+ const lastLine = stdout.trim().split("\n").filter((line) => line.startsWith("{")).at(-1);
89
+ if (error || !lastLine) return reject(new Error(`codex app-server daemon start failed: ${stderr.trim() || error?.message || stdout.trim()}`));
90
+ try {
91
+ const parsed = JSON.parse(lastLine) as DaemonStatus;
92
+ if (typeof parsed.socketPath !== "string") throw new Error("no socketPath in daemon status");
93
+ resolve(parsed);
94
+ } catch (parseError) {
95
+ reject(new Error(`codex app-server daemon start gave unreadable output: ${lastLine} (${parseError instanceof Error ? parseError.message : String(parseError)})`));
96
+ }
97
+ });
98
+ });
99
+ }
100
+
101
+ /** A connected, initialized app-server client; reconnects after the previous one closed. */
102
+ async client(): Promise<CodexAppServerClient> {
103
+ if (this.connection) {
104
+ const existing = await this.connection.catch(() => undefined);
105
+ if (existing && !existing.isClosed) return existing;
106
+ }
107
+ const attempt = this.ensureDaemon().then((status) => CodexAppServerClient.connect(status.socketPath));
108
+ this.connection = attempt;
109
+ try {
110
+ return await attempt;
111
+ } catch (error) {
112
+ this.connection = undefined;
113
+ throw error;
114
+ }
115
+ }
116
+
117
+ async daemonStatus(): Promise<DaemonStatus> {
118
+ return this.ensureDaemon();
119
+ }
120
+
121
+ close(): void {
122
+ const connection = this.connection;
123
+ this.connection = undefined;
124
+ void connection?.then((client) => client.close()).catch(() => undefined);
125
+ }
126
+ }
@@ -0,0 +1,112 @@
1
+ /**
2
+ * Minimal WebSocket client over a unix socket: the Codex app-server speaks
3
+ * WebSocket on `unix://PATH`, and Node's WebSocket cannot dial a unix socket.
4
+ * Text frames only; that is all the app-server's JSON-RPC uses.
5
+ */
6
+ import { createHash, randomBytes } from "node:crypto";
7
+ import { connect, type Socket } from "node:net";
8
+
9
+ const GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
10
+
11
+ export interface UnixWebSocket {
12
+ send(text: string): void;
13
+ close(): void;
14
+ }
15
+
16
+ export interface UnixWebSocketHandlers {
17
+ onMessage(text: string): void;
18
+ onClose(error?: Error): void;
19
+ }
20
+
21
+ function encodeFrame(opcode: number, payload: Buffer): Buffer {
22
+ const mask = randomBytes(4);
23
+ const length = payload.length;
24
+ const header = length < 126 ? Buffer.from([0x80 | opcode, 0x80 | length]) : length < 65536 ? Buffer.from([0x80 | opcode, 0x80 | 126, length >> 8, length & 0xff]) : (() => {
25
+ const buffer = Buffer.alloc(10);
26
+ buffer[0] = 0x80 | opcode;
27
+ buffer[1] = 0x80 | 127;
28
+ buffer.writeBigUInt64BE(BigInt(length), 2);
29
+ return buffer;
30
+ })();
31
+ const masked = Buffer.from(payload);
32
+ for (let i = 0; i < masked.length; i++) masked[i]! ^= mask[i % 4]!;
33
+ return Buffer.concat([header, mask, masked]);
34
+ }
35
+
36
+ /** Open a WebSocket to `socketPath`. Resolves after the upgrade handshake. */
37
+ export function connectUnixWebSocket(socketPath: string, handlers: UnixWebSocketHandlers): Promise<UnixWebSocket> {
38
+ return new Promise((resolve, reject) => {
39
+ const socket: Socket = connect(socketPath);
40
+ const key = randomBytes(16).toString("base64");
41
+ let buffer: Buffer = Buffer.alloc(0);
42
+ let upgraded = false;
43
+ let fragments: Buffer[] = [];
44
+ let closed = false;
45
+ const finish = (error?: Error): void => {
46
+ if (closed) return;
47
+ closed = true;
48
+ socket.destroy();
49
+ if (!upgraded) reject(error ?? new Error("socket closed before the WebSocket upgrade"));
50
+ else handlers.onClose(error);
51
+ };
52
+ const api: UnixWebSocket = {
53
+ send: (text) => void socket.write(encodeFrame(0x1, Buffer.from(text, "utf8"))),
54
+ close: () => {
55
+ if (!closed) socket.write(encodeFrame(0x8, Buffer.alloc(0)));
56
+ finish();
57
+ },
58
+ };
59
+ const pump = (): void => {
60
+ for (;;) {
61
+ if (buffer.length < 2) return;
62
+ const fin = (buffer[0]! & 0x80) !== 0;
63
+ const opcode = buffer[0]! & 0x0f;
64
+ let length = buffer[1]! & 0x7f;
65
+ let offset = 2;
66
+ if (length === 126) {
67
+ if (buffer.length < 4) return;
68
+ length = buffer.readUInt16BE(2);
69
+ offset = 4;
70
+ } else if (length === 127) {
71
+ if (buffer.length < 10) return;
72
+ length = Number(buffer.readBigUInt64BE(2));
73
+ offset = 10;
74
+ }
75
+ if (buffer.length < offset + length) return;
76
+ const payload = buffer.subarray(offset, offset + length);
77
+ buffer = buffer.subarray(offset + length);
78
+ if (opcode === 0x8) return finish();
79
+ if (opcode === 0x9) {
80
+ socket.write(encodeFrame(0xa, payload));
81
+ continue;
82
+ }
83
+ if (opcode === 0xa) continue;
84
+ fragments.push(Buffer.from(payload));
85
+ if (fin) {
86
+ const text = Buffer.concat(fragments).toString("utf8");
87
+ fragments = [];
88
+ handlers.onMessage(text);
89
+ }
90
+ }
91
+ };
92
+ socket.on("connect", () => {
93
+ socket.write(`GET / HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: ${key}\r\nSec-WebSocket-Version: 13\r\n\r\n`);
94
+ });
95
+ socket.on("data", (chunk: Buffer) => {
96
+ buffer = Buffer.concat([buffer, chunk]);
97
+ if (!upgraded) {
98
+ const end = buffer.indexOf("\r\n\r\n");
99
+ if (end < 0) return;
100
+ const head = buffer.subarray(0, end).toString("latin1");
101
+ buffer = buffer.subarray(end + 4);
102
+ const accept = createHash("sha1").update(key + GUID).digest("base64");
103
+ if (!/^HTTP\/1\.1 101/.test(head) || !head.includes(accept)) return finish(new Error(`WebSocket upgrade refused: ${head.split("\r\n")[0]}`));
104
+ upgraded = true;
105
+ resolve(api);
106
+ }
107
+ pump();
108
+ });
109
+ socket.on("error", (error) => finish(error));
110
+ socket.on("close", () => finish());
111
+ });
112
+ }
@@ -0,0 +1,96 @@
1
+ import { execFile } from "node:child_process";
2
+ import { fileURLToPath } from "node:url";
3
+
4
+ export interface CompanionInfo {
5
+ /** Name of the tmux session on the host that runs the companion terminal. */
6
+ tmuxSession: string;
7
+ /** argv (run on the host) that attaches a terminal to it; `ssh -t <host> <argv>` is `pi-remote attach --host`. */
8
+ attach: string[];
9
+ /** False when a companion for this session was already running and is reused. */
10
+ created: boolean;
11
+ }
12
+
13
+ export interface CompanionManagerOptions {
14
+ socketPath: string;
15
+ /** Name of a dedicated tmux server (`tmux -L`). Default: the user's own tmux server. */
16
+ tmuxSocket?: string;
17
+ /** Replace the companion's command line (tests); default runs `pi-remote console` with this Node. */
18
+ command?: (sessionId: string, socketPath: string) => string[];
19
+ /** True once the companion itself (not some other client) holds the session's controller lease. */
20
+ isReady: (sessionId: string) => boolean;
21
+ readyTimeoutMs?: number;
22
+ }
23
+
24
+ const REMOTE_CLI = fileURLToPath(new URL("./remote-cli.ts", import.meta.url));
25
+
26
+ function run(file: string, args: string[]): Promise<{ code: number; stderr: string }> {
27
+ return new Promise((resolve) => {
28
+ execFile(file, args, (error, _stdout, stderr) => {
29
+ const code = error ? (typeof (error as { code?: unknown }).code === "number" ? ((error as { code: number }).code) : 127) : 0;
30
+ resolve({ code, stderr: error && code === 127 && !stderr ? error.message : stderr });
31
+ });
32
+ });
33
+ }
34
+
35
+ /**
36
+ * Runs one full-screen terminal per session inside a named tmux session on the
37
+ * daemon's host. The terminal is an ordinary daemon client (`pi-remote console`)
38
+ * that holds the controller lease, so attaching never makes a second writer:
39
+ * any number of `tmux attach` clients share that one pane.
40
+ */
41
+ export class CompanionManager {
42
+ private readonly options: CompanionManagerOptions;
43
+ private readonly inFlight = new Map<string, Promise<CompanionInfo>>();
44
+
45
+ constructor(options: CompanionManagerOptions) {
46
+ this.options = options;
47
+ }
48
+
49
+ static sessionName(sessionId: string): string {
50
+ return `pi-${sessionId.slice(0, 12)}`;
51
+ }
52
+
53
+ private tmux(...args: string[]): string[] {
54
+ return [...(this.options.tmuxSocket ? ["-L", this.options.tmuxSocket] : []), ...args];
55
+ }
56
+
57
+ private async exists(name: string): Promise<boolean> {
58
+ return (await run("tmux", this.tmux("has-session", "-t", `=${name}`))).code === 0;
59
+ }
60
+
61
+ /** Start the companion for a session, or return the one already running. Calls for one session are serialized. */
62
+ start(sessionId: string, cwd: string): Promise<CompanionInfo> {
63
+ const running = this.inFlight.get(sessionId);
64
+ if (running) return running;
65
+ const started = this.startOnce(sessionId, cwd).finally(() => this.inFlight.delete(sessionId));
66
+ this.inFlight.set(sessionId, started);
67
+ return started;
68
+ }
69
+
70
+ private async startOnce(sessionId: string, cwd: string): Promise<CompanionInfo> {
71
+ const name = CompanionManager.sessionName(sessionId);
72
+ const attach = ["tmux", ...this.tmux("attach", "-t", `=${name}`)];
73
+ if (await this.exists(name)) return { tmuxSession: name, attach, created: false };
74
+
75
+ const command = this.options.command?.(sessionId, this.options.socketPath) ?? [process.execPath, REMOTE_CLI, "console", sessionId, "--companion", "--socket", this.options.socketPath];
76
+ const made = await run("tmux", this.tmux("new-session", "-d", "-s", name, "-x", "200", "-y", "50", "-c", cwd, "--", ...command));
77
+ if (made.code !== 0) {
78
+ throw new Error(made.code === 127 ? "tmux is not installed on this host; attach needs it" : `tmux could not start the companion: ${made.stderr.trim() || `exit ${made.code}`}`);
79
+ }
80
+ const deadline = Date.now() + (this.options.readyTimeoutMs ?? 15_000);
81
+ while (!this.options.isReady(sessionId)) {
82
+ if (!(await this.exists(name))) throw new Error("The companion terminal exited before it took control; another client may hold the session's controller lease");
83
+ if (Date.now() > deadline) {
84
+ await this.stop(sessionId);
85
+ throw new Error("The companion terminal did not take control in time");
86
+ }
87
+ await new Promise((r) => setTimeout(r, 25));
88
+ }
89
+ return { tmuxSession: name, attach, created: true };
90
+ }
91
+
92
+ async stop(sessionId: string): Promise<boolean> {
93
+ const name = CompanionManager.sessionName(sessionId);
94
+ return (await run("tmux", this.tmux("kill-session", "-t", `=${name}`))).code === 0;
95
+ }
96
+ }
package/src/control.ts ADDED
@@ -0,0 +1,85 @@
1
+ import type { LoggedEvent } from "./event-log.ts";
2
+ import type { HostedSession } from "./hosted-session.ts";
3
+ import { failure, type DialogAnswer, type ServerMessage } from "./protocol.ts";
4
+
5
+ /**
6
+ * What one client connection holds on the daemon: its event subscriptions and
7
+ * its controller leases. Both end when the connection does, so a vanished
8
+ * client can never keep a lease or a stream alive.
9
+ */
10
+ export class ConnectionControl {
11
+ private readonly subscriptions = new Map<string, () => void>();
12
+ private readonly leases = new Set<HostedSession>();
13
+ /** True once this connection took a lease as the attach companion. */
14
+ companion = false;
15
+ private readonly send: (message: ServerMessage) => void;
16
+
17
+ constructor(send: (message: ServerMessage) => void) {
18
+ this.send = send;
19
+ }
20
+
21
+ /** Stream a session's events to this connection, replaying after `sinceSeq` first. Replaces an earlier subscription. */
22
+ subscribe(sessionId: string, hosted: HostedSession, sinceSeq: number | undefined): { summary: Record<string, unknown>; events: LoggedEvent[] } {
23
+ this.unsubscribe(sessionId);
24
+ const { replay, unsubscribe } = hosted.subscribe(sinceSeq, (logged) => this.send({ type: "event", sessionId, generation: hosted.generation, seq: logged.seq, event: logged.event }));
25
+ this.subscriptions.set(sessionId, unsubscribe);
26
+ const summary = { generation: hosted.generation, lastSeq: hosted.lastSeq, firstSeq: replay.firstSeq, replayed: replay.events.length, truncated: replay.truncated };
27
+ return { summary, events: replay.events };
28
+ }
29
+
30
+ unsubscribe(sessionId: string): void {
31
+ this.subscriptions.get(sessionId)?.();
32
+ this.subscriptions.delete(sessionId);
33
+ }
34
+
35
+ /** Answer a subscribe/acquire_control/release_control/extension_ui_response command. */
36
+ handle(command: Record<string, unknown>, hosted: HostedSession): void {
37
+ const id = typeof command.id === "string" ? command.id : undefined;
38
+ const type = String(command.type);
39
+ const sessionId = String(command.sessionId);
40
+ const reply = (data?: unknown): void => this.send({ ...(id !== undefined ? { id } : {}), sessionId, type: "response", command: type, success: true, ...(data !== undefined ? { data } : {}) } as ServerMessage);
41
+ const refuse = (error: string): void => this.send(failure(id, type, error, sessionId));
42
+
43
+ if (type === "subscribe") {
44
+ const since = command.sinceSeq;
45
+ if (since !== undefined && (typeof since !== "number" || !Number.isInteger(since) || since < 0)) return refuse("sinceSeq must be a non-negative integer");
46
+ const { summary, events } = this.subscribe(sessionId, hosted, since as number | undefined);
47
+ reply(summary);
48
+ for (const logged of events) this.send({ type: "event", sessionId, generation: hosted.generation, seq: logged.seq, event: logged.event });
49
+ return;
50
+ }
51
+ if (type === "acquire_control") {
52
+ if (!hosted.acquireControl(this)) return refuse("Another connection holds the controller lease for this session");
53
+ this.leases.add(hosted);
54
+ if (command.companion === true) this.companion = true;
55
+ return reply({ needsInput: hosted.needsInput });
56
+ }
57
+ if (type === "release_control") {
58
+ if (!hosted.releaseControl(this)) return refuse("This connection does not hold the controller lease");
59
+ this.leases.delete(hosted);
60
+ return reply();
61
+ }
62
+ // extension_ui_response
63
+ if (!hosted.isController(this)) return refuse("Only the controller can answer dialogs: acquire_control first");
64
+ const requestId = command.requestId;
65
+ if (typeof requestId !== "string") return refuse("requestId is required");
66
+ const answer = parseAnswer(command);
67
+ if (!answer) return refuse("Answer needs one of: value (string), confirmed (boolean), cancelled (true)");
68
+ if (!hosted.answerDialog(requestId, answer)) return refuse(`No pending dialog ${requestId}`);
69
+ reply();
70
+ }
71
+
72
+ dispose(): void {
73
+ for (const unsubscribe of this.subscriptions.values()) unsubscribe();
74
+ this.subscriptions.clear();
75
+ for (const hosted of this.leases) hosted.releaseControl(this);
76
+ this.leases.clear();
77
+ }
78
+ }
79
+
80
+ function parseAnswer(command: Record<string, unknown>): DialogAnswer | undefined {
81
+ if (typeof command.value === "string") return { value: command.value };
82
+ if (typeof command.confirmed === "boolean") return { confirmed: command.confirmed };
83
+ if (command.cancelled === true) return { cancelled: true };
84
+ return undefined;
85
+ }