pi-better-server 0.1.2 → 0.2.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.
package/README.md CHANGED
@@ -108,14 +108,16 @@ A client that skips `hello` is still served.
108
108
 
109
109
  The native client provides an experimental VS Code Remote-style workflow:
110
110
  start ordinary local Pi **1.2.0** with this package loaded at startup, then run
111
- `/remote connect r5`. The terminal keeps Pi's native local UI while the remote daemon owns
111
+ `/remote connect r5`, or `/remote connect localhost` for the daemon on this machine.
112
+ The terminal keeps Pi's native local UI while the daemon owns
112
113
  the model, tools, workspace and session state. Your local conversation stays separate
113
114
  unless you explicitly choose to move or copy it after connecting.
114
115
 
115
- Connecting installs or stages the matching server build automatically, verifies
116
- readiness and compatibility, and then opens the SSH tunnel. A registered runtime
117
- keeps its agent and server directories. A new host uses `~/.pi/agent` and
118
- `~/.pi/agent/server`. See [automatic server updates](#automatic-server-updates)
116
+ `localhost` skips SSH. It talks to the local daemon socket, starting that daemon
117
+ through the installed runtime when one is registered. A remote host installs or stages
118
+ the matching server build, verifies readiness and compatibility, and then opens the SSH
119
+ tunnel. A registered runtime keeps its agent and server directories. A new host uses
120
+ `~/.pi/agent` and `~/.pi/agent/server`. See [automatic server updates](#automatic-server-updates)
119
121
  for busy sessions, older daemons and manual launcher overrides.
120
122
 
121
123
  ### Connect and disconnect
@@ -131,6 +133,7 @@ connecting.
131
133
  /remote list
132
134
  /remote connect
133
135
  /remote connect r5
136
+ /remote connect localhost
134
137
  /remote r5
135
138
  /remote r5 --cwd /home/user/workspaces/project
136
139
  /remote r5 --session <id-or-unique-prefix>
@@ -148,9 +151,12 @@ and press Enter to confirm a connection. `/remote connect` opens a host picker;
148
151
  actions only. Host suggestions appear only after `connect`, with a complete
149
152
  `connect <host>` completion value. `/remote r5` remains a supported shorthand.
150
153
 
151
- While connecting, a native spinner shows the current stage: establishing SSH,
152
- finding the remote server, opening the tunnel, or contacting the Pi daemon.
153
- Escape cancels that attempt and returns to the local UI. It does not stop any
154
+ While connecting, a native spinner names each stage and shows how long that stage
155
+ and the whole attempt have taken. Finished stages stay on screen with their duration.
156
+ Once SSH succeeds, the screen says Connected. Later stages are remote progress, not
157
+ another connection attempt: finding the remote server, starting or checking the Pi
158
+ server, opening the tunnel, and contacting the daemon. Local stages stay under Connecting,
159
+ because there is no SSH step. Escape cancels that attempt and returns to the local UI. It does not stop any
154
160
  remote sessions or shared SSH connection. Connection failures retain their original
155
161
  error message; the spinner does not imply that an unreachable host is available.
156
162
 
@@ -287,6 +293,17 @@ target downloads fail, the client downloads and uploads verified archives instea
287
293
  Concurrent connectors share the same release only after integrity validation.
288
294
  Published releases are not overwritten to repair corruption.
289
295
 
296
+ Repeat connections to an already installed matching release verify and reuse its
297
+ private Node without downloading Node or dependencies again. Before running any
298
+ cached executable, the client copies it into its own staging directory and checks
299
+ its SHA-256 against a pinned executable checksum. The freshly uploaded installer
300
+ then validates the complete release, manifest and source under the build lock.
301
+ New releases also retain the original source archive under the release inventory;
302
+ repeat connections copy and authenticate it locally rather than uploading it again.
303
+ Older releases without an archive still use a verified upload for compatibility.
304
+ A present but corrupted release is an error, not permission to replace it. A new
305
+ build still needs the normal first-install downloads and verification.
306
+
290
307
  Staging can proceed while sessions run. Activation waits for all sessions to be
291
308
  idle, including SDK preflight and settlement, queued messages, compaction, shell
292
309
  commands, dialogs and observable background work. Native cache warming is also
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-server",
3
- "version": "0.1.2",
3
+ "version": "0.2.0",
4
4
  "description": "Daemon that hosts Pi agent sessions behind a local Unix socket with session-addressed Pi RPC.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -0,0 +1,279 @@
1
+ /**
2
+ * Benchmark for the pi-better-server localhost connection path.
3
+ *
4
+ * Run with plain node (Node >= 22.18 strips the types itself):
5
+ *
6
+ * node scripts/bench-localhost.ts
7
+ *
8
+ * Spawns real daemon child processes (src/cli.ts) against a private agent dir
9
+ * with the scripted fake provider, then measures: cold start, connect+hello,
10
+ * RPC latencies, prompt roundtrip, replay catch-up, and the re-attach path.
11
+ */
12
+ import { connect } from "node:net";
13
+ import { join } from "node:path";
14
+ import { performance } from "node:perf_hooks";
15
+ import { DaemonClient } from "../src/client.ts";
16
+ import { makeEnv, spawnDaemon, type Env } from "../test/helpers.ts";
17
+
18
+ // Iteration counts. Kept small so the whole run stays well under a minute.
19
+ const COLD_STARTS = 3;
20
+ const CONNECTS = 10;
21
+ const RPC_CALLS = 10;
22
+ const CREATE_SESSIONS = 4;
23
+ const PROMPTS = 5;
24
+ const REPLAY_TURNS = 12; // prompts run to accumulate events for the replay measurement
25
+ const REPLAY_RUNS = 5; // fresh connections replaying the accumulated history
26
+ const ATTACHES = 5;
27
+
28
+ const now = (): number => performance.now();
29
+
30
+ function stats(samples: number[]): { min: number; median: number; max: number } {
31
+ const sorted = [...samples].sort((a, b) => a - b);
32
+ const mid = Math.floor(sorted.length / 2);
33
+ const median = sorted.length % 2 === 0 ? (sorted[mid - 1] + sorted[mid]) / 2 : sorted[mid];
34
+ return { min: sorted[0], median, max: sorted[sorted.length - 1] };
35
+ }
36
+
37
+ interface Row {
38
+ name: string;
39
+ n: number;
40
+ min: number;
41
+ median: number;
42
+ max: number;
43
+ note?: string;
44
+ }
45
+
46
+ const rows: Row[] = [];
47
+ function record(name: string, samples: number[], note?: string): void {
48
+ const s = stats(samples);
49
+ rows.push({ name, n: samples.length, ...s, note });
50
+ }
51
+
52
+ function printTable(): void {
53
+ const headers = ["benchmark", "n", "min (ms)", "median (ms)", "max (ms)", "notes"];
54
+ const cells = rows.map((r) => [r.name, String(r.n), r.min.toFixed(1), r.median.toFixed(1), r.max.toFixed(1), r.note ?? ""]);
55
+ const widths = headers.map((h, i) => Math.max(h.length, ...cells.map((c) => c[i].length)));
56
+ const line = (parts: string[]): string => parts.map((p, i) => p.padEnd(widths[i])).join(" ").trimEnd();
57
+ console.log("");
58
+ console.log(line(headers));
59
+ console.log(widths.map((w) => "-".repeat(w)).join(" "));
60
+ for (const c of cells) console.log(line(c));
61
+ console.log("");
62
+ }
63
+
64
+ /** Connect, say hello (no optional capabilities), and time the whole thing. */
65
+ async function timedConnect(socketPath: string): Promise<{ client: DaemonClient; ms: number }> {
66
+ const t0 = now();
67
+ const client = await DaemonClient.connect(socketPath, { hello: { capabilities: [] } });
68
+ return { client, ms: now() - t0 };
69
+ }
70
+
71
+ /** Time one RPC through `client.call` (throws on failure). */
72
+ async function timedCall(client: DaemonClient, command: Record<string, unknown>): Promise<{ response: any; ms: number }> {
73
+ const t0 = now();
74
+ const response = await client.call(command);
75
+ return { response, ms: now() - t0 };
76
+ }
77
+
78
+ /** Resolve once `match` has been true for a pushed event, with a hard timeout. */
79
+ function waitForEvent(events: Array<{ message: any; at: number }>, what: string, match: (message: any) => boolean, timeoutMs = 20_000): Promise<{ message: any; at: number }> {
80
+ const deadline = now() + timeoutMs;
81
+ return new Promise((resolve, reject) => {
82
+ const poll = (): void => {
83
+ const hit = events.find((e) => match(e.message));
84
+ if (hit) return resolve(hit);
85
+ if (now() > deadline) return reject(new Error(`Timed out waiting for ${what}`));
86
+ setTimeout(poll, 5);
87
+ };
88
+ poll();
89
+ });
90
+ }
91
+
92
+ const daemons: Array<{ kill: (signal?: string) => void }> = [];
93
+ function cleanup(): void {
94
+ for (const child of daemons) {
95
+ try {
96
+ child.kill("SIGKILL");
97
+ } catch {
98
+ // already gone
99
+ }
100
+ }
101
+ }
102
+ process.on("exit", cleanup);
103
+ // makeEnv registers an exit handler that removes the temp roots.
104
+
105
+ async function main(): Promise<void> {
106
+ console.log("bench-localhost: measuring pi-better-server over a local unix socket");
107
+
108
+ // ---- 1. Daemon cold start: spawn -> "listening on" -> socket accepts a connection ----
109
+ const coldStarts: number[] = [];
110
+ let env: Env | undefined;
111
+ let daemon: (typeof daemons)[number] | undefined;
112
+ let socketPath = "";
113
+ for (let i = 0; i < COLD_STARTS; i++) {
114
+ const e = makeEnv();
115
+ const t0 = now();
116
+ const started = await spawnDaemon(e);
117
+ // The stderr marker precedes the socket being connectable by a hair; probe a real connection.
118
+ await new Promise<void>((resolve, reject) => {
119
+ const probe = connect(join(e.serverDir, "pi-server.sock"));
120
+ probe.once("connect", () => {
121
+ probe.end();
122
+ resolve();
123
+ });
124
+ probe.once("error", reject);
125
+ });
126
+ coldStarts.push(now() - t0);
127
+ daemons.push(started.child);
128
+ if (i === COLD_STARTS - 1) {
129
+ // Keep the last daemon for the rest of the benchmark.
130
+ env = e;
131
+ daemon = started.child;
132
+ socketPath = started.socketPath;
133
+ } else {
134
+ started.child.kill("SIGKILL");
135
+ }
136
+ }
137
+ record("daemon cold start (spawn -> socket accepts)", coldStarts);
138
+ if (!env || !daemon) throw new Error("no daemon survived cold-start measurement");
139
+
140
+ // ---- 2. Client connect + hello handshake ----
141
+ const connects: number[] = [];
142
+ for (let i = 0; i < CONNECTS; i++) {
143
+ const { client, ms } = await timedConnect(socketPath);
144
+ connects.push(ms);
145
+ client.close();
146
+ }
147
+ record("client connect + hello", connects);
148
+
149
+ // One long-lived client for the RPC and prompt measurements.
150
+ const { client } = await timedConnect(socketPath);
151
+
152
+ // ---- 3a. list_sessions ----
153
+ const listSessions: number[] = [];
154
+ for (let i = 0; i < RPC_CALLS; i++) listSessions.push((await timedCall(client, { type: "list_sessions" })).ms);
155
+ record("rpc list_sessions", listSessions);
156
+
157
+ // ---- 3b. create_session (keeps one for the prompt tests, closes the rest later) ----
158
+ const createSessions: number[] = [];
159
+ const createdIds: string[] = [];
160
+ for (let i = 0; i < CREATE_SESSIONS; i++) {
161
+ const { response, ms } = await timedCall(client, { type: "create_session", cwd: env.cwd, model: { provider: "fake", modelId: "fake-1" } });
162
+ createSessions.push(ms);
163
+ createdIds.push(response.sessionId);
164
+ }
165
+ record("rpc create_session", createSessions);
166
+ const sessionId = createdIds[0];
167
+ const spareIds = createdIds.slice(1);
168
+
169
+ // ---- 3c. open_session on an already-created session ----
170
+ const openSessions: number[] = [];
171
+ for (let i = 0; i < RPC_CALLS; i++) openSessions.push((await timedCall(client, { type: "open_session", sessionId })).ms);
172
+ record("rpc open_session", openSessions);
173
+
174
+ // ---- 3d. client_snapshot ----
175
+ const snapshots: number[] = [];
176
+ for (let i = 0; i < RPC_CALLS; i++) snapshots.push((await timedCall(client, { type: "client_snapshot", sessionId })).ms);
177
+ record("rpc client_snapshot", snapshots);
178
+
179
+ // ---- 3e. subscribe ----
180
+ const subscribes: number[] = [];
181
+ for (let i = 0; i < RPC_CALLS; i++) subscribes.push((await timedCall(client, { type: "subscribe", sessionId })).ms);
182
+ record("rpc subscribe", subscribes);
183
+
184
+ // ---- 3f. rename_session ----
185
+ const renames: number[] = [];
186
+ for (let i = 0; i < RPC_CALLS; i++) renames.push((await timedCall(client, { type: "rename_session", sessionId, name: `bench-${i}` })).ms);
187
+ record("rpc rename_session", renames);
188
+
189
+ // ---- 3g. close_session (close the spare sessions created above) ----
190
+ const closes: number[] = [];
191
+ for (const id of spareIds) closes.push((await timedCall(client, { type: "close_session", sessionId: id })).ms);
192
+ record("rpc close_session", closes);
193
+
194
+ // ---- 4. Prompt roundtrip with the fake provider ----
195
+ // The creator connection is auto-subscribed, so events stream to it.
196
+ const events: Array<{ message: any; at: number }> = [];
197
+ client.onEvent((message) => events.push({ message, at: now() }));
198
+ const firstEvent: number[] = [];
199
+ const toAgentEnd: number[] = [];
200
+ const toSettled: number[] = [];
201
+ let settledSeen = false;
202
+ // Match only events pushed after `startIdx` in the shared log.
203
+ const after = (startIdx: number, predicate: (m: any) => boolean) => (m: any): boolean => {
204
+ const idx = events.findIndex((e) => e.message === m);
205
+ return idx >= startIdx && predicate(m);
206
+ };
207
+ for (let i = 0; i < PROMPTS; i++) {
208
+ const baseline = events.length;
209
+ const t0 = now();
210
+ await client.call({ type: "prompt", sessionId, message: `bench prompt ${i}` });
211
+ const first = await waitForEvent(events, "first streamed event", after(baseline, (m) => m.sessionId === sessionId));
212
+ firstEvent.push(first.at - t0);
213
+ const end = await waitForEvent(events, "agent_end", after(baseline, (m) => m.sessionId === sessionId && m.event?.type === "agent_end"));
214
+ toAgentEnd.push(end.at - t0);
215
+ try {
216
+ const settled = await waitForEvent(events, "agent_settled", after(baseline, (m) => m.sessionId === sessionId && m.event?.type === "agent_settled"), 3_000);
217
+ toSettled.push(settled.at - t0);
218
+ settledSeen = true;
219
+ } catch {
220
+ // This Pi build does not emit agent_settled to subscribers; agent_end is the terminal event.
221
+ }
222
+ }
223
+ record("prompt -> first streamed event", firstEvent);
224
+ record("prompt -> agent_end", toAgentEnd);
225
+ if (settledSeen) record("prompt -> agent_settled", toSettled);
226
+ else console.log("note: daemon emitted no agent_settled event; agent_end is the measured terminal event");
227
+
228
+ // ---- 5. Replay: accumulate history, then subscribe from seq 0 on fresh connections ----
229
+ for (let i = 0; i < REPLAY_TURNS; i++) {
230
+ const baseline = events.length;
231
+ await client.call({ type: "prompt", sessionId, message: `replay filler ${i}` });
232
+ await waitForEvent(events, "agent_end", after(baseline, (m) => m.sessionId === sessionId && m.event?.type === "agent_end"));
233
+ }
234
+ const replays: number[] = [];
235
+ let replayCount = 0;
236
+ let replayed = 0;
237
+ for (let run = 0; run < REPLAY_RUNS; run++) {
238
+ const replayClient = (await timedConnect(socketPath)).client;
239
+ const replayEvents: Array<{ message: any; at: number }> = [];
240
+ replayClient.onEvent((message) => replayEvents.push({ message, at: now() }));
241
+ const tReplay0 = now();
242
+ const sub = await replayClient.call({ type: "subscribe", sessionId, sinceSeq: 0 });
243
+ const lastSeq = (sub.data as { lastSeq: number }).lastSeq;
244
+ replayed = (sub.data as { replayed: number }).replayed;
245
+ await waitForEvent(replayEvents, `replay catch-up to seq ${lastSeq}`, (m) => m.sessionId === sessionId && typeof m.seq === "number" && m.seq >= lastSeq);
246
+ replays.push(now() - tReplay0);
247
+ replayCount = replayEvents.filter((m) => m.message.sessionId === sessionId && typeof m.message.seq === "number" && m.message.seq <= lastSeq).length;
248
+ replayClient.close();
249
+ }
250
+ const replayMedian = stats(replays).median;
251
+ const perSec = replayMedian > 0 ? (replayCount / replayMedian) * 1000 : 0;
252
+ record("replay subscribe(sinceSeq 0) -> caught up", replays, `${replayCount} events (replayed ${replayed}), ${perSec.toFixed(0)} events/s at median`);
253
+
254
+ // ---- 6. Re-attach: open_session + client_snapshot + subscribe on the existing session ----
255
+ const attaches: number[] = [];
256
+ for (let i = 0; i < ATTACHES; i++) {
257
+ const attachClient = (await timedConnect(socketPath)).client;
258
+ const t0 = now();
259
+ await attachClient.call({ type: "open_session", sessionId });
260
+ await attachClient.call({ type: "client_snapshot", sessionId });
261
+ await attachClient.call({ type: "subscribe", sessionId, sinceSeq: 0 });
262
+ attaches.push(now() - t0);
263
+ attachClient.close();
264
+ }
265
+ record("re-attach (open + snapshot + subscribe)", attaches, "per fresh connection, connect+hello excluded");
266
+
267
+ // ---- Cleanup ----
268
+ await client.call({ type: "close_session", sessionId }).catch(() => undefined);
269
+ client.close();
270
+ daemon.kill("SIGKILL");
271
+
272
+ printTable();
273
+ }
274
+
275
+ main().catch((error) => {
276
+ console.error("bench failed:", error);
277
+ cleanup();
278
+ process.exit(1);
279
+ });
@@ -8,6 +8,14 @@ export const NODE_CHECKSUMS: Record<RuntimePlatform, string> = {
8
8
  "darwin-x64": "2526230ad7d922be82d4fdb1e7ee1e84303e133e3b4b0ec4c2897ab31de0253d",
9
9
  "darwin-arm64": "25495ff85bd89e2d8a24d88566d7e2f827c6b0d3d872b2cebf75371f93fcb1fe",
10
10
  };
11
+ // Extracted bin/node hashes from the archives authenticated by NODE_CHECKSUMS.
12
+ // Source: https://nodejs.org/dist/v24.14.1/SHASUMS256.txt
13
+ export const NODE_EXECUTABLE_CHECKSUMS: Record<RuntimePlatform, string> = {
14
+ "linux-x64": "bf9112eb83a827dc9f9c8d19bb7bddcbf00f7b2fedae18fdcaee05406981f20a",
15
+ "linux-arm64": "7fac13c04c19207c3e904a7721f8c045e6b99493471e2df85444f764cdd21934",
16
+ "darwin-x64": "9ab4f6249a8de4671c3205ef58621dfb19d120a9c59fd96ed206571bafb0319c",
17
+ "darwin-arm64": "35d4bc736bbe4161f0c074aa140ddb74586e46969bc2ad63d32c838bec4463ff",
18
+ };
11
19
  export function digest(value: string | Buffer): string { return createHash("sha256").update(value).digest("hex"); }
12
20
  export function stable(value: any): string {
13
21
  if (Array.isArray(value)) return `[${value.map(stable).join(",")}]`;
@@ -6,14 +6,15 @@ import { gunzipSync } from "node:zlib";
6
6
  import { setTimeout as delay } from "node:timers/promises";
7
7
  import { digest, stable, validatePayload, validateStaged } from "./format.ts";
8
8
 
9
- const [work, installRoot, expectedSha, mode] = process.argv.slice(2) as [string, string, string, string];
9
+ const [work, installRoot, expectedSha, mode, expectedBuildId] = process.argv.slice(2) as [string, string, string, string, string | undefined];
10
10
  let lock: string | undefined;
11
11
  let acquired = false;
12
12
  let ownsWork = false;
13
13
  let candidate: string | undefined;
14
14
  function cancelled() { if (existsSync(join(work, "cancel"))) throw new Error("installation cancelled"); }
15
15
  function plainDirectory(path: string) {
16
- if (existsSync(path) && (!lstatSync(path).isDirectory() || lstatSync(path).isSymbolicLink())) throw new Error(`permission: unsafe directory ${path}`);
16
+ const stat = lstatSync(path, { throwIfNoEntry: false });
17
+ if (stat && (!stat.isDirectory() || stat.isSymbolicLink())) throw new Error(`permission: unsafe directory ${path}`);
17
18
  mkdirSync(path, { recursive: true, mode: 0o700 });
18
19
  }
19
20
  function inventory(root: string): Record<string, string> {
@@ -61,9 +62,13 @@ try {
61
62
  writeFileSync(join(work, "installer.pid"), String(process.pid), { flag: "wx", mode: 0o600 });
62
63
  ownsWork = true;
63
64
  cancelled();
64
- const bytes = readFileSync(join(work, "artifact.gz"));
65
+ const archivePath = join(work, "artifact.gz");
66
+ const archive = lstatSync(archivePath);
67
+ if (!archive.isFile() || archive.isSymbolicLink() || archive.size > 32 * 1024 * 1024) throw new Error("artifact integrity mismatch or size limit");
68
+ const bytes = readFileSync(archivePath);
65
69
  if (bytes.length > 32 * 1024 * 1024 || digest(bytes) !== expectedSha) throw new Error("artifact integrity mismatch or size limit");
66
70
  const payload = validatePayload(JSON.parse(gunzipSync(bytes, { maxOutputLength: 64 * 1024 * 1024 }).toString()));
71
+ if ((mode === "reuse-only" || expectedBuildId !== undefined) && payload.build.contentId !== expectedBuildId) throw new Error("cached artifact build identity mismatch");
67
72
  if (`${process.platform}-${process.arch}` !== payload.build.platform || process.versions.node !== payload.build.nodeVersion) throw new Error("unsupported platform or Node version mismatch");
68
73
  if (realpathSync(installRoot) !== resolve(installRoot)) throw new Error("permission: install root contains symlink");
69
74
  const releases = join(installRoot, "releases");
@@ -87,8 +92,10 @@ try {
87
92
  }
88
93
  writeFileSync(join(lock, "owner.json"), JSON.stringify({ pid: process.pid, work }), { flag: "wx", mode: 0o600 });
89
94
  const runtime = validateStaged({ format: 1, build: payload.build, root: finalRoot, node: join(finalRoot, "node/bin/node"), entrypoint: join(finalRoot, "src/cli.ts"), manifestPath: join(finalRoot, "runtime.json"), installRoot });
90
- if (existsSync(finalRoot)) {
91
- if (lstatSync(finalRoot).isSymbolicLink()) throw new Error("corrupt cache: release symlink");
95
+ const release = lstatSync(finalRoot, { throwIfNoEntry: false });
96
+ if (release) {
97
+ if (release.isSymbolicLink()) throw new Error("corrupt cache: release symlink");
98
+ if (!release.isDirectory()) throw new Error("corrupt cache: expected release directory");
92
99
  for (const path of [runtime.manifestPath, join(finalRoot, "integrity.json"), ...payload.files.map((file) => join(finalRoot, file.path))]) {
93
100
  if (!existsSync(path) || !lstatSync(path).isFile() || lstatSync(path).isSymbolicLink()) throw new Error(`corrupt cache: expected regular file ${path}`);
94
101
  }
@@ -98,6 +105,7 @@ try {
98
105
  cancelled();
99
106
  process.stdout.write(JSON.stringify(runtime));
100
107
  } else {
108
+ if (mode === "reuse-only") throw new Error("reuse-only: release absent");
101
109
  candidate = join(work, "release");
102
110
  removeOwned(candidate);
103
111
  mkdirSync(candidate, { mode: 0o700 });
@@ -106,6 +114,7 @@ try {
106
114
  mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
107
115
  writeFileSync(path, Buffer.from(file.data, "base64"), { flag: "wx", mode: 0o600 });
108
116
  }
117
+ cpSync(join(work, "artifact.gz"), join(candidate, "artifact.gz"));
109
118
  cpSync(join(work, "node"), join(candidate, "node"), { recursive: true, dereference: false, verbatimSymlinks: true });
110
119
  const deps = join(work, "dependencies");
111
120
  plainDirectory(deps);
package/src/handshake.ts CHANGED
@@ -4,7 +4,7 @@ import type { ServerBuild } from "./startup/managed-types.ts";
4
4
  import { PROTOCOL_VERSION, type HelloCommand, type HelloData } from "./protocol.ts";
5
5
 
6
6
  /** Kept equal to package.json `version`; a test pins that. */
7
- export const SERVER_VERSION = "0.1.2";
7
+ export const SERVER_VERSION = "0.2.0";
8
8
 
9
9
  export const SERVER_EXTENSION_VERSIONS: Readonly<Record<string, string>> = { "pi-better-server": SERVER_VERSION };
10
10
 
@@ -121,6 +121,7 @@ export async function resolveTarget(options: TargetOptions): Promise<Target> {
121
121
  const ensureServer = options.ensureServer !== false && (options.agent ?? process.env.PI_SERVER_AGENT ?? "pi") === "pi";
122
122
  if (!options.host) {
123
123
  let socketPath = options.socket;
124
+ const requestedDir = options.remoteDir ? absolutePath(options.remoteDir, "--remote-dir") : undefined;
124
125
  let serverDir: string | undefined;
125
126
  const candidate = ensureServer && !options.socket ? discoverLocalRuntime() : undefined;
126
127
  if (candidate) {
@@ -133,7 +134,7 @@ export async function resolveTarget(options: TargetOptions): Promise<Target> {
133
134
  checkAbort();
134
135
  if (discovery.exitCode !== 0) throw new Error(`Runtime discovery: ${discovery.stderr.trim() || "launcher failed"}. ${INSTALL_GUIDANCE}`);
135
136
  const runtime = parseRuntime(discovery.stdout);
136
- serverDir = process.env.PI_SERVER_DIR || runtime.defaultServerDir;
137
+ serverDir = requestedDir ?? (process.env.PI_SERVER_DIR || runtime.defaultServerDir);
137
138
  progress("server");
138
139
  const result = await runner.runOnce({
139
140
  shell: false, argv: [runtime.launcher, ...ensureArgs(serverDir)],
@@ -144,7 +145,7 @@ export async function resolveTarget(options: TargetOptions): Promise<Target> {
144
145
  socketPath = parseReadiness(result.stdout, serverDir).socketPath;
145
146
  }
146
147
  if (socketPath === undefined) {
147
- serverDir = defaultServerDir();
148
+ serverDir = requestedDir ?? defaultServerDir();
148
149
  socketPath = socketPathFor(serverDir);
149
150
  }
150
151
  return {
@@ -4,10 +4,24 @@ import { CancellableLoader, truncateToWidth } from "@earendil-works/pi-tui";
4
4
  export interface ConnectionProgress {
5
5
  signal: AbortSignal;
6
6
  stage(message: string): void;
7
+ /** SSH is up. Later stages are work on the remote, not the connection itself. */
8
+ sshConnected(): void;
7
9
  }
8
10
 
9
11
  type Outcome<T> = { kind: "connected"; value: T } | { kind: "failed"; error: unknown } | { kind: "cancelled" };
10
12
 
13
+ interface StageRecord {
14
+ message: string;
15
+ startedAt: number;
16
+ durationMs?: number;
17
+ }
18
+
19
+ /** Compact durations: one decimal under ten seconds, whole seconds after that. */
20
+ export function formatStageDuration(ms: number): string {
21
+ const seconds = Math.max(0, ms) / 1000;
22
+ return seconds < 10 ? `${seconds.toFixed(1)}s` : `${Math.round(seconds)}s`;
23
+ }
24
+
11
25
  /** Owns the loading screen only; late resources from a cancelled attempt are disposed. */
12
26
  export async function withConnectionProgress<T>(
13
27
  ui: Pick<ExtensionUIContext, "custom">,
@@ -20,43 +34,83 @@ export async function withConnectionProgress<T>(
20
34
  try {
21
35
  outcome = await ui.custom<Outcome<T>>((tui, theme, _keys, done) => {
22
36
  const controller = new AbortController();
37
+ const startedAt = Date.now();
38
+ const stages: StageRecord[] = [];
23
39
  const loader = new CancellableLoader(tui, text => theme.fg("accent", text), text => theme.fg("muted", text), `Connecting to ${host}: preparing...`);
24
40
  let finished = false;
25
41
  let abandoned = false;
42
+ let sshReady = false;
43
+ const prefix = () => sshReady ? "Remote" : `Connecting to ${host}`;
44
+ const paint = (message: string, started = Date.now()) => {
45
+ loader.setMessage(`${prefix()}: ${message} · ${formatStageDuration(Date.now() - started)}`);
46
+ };
47
+ // Elapsed labels tick even when the current stage produces no new messages.
48
+ const ticker = setInterval(() => {
49
+ if (finished) return;
50
+ const current = stages.at(-1);
51
+ if (current) paint(current.message, current.startedAt);
52
+ tui.requestRender();
53
+ }, 500);
54
+ const stage = (message: string) => {
55
+ if (finished) return;
56
+ const current = stages.at(-1);
57
+ if (current?.message === message) return;
58
+ if (current) current.durationMs = Date.now() - current.startedAt;
59
+ stages.push({ message, startedAt: Date.now() });
60
+ if (!finished) loader.setMessage(`${prefix()}: ${message}`);
61
+ tui.requestRender();
62
+ };
63
+ const sshConnected = () => {
64
+ if (finished || sshReady) return;
65
+ sshReady = true;
66
+ const current = stages.at(-1);
67
+ if (current) loader.setMessage(`${prefix()}: ${current.message}`);
68
+ tui.requestRender();
69
+ };
70
+ const stop = () => {
71
+ clearInterval(ticker);
72
+ loader.stop();
73
+ };
26
74
  abandon = () => {
27
75
  if (finished) return;
28
76
  finished = true;
29
77
  abandoned = true;
30
78
  controller.abort();
31
- loader.stop();
79
+ stop();
32
80
  };
33
81
  loader.onAbort = () => { if (!finished) { abandon!(); done({ kind: "cancelled" }); } };
34
82
  void Promise.resolve().then(() => {
35
83
  controller.signal.throwIfAborted();
36
- return connect({
37
- signal: controller.signal,
38
- stage: message => { if (!finished) loader.setMessage(`Connecting to ${host}: ${message}`); },
39
- });
84
+ return connect({ signal: controller.signal, stage, sshConnected });
40
85
  }).then(value => {
41
86
  if (abandoned) { void Promise.resolve().then(() => disposeLate(value)).catch(() => undefined); return; }
42
87
  finished = true;
43
- loader.stop();
88
+ stop();
44
89
  done({ kind: "connected", value });
45
90
  }, error => {
46
91
  if (abandoned) return;
47
92
  finished = true;
48
- loader.stop();
93
+ stop();
49
94
  done({ kind: "failed", error });
50
95
  });
51
96
  return {
52
- render: width => width > 0 ? [...loader.render(width), theme.fg("dim", truncateToWidth("Esc cancel", width, ""))] : [],
97
+ render: width => {
98
+ if (width <= 0) return [];
99
+ const fit = (text: string) => truncateToWidth(text, width, "...");
100
+ const now = Date.now();
101
+ const history = stages.slice(0, -1).map(doneStage =>
102
+ theme.fg("muted", fit(` ✓ ${doneStage.message} ${formatStageDuration(doneStage.durationMs ?? now - doneStage.startedAt)}`)));
103
+ const connected = sshReady ? [theme.fg("accent", fit(`Connected to ${host}`))] : [];
104
+ const elapsed = theme.fg("dim", fit(`Esc cancel · ${formatStageDuration(now - startedAt)}`));
105
+ return [...history, ...connected, ...loader.render(width), elapsed];
106
+ },
53
107
  handleInput: data => loader.handleInput(data),
54
108
  invalidate: () => loader.invalidate(),
55
- dispose: () => { abandon?.(); loader.dispose(); },
109
+ dispose: () => { clearInterval(ticker); abandon?.(); loader.dispose(); },
56
110
  };
57
111
  });
58
112
  } catch (error) { abandon?.(); throw error; }
59
113
  if (!outcome) { abandon?.(); return undefined; }
60
114
  if (outcome.kind === "failed") throw outcome.error;
61
115
  return outcome.kind === "connected" ? outcome.value : undefined;
62
- }
116
+ }
@@ -8,7 +8,7 @@ import { resolveSession } from "../remote/sessions.ts";
8
8
  import { getPi12Bridge, installPi12Bridge, type Pi12Bridge } from "./pi-1.2-bridge.ts";
9
9
  import { planPackageSync, readLocalPackageCatalog, type PackageCatalog } from "./packages.ts";
10
10
  import { RemoteClientSession } from "./session.ts";
11
- import { availableRemoteHosts, chooseRemoteHost, remoteArgumentCompletions, showRemoteHostList } from "./menu.ts";
11
+ import { availableRemoteHosts, chooseRemoteHost, LOCAL_HOST, remoteArgumentCompletions, showRemoteHostList } from "./menu.ts";
12
12
  import { rememberedServerDir, rememberRemoteHost } from "./profiles.ts";
13
13
  import { browseRemoteSessions } from "./session-browser.ts";
14
14
  import { withConnectionProgress } from "./connection-progress.ts";
@@ -19,9 +19,13 @@ import { browseRemoteFolders } from "./folder-browser.ts";
19
19
  import { showRemoteProgress } from "./remote-progress.ts";
20
20
  import { NATIVE_RECONNECT_CAPABILITIES, openUpgradeTransport } from "./upgrade-transport.ts";
21
21
 
22
- const USAGE = "/remote connect <ssh-alias> [--cwd <remote-path>] [--session <id>] [--remote-dir <server-dir>]";
22
+ const USAGE = "/remote connect <ssh-alias|localhost> [--cwd <remote-path>] [--session <id>] [--remote-dir <server-dir>]";
23
+ /** `localhost` names the daemon on this machine: a plain Unix socket, no SSH setup. */
24
+ export { LOCAL_HOST };
25
+ export const isLocalHost = (host: string): boolean => host === LOCAL_HOST;
23
26
  const UPGRADE_STAGES: Record<string, string> = {
24
27
  artifact: "preparing matching server...", probe: "checking remote platform...", "node-download": "preparing private Node runtime...",
28
+ verifying: "verifying installed server...", "verification-upload": "sending server verification data...",
25
29
  "node-upload": "uploading verified Node runtime...", dependencies: "checking server dependencies...", "dependencies-upload": "uploading verified dependencies...",
26
30
  staged: "matching server staged...", activating: "activating matching server...", ready: "matching server ready...", deferred: "server update staged; current daemon continues...",
27
31
  };
@@ -34,7 +38,8 @@ export function parseRemoteArgs(text: string) {
34
38
  cwd: { type: "string" }, session: { type: "string" }, "remote-dir": { type: "string" },
35
39
  } });
36
40
  if (positionals.length !== 1) throw new Error(`Usage: ${USAGE}`);
37
- return { host: positionals[0]!, cwd: values.cwd, sessionId: values.session, remoteDir: values["remote-dir"] };
41
+ const host = positionals[0] === "local" ? LOCAL_HOST : positionals[0]!;
42
+ return { host, cwd: values.cwd, sessionId: values.session, remoteDir: values["remote-dir"] };
38
43
  }
39
44
 
40
45
  type RemoteOptions = ReturnType<typeof parseRemoteArgs>;
@@ -182,15 +187,22 @@ export async function connectHost(options: RemoteOptions, local: LocalFrontend):
182
187
  let remoteDir = options.remoteDir ?? await rememberedServerDir(options.host);
183
188
  const controlPathRoot = join(process.env.PI_REMOTE_TMP ?? "/tmp", `pi-native-${process.getuid?.() ?? process.pid}`);
184
189
  let deferredUpgrade: string | undefined;
185
- const setup = await withConnectionProgress(ui, options.host, async ({ signal, stage }) => {
190
+ const setup = await withConnectionProgress(ui, options.host, async ({ signal, stage, sshConnected }) => {
186
191
  let pendingTarget: Target | undefined;
187
192
  let pendingClient: DaemonClient | undefined;
188
193
  try {
189
- stage("establishing SSH...");
194
+ const localConnect = isLocalHost(options.host);
195
+ stage(localConnect ? "finding local server..." : "establishing SSH...");
190
196
  pendingTarget = await local.dependencies.resolveTarget({
191
- host: options.host, agent: "pi", controlPathRoot, signal, managedRuntime: true,
197
+ host: localConnect ? undefined : options.host, agent: "pi", controlPathRoot, signal, managedRuntime: true,
192
198
  ...(remoteDir ? { remoteDir } : {}),
193
- onProgress: phase => stage({ ssh: "establishing SSH...", directory: "finding remote server...", server: "starting or checking Pi server...", forward: "opening SSH tunnel..." }[phase]),
199
+ onProgress: phase => {
200
+ // The ssh phase is the connection. Everything after it is work on the remote.
201
+ if (!localConnect && phase !== "ssh") sshConnected();
202
+ stage(localConnect
203
+ ? { directory: "finding local server...", server: "starting or checking Pi server...", ssh: "finding local server...", forward: "connecting to local socket..." }[phase]
204
+ : { ssh: "establishing SSH...", directory: "finding remote server...", server: "starting or checking Pi server...", forward: "opening SSH tunnel..." }[phase]);
205
+ },
194
206
  onUpgradeProgress: (phase, detail) => {
195
207
  if (phase === "deferred") deferredUpgrade = detail;
196
208
  stage(UPGRADE_STAGES[phase] ?? "checking matching server...");
@@ -198,7 +210,12 @@ export async function connectHost(options: RemoteOptions, local: LocalFrontend):
198
210
  });
199
211
  signal.throwIfAborted();
200
212
  stage("contacting Pi server...");
201
- pendingClient = await DaemonClient.connect(pendingTarget.socketPath, { signal, hello: { capabilities: [...NATIVE_RECONNECT_CAPABILITIES] } });
213
+ try {
214
+ pendingClient = await DaemonClient.connect(pendingTarget.socketPath, { signal, hello: { capabilities: [...NATIVE_RECONNECT_CAPABILITIES] } });
215
+ } catch (error) {
216
+ if (!localConnect) throw error;
217
+ throw new Error(`Could not reach the local Pi server at ${pendingTarget.socketPath}: ${error instanceof Error ? error.message : String(error)}. Start it with the pi-better-server CLI or install the native runtime, then retry /remote connect localhost.`);
218
+ }
202
219
  signal.throwIfAborted();
203
220
  stage("checking server compatibility...");
204
221
  const capabilities = pendingClient.server?.capabilities ?? [];
@@ -224,7 +241,8 @@ export async function connectHost(options: RemoteOptions, local: LocalFrontend):
224
241
  : `Server update staged. The current daemon cannot perform a verified automatic handoff and was left running. ${deferredUpgrade}`, safe ? "info" : "warning");
225
242
  }
226
243
  let connection = client;
227
- ui.setStatus("pi-remote", `SSH: ${options.host} (sessions)`);
244
+ const targetLabel = isLocalHost(options.host) ? "local daemon" : `SSH: ${options.host}`;
245
+ ui.setStatus("pi-remote", `${targetLabel} (sessions)`);
228
246
  if (!await syncPackages(connection, local, undefined, { scope: "global", host: options.host, onNotice: message => notices.push(message) })) return;
229
247
  let choice: Exclude<RemoteSessionChoice, { action: "transfer" }> | undefined;
230
248
  for (;;) {
@@ -248,17 +266,18 @@ export async function connectHost(options: RemoteOptions, local: LocalFrontend):
248
266
  if (selectedChoice.action === "create") sessionId = (await connection.call({ type: "create_session", cwd })).sessionId as string;
249
267
  await connection.call({ type: "open_session", sessionId });
250
268
  return RemoteClientSession.connect(connection, sessionId, {
251
- reconnectAfterUpgrade: (notice, signal) => openUpgradeTransport({
252
- host: options.host, agent: "pi", controlPathRoot, managedRuntime: true, ...(remoteDir ? { remoteDir } : {}),
253
- }, local.dependencies, signal, notice.buildId),
269
+ reconnectAfterUpgrade: (notice, signal) => openUpgradeTransport(isLocalHost(options.host)
270
+ ? { agent: "pi", managedRuntime: true, ...(remoteDir ? { remoteDir } : {}) }
271
+ : { host: options.host, agent: "pi", controlPathRoot, managedRuntime: true, ...(remoteDir ? { remoteDir } : {}) },
272
+ local.dependencies, signal, notice.buildId),
254
273
  onReconnected: replacement => {
255
274
  connection = replacement;
256
275
  void closeInitialTransport().catch(error => ui.notify(`Remote tunnel cleanup: ${String(error)}`, "warning"));
257
276
  },
258
277
  onUpgradeStatus: phase => ui.setStatus("pi-remote", phase === "ready"
259
- ? `SSH: ${options.host}` : `SSH: ${options.host} (${phase === "restarting" ? "server restarting" : "reconnecting"})`),
278
+ ? targetLabel : `${targetLabel} (${phase === "restarting" ? "server restarting" : "reconnecting"})`),
260
279
  onDisconnect: () => {
261
- ui.setStatus("pi-remote", `SSH: ${options.host} (disconnected)`);
280
+ ui.setStatus("pi-remote", `${targetLabel} (disconnected)`);
262
281
  ui.notify(`Disconnected from ${options.host}. Remote work has not been aborted. Use /remote disconnect to return locally, then reconnect.`, "warning");
263
282
  },
264
283
  localCommandCompletions: (prefix) => argumentCompletions(prefix, true),
@@ -293,7 +312,7 @@ export async function connectHost(options: RemoteOptions, local: LocalFrontend):
293
312
  await bridge.attach(remote);
294
313
  endBrowse = undefined;
295
314
  attached = true;
296
- ui.setStatus("pi-remote", `SSH: ${options.host}`);
315
+ ui.setStatus("pi-remote", targetLabel);
297
316
  ui.notify(`Attached to ${options.host}:${cwd}. /remote opens the server's sessions; /remote disconnect returns locally.`, "info");
298
317
  } finally {
299
318
  try { endBrowse?.(); }
@@ -6,6 +6,8 @@ import { sshHostAliases } from "./ssh-hosts.ts";
6
6
 
7
7
  type MenuUi = Pick<ExtensionUIContext, "select" | "input">;
8
8
  const OTHER_HOST = "Connect to another SSH host...";
9
+ const LOCAL_HOST_LABEL = "Connect to localhost (this machine, no SSH)";
10
+ export const LOCAL_HOST = "localhost";
9
11
 
10
12
  export async function savedRemoteHosts(agentDir = getAgentDir()): Promise<string[]> {
11
13
  let files;
@@ -36,8 +38,9 @@ export async function showRemoteHostList(ui: Pick<ExtensionUIContext, "select" |
36
38
 
37
39
  export async function chooseRemoteHost(ui: MenuUi, hosts: readonly string[]): Promise<string | undefined> {
38
40
  const labels = hosts.map((host) => `Connect to ${host}`);
39
- const choice = await ui.select("Remote", [...labels, OTHER_HOST]);
41
+ const choice = await ui.select("Remote", [LOCAL_HOST_LABEL, ...labels, OTHER_HOST]);
40
42
  if (choice === undefined) return undefined;
43
+ if (choice === LOCAL_HOST_LABEL) return LOCAL_HOST;
41
44
  const index = labels.indexOf(choice);
42
45
  if (index !== -1) return hosts[index];
43
46
  if (choice !== OTHER_HOST) throw new Error("Unknown remote menu choice");
@@ -52,8 +55,10 @@ export function remoteArgumentCompletions(prefix: string, connected = false, hos
52
55
  if (/^(connect|pull)(?:\s|$)/.test(input)) {
53
56
  const action = input.split(/\s+/, 1)[0]!;
54
57
  const hostPrefix = input.slice(action.length).trimStart();
55
- const matches = hosts.filter((host) => host.toLowerCase().startsWith(hostPrefix))
56
- .map((host) => ({ value: `${action} ${host}`, label: host, description: `${action === "connect" ? "Connect to" : "Pull session from"} ${host}` }));
58
+ const candidates = action === "connect" ? [LOCAL_HOST, ...hosts.filter((host) => host !== LOCAL_HOST)] : [...hosts];
59
+ const matches = candidates.filter((host) => host.toLowerCase().startsWith(hostPrefix))
60
+ .map((host) => ({ value: `${action} ${host}`, label: host,
61
+ description: host === LOCAL_HOST ? "Connect to the daemon on this machine" : `${action === "connect" ? "Connect to" : "Pull session from"} ${host}` }));
57
62
  return matches.length ? matches : null;
58
63
  }
59
64
  const values = connected ? ["connect", "list", "sessions", "pull", "disconnect"] : ["connect", "list", "pull"];
@@ -176,12 +176,14 @@ class Controller implements Pi12Bridge {
176
176
  methods(ui, ["clear", "addChild", "requestRender"], "InteractiveMode.ui");
177
177
  if (!Array.isArray(ui.children)) throw failure("InteractiveMode.ui.children is missing.");
178
178
  methods(object(this.mode.editorContainer, "InteractiveMode.editorContainer"), ["render"], "editorContainer");
179
+ methods(object(this.mode.footerContainer, "InteractiveMode.footerContainer"), ["render"], "footerContainer");
179
180
  const header = object(this.mode.headerContainer, "InteractiveMode.headerContainer");
180
181
  methods(header, ["render"], "headerContainer");
181
182
  writable(header, "render");
182
183
  if (ui.mode === "fullscreen") {
183
184
  methods(ui, ["setLayoutRoot"], "InteractiveMode.ui");
184
- object(this.mode.fullscreenLayoutRoot, "InteractiveMode.fullscreenLayoutRoot");
185
+ const root = object(this.mode.fullscreenLayoutRoot, "InteractiveMode.fullscreenLayoutRoot");
186
+ if (typeof root.constructor !== "function" || root.constructor === Object) throw failure("fullscreen layout cannot compose the browse footer.");
185
187
  }
186
188
  }
187
189
 
@@ -194,6 +196,12 @@ class Controller implements Pi12Bridge {
194
196
  const ui = this.mode.ui as Native;
195
197
  const roots = [...ui.children];
196
198
  const layoutRoot = this.mode.fullscreenLayoutRoot;
199
+ // Reuse Pi 1.2's native stack type without importing a newer TUI API on SDK 0.82.
200
+ const browseRoot = ui.mode === "fullscreen" ? new layoutRoot.constructor([
201
+ { component: this.mode.editorContainer, basis: 0, grow: 1, shrink: 1, minSize: 0 },
202
+ { component: this.mode.footerContainer, basis: "auto", grow: 0, shrink: 0 },
203
+ ]) : undefined;
204
+ if (browseRoot) methods(browseRoot, ["render"], "browse layout");
197
205
  let active = true;
198
206
  const cleanup = () => {
199
207
  if (!active) return;
@@ -206,11 +214,11 @@ class Controller implements Pi12Bridge {
206
214
  };
207
215
  this.endBrowse = cleanup;
208
216
  try {
209
- // Native custom/select/input screens all use this container. Unmount the
210
- // surrounding local view, not its children or its still-live runtime.
217
+ // Keep the live footer/status map, but hide the local transcript and widgets.
211
218
  ui.clear();
212
219
  ui.addChild(this.mode.editorContainer);
213
- if (ui.mode === "fullscreen") ui.setLayoutRoot(this.mode.editorContainer);
220
+ ui.addChild(this.mode.footerContainer);
221
+ if (ui.mode === "fullscreen") ui.setLayoutRoot(browseRoot);
214
222
  ui.requestRender(true);
215
223
  } catch (error) {
216
224
  cleanup();
@@ -1,5 +1,6 @@
1
1
  import type { ExtensionUIContext } from "@earendil-works/pi-coding-agent";
2
2
  import { CancellableLoader, truncateToWidth } from "@earendil-works/pi-tui";
3
+ import { formatStageDuration } from "./connection-progress.ts";
3
4
 
4
5
  type Outcome<T> = { value: T } | { error: unknown } | undefined;
5
6
 
@@ -14,11 +15,19 @@ export async function showRemoteProgress<T>(
14
15
  const cancellable = options.cancellable !== false;
15
16
  const result = await ui.custom<Outcome<T>>((tui, theme, _keys, done) => {
16
17
  let disposed = false;
18
+ const startedAt = Date.now();
17
19
  const safeMessage = `${host}: ${message}`.replace(/[\x00-\x1f\x7f-\x9f]/g, " ");
18
20
  const loader = new CancellableLoader(tui, text => theme.fg("accent", text), text => theme.fg("muted", text), safeMessage);
21
+ // Keep the wait visibly alive: the elapsed label ticks even when nothing else changes.
22
+ const ticker = setInterval(() => {
23
+ if (disposed) return;
24
+ loader.setMessage(`${safeMessage} · ${formatStageDuration(Date.now() - startedAt)}`);
25
+ tui.requestRender();
26
+ }, 500);
19
27
  const finish = (value: Outcome<T>) => {
20
28
  if (disposed) return;
21
29
  disposed = true;
30
+ clearInterval(ticker);
22
31
  loader.stop();
23
32
  done(value);
24
33
  };
@@ -31,7 +40,7 @@ export async function showRemoteProgress<T>(
31
40
  render: width => width > 0 ? [...loader.render(width), theme.fg("dim", truncateToWidth(cancellable ? "Esc cancel" : "Waiting for the remote operation to finish", width, ""))] : [],
32
41
  handleInput: data => { if (cancellable) loader.handleInput(data); },
33
42
  invalidate: () => loader.invalidate(),
34
- dispose: () => { disposed = true; loader.dispose(); },
43
+ dispose: () => { disposed = true; clearInterval(ticker); loader.dispose(); },
35
44
  };
36
45
  });
37
46
  if (result && "error" in result) throw result.error;
@@ -115,7 +115,8 @@ export class RemoteSessionBrowser implements Component {
115
115
  if (previous && visibleWidth(`${previous} ${command}`) <= width) legend[legend.length - 1] = `${previous} ${command}`;
116
116
  else legend.push(fit(command));
117
117
  }
118
- let header = [theme.bold(fit(`Remote: ${singleLine(this.host)}`)),
118
+ const hostLabel = this.host === "localhost" ? "Local daemon" : `Remote: ${singleLine(this.host)}`;
119
+ let header = [theme.bold(fit(hostLabel)),
119
120
  ...(this.options.cwd ? [theme.fg("muted", fit(`Folder: ${singleLine(this.options.cwd)}`))] : [])];
120
121
  let details = selected ? [
121
122
  ...wrapTextWithAnsi(singleLine(selected.name || "Untitled session"), width).slice(0, 2).map(line => theme.fg("accent", line)),
@@ -134,7 +135,8 @@ export class RemoteSessionBrowser implements Component {
134
135
  if (fixed() + minimumBody + scrollRoom > budget) notices = [];
135
136
  while (header.length && fixed() + minimumBody + scrollRoom > budget) header.pop();
136
137
  const available = Math.max(0, budget - fixed());
137
- const unreservedHeight = Math.min(10, available);
138
+ // Use the height the terminal offers; only very short windows shed rows.
139
+ const unreservedHeight = available;
138
140
  const entryCount = rows.length + (unreservedHeight >= 4 ? new Set(rows.map(session => session.cwd)).size : 0);
139
141
  const bodyHeight = Math.max(0, unreservedHeight - (entryCount > unreservedHeight && available > 1 ? 1 : 0));
140
142
  const grouped = bodyHeight >= 4;
@@ -84,14 +84,17 @@ export async function runRemoteTransfer(args: RemoteTransferArgs, frontend: Tran
84
84
  let client: DaemonClient | undefined;
85
85
  let operationFailed = false;
86
86
  try {
87
- const setup = await withConnectionProgress(ui, host, async ({ signal, stage }) => {
87
+ const setup = await withConnectionProgress(ui, host, async ({ signal, stage, sshConnected }) => {
88
88
  let pendingTarget: Target | undefined;
89
89
  let pendingClient: DaemonClient | undefined;
90
90
  try {
91
91
  stage("establishing SSH...");
92
92
  pendingTarget = await (frontend.resolveTarget ?? resolveTarget)({
93
93
  host, agent: "pi", signal, ...(remoteDir ? { remoteDir } : {}),
94
- onProgress: phase => stage({ ssh: "establishing SSH...", directory: "finding remote server...", server: "starting or checking Pi server...", forward: "opening SSH tunnel..." }[phase]),
94
+ onProgress: phase => {
95
+ if (phase !== "ssh") sshConnected();
96
+ stage({ ssh: "establishing SSH...", directory: "finding remote server...", server: "starting or checking Pi server...", forward: "opening SSH tunnel..." }[phase]);
97
+ },
95
98
  });
96
99
  signal.throwIfAborted();
97
100
  stage("contacting Pi server...");
@@ -298,11 +298,21 @@ export const defaultActivationPorts: ActivationPorts = {
298
298
  export async function runActivationWorker(request: UpgradeRequest, ports: ActivationPorts = defaultActivationPorts): Promise<ActivationResult> {
299
299
  const serverDir = canonicalStateDir(request.serverDir);
300
300
  let release: () => void;
301
- try { release = claimDaemonOwner(serverDir, LOCK); }
302
- catch (error) {
303
- const journal = readActivationJournal(serverDir);
304
- if (journal) return journal.desiredBuild.contentId === request.runtime.build.contentId ? result(journal) : conflict(journal);
305
- return { status: "deferred", operationId: request.operationId, reason: `Activation coordinator already owns this directory: ${message(error)}` };
301
+ for (let attempt = 0; ; attempt++) {
302
+ try { release = claimDaemonOwner(serverDir, LOCK); break; }
303
+ catch (error) {
304
+ const journal = readActivationJournal(serverDir);
305
+ // A staged journal can still name the abandoned build while the coordinator
306
+ // awaits stale-owner proof. Keep this worker alive so its caller keeps waiting.
307
+ if (journal?.phase === "staged" && journal.desiredBuild.contentId !== request.runtime.build.contentId
308
+ && journal.rollbackPermit === undefined && reservedAgainst(request, journal.operationId)
309
+ && inspectDaemonOwner(serverDir, LOCK).status === "live" && attempt < 300) {
310
+ await ports.pause();
311
+ continue;
312
+ }
313
+ if (journal) return journal.desiredBuild.contentId === request.runtime.build.contentId ? result(journal) : conflict(journal);
314
+ return { status: "deferred", operationId: request.operationId, reason: `Activation coordinator already owns this directory: ${message(error)}` };
315
+ }
306
316
  }
307
317
  let journal: ActivationJournal | undefined;
308
318
  try {
@@ -3,7 +3,7 @@ import { posix } from "node:path";
3
3
  import { decodeServerArtifact } from "./artifact.ts";
4
4
  import { absolutePath, probeRemoteRuntime, shellQuote } from "./runtime.ts";
5
5
  import type { RunRemote, ServerArtifact, StagedRuntime } from "./managed-types.ts";
6
- import { NODE_CHECKSUMS, validateStaged } from "../../scripts/private-runtime/format.ts";
6
+ import { NODE_CHECKSUMS, NODE_EXECUTABLE_CHECKSUMS, validateStaged } from "../../scripts/private-runtime/format.ts";
7
7
 
8
8
  export interface StageRuntimeOptions {
9
9
  run: RunRemote;
@@ -61,30 +61,90 @@ export async function stageRuntime(options: StageRuntimeOptions): Promise<Staged
61
61
 
62
62
  signal?.throwIfAborted();
63
63
  signal?.addEventListener("abort", cancel, { once: true });
64
- onProgress?.("node-download");
65
- signal?.throwIfAborted();
66
- const archive = `node-v${artifact.build.nodeVersion}-${probe.platform}`;
67
- const url = `https://nodejs.org/dist/v${artifact.build.nodeVersion}/${archive}.tar.gz`;
68
- const sha = NODE_CHECKSUMS[probe.platform];
69
- const tar = `${work}/node.tar.gz`;
70
- const remote = await run(`curl -q --fail --silent --show-error --location --proto '=https' --connect-timeout 10 --max-time 120 ${q(url)} -o ${q(tar)}`, undefined, 125_000);
71
- signal?.throwIfAborted();
72
- if (remote.exitCode !== 0 || remote.timedOut) {
73
- onProgress?.("node-upload");
74
- await checked(`cat > ${q(tar)}`, await download(url, `sha256-${sha}`, signal), 120_000);
64
+ const finalRoot = `${root}/releases/${artifact.build.contentId}`;
65
+ const cachedArtifact = `${finalRoot}/artifact.gz`;
66
+ const artifactPath = `${work}/artifact.gz`;
67
+ // Older releases may lack the archive. Its contents are authenticated by the fresh installer against the requested build.
68
+ const archiveCache = await checked(`set -eu
69
+ p=${q(finalRoot)}
70
+ while [ "$p" != / ]; do
71
+ [ ! -L "$p" ] || { echo 'corrupt cache: symlink release path' >&2; exit 1; }
72
+ [ ! -e "$p" ] || { [ -d "$p" ] && [ -x "$p" ]; } || { echo 'corrupt cache: unsafe release directory' >&2; exit 1; }
73
+ p=$(dirname "$p")
74
+ done
75
+ if [ -L ${q(cachedArtifact)} ]; then echo 'corrupt cache: artifact symlink' >&2; exit 1; fi
76
+ if [ ! -e ${q(cachedArtifact)} ]; then
77
+ if [ -e ${q(finalRoot)} ]; then printf 'legacy\\n'; else printf 'absent\\n'; fi
78
+ exit 0
79
+ fi
80
+ [ -f ${q(cachedArtifact)} ] || { echo 'corrupt cache: expected regular artifact' >&2; exit 1; }
81
+ [ "$(wc -c < ${q(cachedArtifact)})" -le 33554432 ] || { echo 'corrupt cache: artifact size limit' >&2; exit 1; }
82
+ cp ${q(cachedArtifact)} ${q(artifactPath)}
83
+ [ "$(wc -c < ${q(artifactPath)})" -le 33554432 ] || { echo 'corrupt cache: artifact size limit' >&2; exit 1; }
84
+ if command -v sha256sum >/dev/null 2>&1; then actual=$(sha256sum ${q(artifactPath)} | cut -d ' ' -f 1); else actual=$(shasum -a 256 ${q(artifactPath)} | cut -d ' ' -f 1); fi
85
+ printf 'reuse:%s\\n' "$actual"`, undefined, 120_000);
86
+ const archiveResponse = archiveCache.stdout.trim();
87
+ const archiveDigest = /^reuse:([a-f0-9]{64})$/.exec(archiveResponse)?.[1];
88
+ const archiveState = archiveDigest ? "reuse" : archiveResponse;
89
+ if (archiveState !== "reuse" && archiveState !== "absent" && archiveState !== "legacy") throw new Error("Runtime staging: unexpected artifact cache probe result");
90
+ if (archiveState !== "reuse") {
91
+ onProgress?.("verification-upload");
92
+ await checked(`cat > ${q(artifactPath)}`, artifact.bytes, 120_000);
75
93
  }
76
- await checked(`set -eu; if command -v sha256sum >/dev/null 2>&1; then actual=$(sha256sum ${q(tar)} | cut -d ' ' -f 1); else actual=$(shasum -a 256 ${q(tar)} | cut -d ' ' -f 1); fi; [ "$actual" = ${q(sha)} ] || { echo 'Node archive integrity mismatch' >&2; exit 1; }; tar -xzf ${q(tar)} -C ${q(work)}; mv ${q(`${work}/${archive}`)} ${q(`${work}/node`)}; rm ${q(tar)}`, undefined, 120_000);
77
- await checked(`cat > ${q(`${work}/artifact.gz`)}`, artifact.bytes);
78
94
  for (const name of ["installer.ts", "format.ts"]) {
79
95
  const file = payload.files.find((entry) => entry.path === `scripts/private-runtime/${name}`)!;
80
96
  await checked(`cat > ${q(`${work}/${name}`)}`, Buffer.from(file.data, "base64"));
81
97
  }
82
- const invoke = (offline: boolean) => `env -i HOME=${q(`${work}/home`)} PATH=${q(`${work}/node/bin:/usr/bin:/bin`)} ${q(`${work}/node/bin/node`)} ${q(`${work}/installer.ts`)} ${q(work)} ${q(root)} ${q(artifact.sha256)} ${offline ? "offline" : "online"}`;
83
- onProgress?.("dependencies");
98
+ const cachedNode = `${finalRoot}/node/bin/node`;
99
+ const node = `${work}/node/bin/node`;
100
+ onProgress?.("verifying");
101
+ // Authenticate the scratch copy before executing any bytes from the cached release.
102
+ const cached = await checked(`set -eu
103
+ p=${q(`${root}/releases`)}
104
+ while [ "$p" != / ]; do
105
+ [ ! -L "$p" ] || { echo 'corrupt cache: symlink release path' >&2; exit 1; }
106
+ [ ! -e "$p" ] || { [ -d "$p" ] && [ -x "$p" ]; } || { echo 'corrupt cache: unsafe release directory' >&2; exit 1; }
107
+ p=$(dirname "$p")
108
+ done
109
+ [ ! -L ${q(finalRoot)} ] || { echo 'corrupt cache: release symlink' >&2; exit 1; }
110
+ if [ ! -e ${q(finalRoot)} ]; then printf 'absent\\n'; exit 0; fi
111
+ [ -d ${q(finalRoot)} ] && [ -x ${q(finalRoot)} ] || { echo 'corrupt cache: expected accessible release directory' >&2; exit 1; }
112
+ p=${q(cachedNode)}
113
+ while [ "$p" != ${q(finalRoot)} ]; do
114
+ [ ! -L "$p" ] || { echo 'corrupt cache: symlink Node path' >&2; exit 1; }
115
+ p=$(dirname "$p")
116
+ done
117
+ [ -f ${q(cachedNode)} ] && [ -x ${q(cachedNode)} ] || { echo 'corrupt cache: expected regular Node executable' >&2; exit 1; }
118
+ mkdir -p ${q(`${work}/node/bin`)}
119
+ cp ${q(cachedNode)} ${q(node)}
120
+ if command -v sha256sum >/dev/null 2>&1; then actual=$(sha256sum ${q(node)} | cut -d ' ' -f 1); else actual=$(shasum -a 256 ${q(node)} | cut -d ' ' -f 1); fi
121
+ [ "$actual" = ${q(NODE_EXECUTABLE_CHECKSUMS[probe.platform])} ] || { echo 'Node executable integrity mismatch' >&2; exit 1; }
122
+ printf 'reuse\\n'`, undefined, 120_000);
123
+ const cachedState = cached.stdout.trim();
124
+ if (cachedState !== "reuse" && cachedState !== "absent") throw new Error("Runtime staging: unexpected cache probe result");
125
+ if (cachedState === "absent" && archiveState !== "absent") throw new Error("Runtime staging: cached release disappeared during verification");
126
+ const reuse = cachedState === "reuse";
127
+ if (!reuse) {
128
+ onProgress?.("node-download");
129
+ signal?.throwIfAborted();
130
+ const archive = `node-v${artifact.build.nodeVersion}-${probe.platform}`;
131
+ const url = `https://nodejs.org/dist/v${artifact.build.nodeVersion}/${archive}.tar.gz`;
132
+ const sha = NODE_CHECKSUMS[probe.platform];
133
+ const tar = `${work}/node.tar.gz`;
134
+ const remote = await run(`curl -q --fail --silent --show-error --location --proto '=https' --connect-timeout 10 --max-time 120 ${q(url)} -o ${q(tar)}`, undefined, 125_000);
135
+ signal?.throwIfAborted();
136
+ if (remote.exitCode !== 0 || remote.timedOut) {
137
+ onProgress?.("node-upload");
138
+ await checked(`cat > ${q(tar)}`, await download(url, `sha256-${sha}`, signal), 120_000);
139
+ }
140
+ await checked(`set -eu; if command -v sha256sum >/dev/null 2>&1; then actual=$(sha256sum ${q(tar)} | cut -d ' ' -f 1); else actual=$(shasum -a 256 ${q(tar)} | cut -d ' ' -f 1); fi; [ "$actual" = ${q(sha)} ] || { echo 'Node archive integrity mismatch' >&2; exit 1; }; tar -xzf ${q(tar)} -C ${q(work)}; mv ${q(`${work}/${archive}`)} ${q(`${work}/node`)}; rm ${q(tar)}`, undefined, 120_000);
141
+ }
142
+ const invoke = (mode: "online" | "offline" | "reuse-only") => `env -i HOME=${q(`${work}/home`)} PATH=${q(`${work}/node/bin:/usr/bin:/bin`)} ${q(node)} ${q(`${work}/installer.ts`)} ${q(work)} ${q(root)} ${q(archiveDigest ?? artifact.sha256)} ${mode} ${q(artifact.build.contentId)}`;
143
+ if (!reuse) onProgress?.("dependencies");
84
144
  signal?.throwIfAborted();
85
- let installed = await run(invoke(false), undefined, 600_000);
145
+ let installed = await run(invoke(reuse ? "reuse-only" : "online"), undefined, 600_000);
86
146
  signal?.throwIfAborted();
87
- if (installed.exitCode === 75) {
147
+ if (!reuse && installed.exitCode === 75) {
88
148
  onProgress?.("dependencies-upload");
89
149
  const lock = JSON.parse(Buffer.from(payload.files.find((f) => f.path === "scripts/private-runtime/package-lock.json")!.data, "base64").toString());
90
150
  await checked(`mkdir -p ${q(`${work}/archives`)}`);
@@ -98,7 +158,7 @@ export async function stageRuntime(options: StageRuntimeOptions): Promise<Staged
98
158
  const failed = batch.find((result) => result.status === "rejected");
99
159
  if (failed?.status === "rejected") throw failed.reason;
100
160
  }
101
- installed = await run(invoke(true), undefined, 600_000);
161
+ installed = await run(invoke("offline"), undefined, 600_000);
102
162
  signal?.throwIfAborted();
103
163
  }
104
164
  if (installed.exitCode !== 0 || installed.timedOut) throw new Error(`Runtime staging: ${installed.stderr || "installer failed"}`);