pi-better-server 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/README.md +624 -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 +396 -0
  76. package/src/remote-client/folder-browser.ts +165 -0
  77. package/src/remote-client/host.ts +130 -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 +345 -0
  81. package/src/remote-client/pi-1.2-bridge.ts +542 -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 +270 -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
package/README.md CHANGED
@@ -1,3 +1,625 @@
1
- # Temporary Holding Version
1
+ # pi-better-server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A daemon that hosts several Pi `AgentSession`s behind one local Unix socket, so
4
+ sessions keep running when no client is attached and come back after a crash.
5
+
6
+ ## Run
7
+
8
+ ```sh
9
+ node src/cli.ts # Node >= 22.18 runs the .ts directly
10
+ ```
11
+
12
+ Files live under `~/.pi/agent/server/` (override with `PI_SERVER_DIR`):
13
+
14
+ - `pi-server.sock`, mode `0600`, the only listener. There is no TCP port.
15
+ - `sessions.json`, the index of sessions and whether each is `running` or `closed`.
16
+
17
+ The directory is created with mode `0700` and tightened if it already exists.
18
+ Each session's conversation is an ordinary Pi session JSONL in the usual
19
+ `~/.pi/agent/sessions/` tree.
20
+
21
+ ### Session and daemon lifetime
22
+
23
+ An active session is an open session, not a connected client or a currently
24
+ generating model. Disconnecting does not close it. By default:
25
+
26
+ - A session expires after **24 hours of inactivity**, even if an idle client is
27
+ attached. Expiry closes its runtime but keeps its transcript and index row.
28
+ Reopen it from the Closed tab to continue; interrupted tools are not replayed.
29
+ - Executing models, tools, shell commands, compaction, and observable
30
+ session-owned background work prevent expiry, including silent execution.
31
+ A fresh inactivity window starts when execution finishes. Waiting for user
32
+ input is idle; expiry cancels pending dialogs rather than approving them.
33
+ - A daemon with no active sessions shuts down after **30 minutes**. Polling,
34
+ heartbeats, and idle browser connections do not keep it alive.
35
+
36
+ Configure independent millisecond durations in `PI_SERVER_DIR/lifecycle.json`:
37
+
38
+ ```json
39
+ {
40
+ "sessionIdleMs": 86400000,
41
+ "daemonIdleMs": 1800000
42
+ }
43
+ ```
44
+
45
+ `0` disables the corresponding timer. Precedence is programmatic daemon options,
46
+ then `PI_SERVER_SESSION_IDLE_MS` / `PI_SERVER_DAEMON_IDLE_MS`, then the saved file,
47
+ then defaults. Values must be non-negative safe integers. Changes take effect
48
+ on the next daemon start. The daemon owns the clocks; idle session deadlines
49
+ survive restarts and include time offline. Renaming, listing, reading snapshots,
50
+ and passive reconnect traffic do not refresh session activity.
51
+
52
+ The server directory also contains an exclusive `daemon-owner/` claim. A live
53
+ process owner is never evicted because a timer or connection attempt expired.
54
+ Crash recovery reclaims dead ownership before reading or resuming the session
55
+ index, preventing concurrent starters from creating competing transcript writers.
56
+
57
+ The current Subagents provider scopes work by session. Older providers without
58
+ ownership information are handled conservatively: process-wide active work can
59
+ keep other idle sessions alive too. If a caller supplies a custom resource loader
60
+ without activity observation, automatic expiry is disabled for that runtime;
61
+ manual close remains available. Unknown external processes are not treated as
62
+ observable session-owned work.
63
+
64
+ ## Protocol
65
+
66
+ Strict LF-delimited JSON lines. A session command is a Pi RPC command (the
67
+ `RpcCommand` payloads from `@earendil-works/pi-coding-agent`) plus `sessionId`.
68
+ Daemon commands: `list_sessions`, `create_session`, `open_session`,
69
+ `close_session`. Control commands, each addressed to one `sessionId`:
70
+ `subscribe`, `acquire_control`, `release_control`, `extension_ui_response`.
71
+ Responses use Pi's `{ type: "response", command, success }` shape and echo `id`
72
+ and `sessionId`.
73
+
74
+ Events reach a connection only after `subscribe` (or, for the connection that
75
+ issued `create_session`, from the start). `open_session` loads a session but
76
+ does not stream. Each event is `{ type: "event", sessionId, seq, event }`, where
77
+ `seq` counts up per session. `subscribe { sessionId, sinceSeq? }` first replays
78
+ the retained events after `sinceSeq` (omit it for live only), then streams live;
79
+ its response reports `truncated: true` when some of those events are no longer
80
+ retained. Subscribing again on the same connection replaces the earlier
81
+ subscription.
82
+
83
+ An extension dialog (select, confirm, input, editor) is held until someone
84
+ answers it; it shows as `needsInput` in `list_sessions` and `get_state`.
85
+ `acquire_control` takes the single controller lease (it also ends when the
86
+ connection drops) and returns the pending dialogs; `release_control` gives it
87
+ back. Only the lease holder may send `extension_ui_response { sessionId,
88
+ requestId, value | confirmed | cancelled }`.
89
+
90
+ `steer` while a turn runs is delivered after the current tool calls and before
91
+ the next LLM call. `steer` on an idle session starts the next turn.
92
+ `new_session`, `switch_session`, `fork` and `clone` are refused: one session id
93
+ owns one session file.
94
+
95
+ ## Handshake
96
+
97
+ A client may open with `hello { protocolVersion, piVersion?, extensionVersions?, capabilities? }`.
98
+ The daemon answers with its own versions and capabilities, plus the managed
99
+ `build` and daemon `instanceId` when available. Native clients supporting transport
100
+ replacement announce `runtime-reconnect-v1`; eligible daemons advertise
101
+ `safe-upgrade-v1`.
102
+ It rejects the client, with an error naming both sides, then closes the
103
+ connection, when the protocol versions differ or when a stated `piVersion` is on
104
+ a different Pi major.minor. Extension versions are reported, never enforced.
105
+ A client that skips `hello` is still served.
106
+
107
+ ## Native remote client (`/remote`, experimental)
108
+
109
+ The native client provides an experimental VS Code Remote-style workflow:
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
112
+ the model, tools, workspace and session state. Your local conversation stays separate
113
+ unless you explicitly choose to move or copy it after connecting.
114
+
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)
119
+ for busy sessions, older daemons and manual launcher overrides.
120
+
121
+ ### Connect and disconnect
122
+
123
+ The opt-in extension is loaded through the normal `pi.extensions` package manifest
124
+ (`src/remote-client/extension.ts`), not a separate client launcher. Configure the
125
+ package before starting Pi: loading it later with `/reload` cannot capture the
126
+ startup bridge. Wait for local work, including `!` commands, to finish before
127
+ connecting.
128
+
129
+ ```text
130
+ /remote
131
+ /remote list
132
+ /remote connect
133
+ /remote connect r5
134
+ /remote r5
135
+ /remote r5 --cwd /home/user/workspaces/project
136
+ /remote r5 --session <id-or-unique-prefix>
137
+ /remote r5 --remote-dir /home/user/.pi/agent/server
138
+ /remote disconnect
139
+ /remote sessions
140
+ /remote pull
141
+ /remote pull r5 --session <id-or-unique-prefix> --cwd /local/existing/project
142
+ /remote pull r5 --session <id> --copy
143
+ ```
144
+
145
+ `/remote list` displays SSH aliases and previously entered hosts. Select a host
146
+ and press Enter to confirm a connection. `/remote connect` opens a host picker;
147
+ `/remote connect r5` connects directly. Root slash-command autocomplete shows
148
+ actions only. Host suggestions appear only after `connect`, with a complete
149
+ `connect <host>` completion value. `/remote r5` remains a supported shorthand.
150
+
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
+ remote sessions or shared SSH connection. Connection failures retain their original
155
+ error message; the spinner does not imply that an unreachable host is available.
156
+
157
+ Connecting opens the server's session landing page after extension synchronization,
158
+ including when the local session has history. The browser takes over a clean native
159
+ screen; leaving it or cancelling setup restores the local view and history.
160
+ Selecting an explicit `--session` attaches directly after the same extension check.
161
+ The landing page has **Active sessions** and **Closed sessions** tabs, with sessions
162
+ grouped by their full working folder. Move and Copy remain explicit actions when
163
+ a local conversation is available; connecting alone never authorizes a transfer.
164
+ The browser displays its keyboard shortcuts:
165
+
166
+ | Key | Action |
167
+ | --- | --- |
168
+ | Up / Down | Select a session |
169
+ | Tab / Shift-Tab / Left / Right | Switch tabs |
170
+ | Enter | Attach to the selected session; reopen it if closed |
171
+ | `x` | Close the selected active session; confirm if busy or waiting for input |
172
+ | F2 | Rename the selected session, including a closed session without reopening it |
173
+ | `n` | Browse remote folders before starting a new session |
174
+ | `r` | Refresh the list |
175
+ | `m` / `c` | Move / copy the local conversation; choose a destination folder and transfer scope first |
176
+ | Escape | Leave the server browser |
177
+
178
+ New Session opens a folder picker. Up / Down selects a folder, Enter opens it,
179
+ `s` chooses the current folder, and `n` creates a new child folder there. The
180
+ parent-folder entry navigates up; Escape returns to the same session selection.
181
+ Creating a folder navigates into it but does not start a session until you press
182
+ `s`. Existing folders, files, and symbolic links are never replaced. If the
183
+ default workspace root is missing, navigate to its parent and explicitly create
184
+ or select a directory; browsing does not create missing directories automatically.
185
+
186
+ Native loaders show progress while loading the browser, listing folders, creating
187
+ a folder, checking or installing extensions, and opening or starting a session.
188
+ Escape can dismiss a read-only wait. Writes that the daemon cannot cancel keep
189
+ their progress visible until the outcome is known. Folder browsing requires a
190
+ daemon advertising `folder-browser-v1`; older daemons can still list and attach
191
+ existing sessions and show update guidance when folder browsing is requested.
192
+
193
+ Fenced and moved sessions cannot be attached, closed or renamed from the browser.
194
+ While attached, `/remote` or `/remote sessions` returns to this host-level page
195
+ without stopping remote work. The local conversation remains separate.
196
+
197
+ The catalog deduplicates literal SSH `Host` aliases (including `Include` files)
198
+ and local `/remote` history. Wildcard and negated SSH patterns are not concrete
199
+ hosts and are omitted. Entered hosts are remembered even if the connection fails
200
+ or uses the default server directory; no credentials are recorded in this history.
201
+
202
+ `r5` is an SSH alias. The folder picker starts at the remote workspace root:
203
+ `PI_SERVER_WORKSPACES_DIR`, or `~/workspaces/` when unset. The landing page's Folder
204
+ line shows this starting context, not a filter on existing sessions. Existing
205
+ sessions remain visible and retain their own folders. Use an explicit `--cwd`
206
+ with another absolute path to change where folder browsing begins; it also refuses
207
+ attaching an existing session from a different workspace. You can navigate to
208
+ other directories accessible to the SSH user. `--session` selects a session
209
+ directly without changing its working directory.
210
+ `--remote-dir` selects the remote daemon's server directory and is saved per host
211
+ with its connection history. It is reused on later connections to that
212
+ host; otherwise the usual remote server-directory discovery applies.
213
+
214
+ `/remote disconnect` restores the original local history in a fresh local runtime.
215
+ After a handoff, that original history stays read-only; resume a returned transcript
216
+ using the path printed by `/remote pull`. Disconnecting releases the connection
217
+ without aborting the remote session or its work.
218
+ A lost connection disables remote commands; use `/remote disconnect` to return
219
+ locally, then connect again. There is no automatic server setup: provision the
220
+ remote daemon, workspace and provider credentials separately.
221
+
222
+ ### Move or copy a conversation
223
+
224
+ Sending the local session is part of `/remote connect`; there is no separate
225
+ `/remote push` command. Choose move or copy, then the transfer scope and destination.
226
+ A final confirmation shows the session, source, destination, scope and ownership
227
+ outcome before a transfer begins.
228
+
229
+ The default is a **conversation-only handoff** into an existing folder. Project
230
+ files in that folder are untouched, and neither folder needs to be a Git repository.
231
+ Workspace files are optional and require a new or empty destination. A transfer
232
+ never merges existing conversations.
233
+
234
+ A handoff keeps the session ID and fences the source before taking its snapshot.
235
+ The source becomes read-only after the destination acknowledges ownership. If the
236
+ outcome cannot be determined, the source stays fenced and recovery guidance is
237
+ printed. Do not start another writer until that outcome is resolved. A copy gets
238
+ a new session ID, and both conversations remain independently writable.
239
+
240
+ `/remote pull` brings a remote session back. While connected it defaults to that
241
+ host and session; otherwise it offers host and session selection. `--copy` keeps
242
+ the remote source writable. `--with-workspace` includes files, and `--cwd` selects
243
+ the local destination. Pulling a handoff of the currently attached session also
244
+ disconnects that remote view. The result prints the local transcript path and its
245
+ `pi --session` command; retained older snapshots are not writable substitutes.
246
+
247
+ Native transfers gzip the archive **before sending it over the connection**.
248
+ Conversation entries are retained, not compacted; transcript metadata records the
249
+ destination folder and, for copies, the new ID. Decoded archives are limited to
250
+ 1 GiB and checked before import. Both ends must advertise `session-transfer-v1`
251
+ and `compressed-bundle-v1`. Legacy raw archives remain readable. Provider
252
+ credentials and machine settings are not synchronized, but conversation text and
253
+ optional workspace files can contain secrets: review the scope before approving.
254
+
255
+ ### Compatibility and controls
256
+
257
+ The native bridge in `src/remote-client/pi-1.2-bridge.ts` uses private Pi internals
258
+ and supports **exactly Pi 1.2.0** on the local client. This is narrower than the
259
+ daemon's general Pi compatibility. Client and daemon Pi major.minor versions must
260
+ match, and the remote daemon must be upgraded to code advertising
261
+ `native-client-v1` and `session-browser-v1`. An older daemon is refused before the local runtime is replaced.
262
+ This describes work in development, not a production release.
263
+
264
+ Core native controls for `/model`, `/thinking` and `!` shell commands operate on
265
+ the remote session. While connected, these local/session-management operations
266
+ are blocked: `/new`, `/fork`, `/clone`, `/tree`, `/resume`, `/import`,
267
+ `/trust`, `/share`, `/settings`, `/login`, `/logout`, `/export`, `/debug`,
268
+ `/scoped-models` and `/bug`. Disconnect before using them locally.
269
+
270
+ Standard remote extension dialogs (select, confirm, input, editor), notifications,
271
+ status and text widgets can be presented locally. Arbitrary remote `ctx.ui.custom`
272
+ screens, custom component widgets and remote extension renderers are not supported.
273
+ Synchronizing a package installation does not provide full extension UI parity.
274
+
275
+ ### Automatic server updates
276
+
277
+ Native `/remote connect` builds an artifact from the client's installed package
278
+ files, including unpublished source changes. A Git checkout is not required.
279
+ The build identity includes the source, target platform, SDK, Node version and
280
+ dependency lock. Supported remote targets are Linux and macOS on x64 and arm64.
281
+
282
+ The server runs from an immutable release under
283
+ `~/.pi-better-server/managed/releases/<build-id>`, outside `node_modules`. Each
284
+ release contains private Node **24.14.1** and SDK **1.2.0** dependencies installed
285
+ on the target. Node checksums and locked dependency integrity are verified. If
286
+ target downloads fail, the client downloads and uploads verified archives instead.
287
+ Concurrent connectors share the same release only after integrity validation.
288
+ Published releases are not overwritten to repair corruption.
289
+
290
+ Staging can proceed while sessions run. Activation waits for all sessions to be
291
+ idle, including SDK preflight and settlement, queued messages, compaction, shell
292
+ commands, dialogs and observable background work. Native cache warming is also
293
+ protected, including pending decision and provider requests. Activity observation
294
+ does not hold the upgrade admission fence while waiting. Unsupported SDK guards
295
+ or unobservable activity defer activation rather than establishing idleness.
296
+
297
+ An eligible daemon records the stop commitment, closes execution admission and
298
+ notifies attached native clients before releasing ownership. The successor adopts
299
+ the same state directory only after that release. Each client keeps its existing
300
+ session adapter and UI bindings, validates the new build and daemon instance, and
301
+ reconciles its snapshot, event cursor and controller lease. Interrupted requests
302
+ are not replayed. Recovery reconnects to the announced build in the selected
303
+ state directory; it does not install or activate the recovering client's build.
304
+ An unannounced connection failure still requires reconnecting.
305
+
306
+ The runtime update does not rerun bootstrap, install its default extension list,
307
+ copy credentials or rewrite agent preferences. Remote-only packages and session
308
+ histories remain in their existing directories. Global runtime registration is
309
+ updated only after verified readiness for the registered default state directory.
310
+ Workspace package synchronization remains a separate approval step below.
311
+
312
+ Older daemons without `safe-upgrade-v1`, unknown owners, incompatible protocols
313
+ and SDK downgrades are deferred. A missing socket or elapsed timeout is not
314
+ permission to replace a live owner. An unverified legacy state directory may need
315
+ an explicit migration before automatic activation can proceed. The client leaves
316
+ the old daemon running and reports the reason instead of killing it.
317
+
318
+ Activation records live in `<serverDir>/activation.json` and `activation.log`.
319
+ `recovery-required` preserves an ambiguous or adopted candidate for inspection;
320
+ it does not authorize another writer or a rollback. Automatic rollback is limited
321
+ to a proven candidate exit before adoption and restores code only, not settings,
322
+ packages or history. Repeating that failed operation does not stop the restored
323
+ runtime. A fresh request needs verified rollback completion and ownership before
324
+ starting another attempt. Do not delete ownership files to force an update.
325
+
326
+ An explicit `PI_SERVER_COMMAND` opts out of managed installation and keeps that
327
+ absolute launcher authoritative. Older SDK CLI clients retain registered-launcher
328
+ startup by default. Codex daemons and explicit local sockets are not managed by
329
+ this native installation workflow.
330
+
331
+ ### Reload remote extensions
332
+
333
+ While connected, `/reload` reloads the daemon's extension runtime, tools and
334
+ commands, then refreshes native client metadata and command completion. It does
335
+ not reload laptop extensions or settings. The daemon must advertise
336
+ `remote-reload-v1`; older daemons return update guidance.
337
+
338
+ Reload requires idle sessions because Pi changes process-wide provider
339
+ registrations. Model, tool, bash, compaction and observable background work,
340
+ pending activity checks, dialogs and runtime maintenance prevent reload. It
341
+ preserves conversation history, event subscriptions and the controller lease.
342
+ A failed runtime rebuild is fenced; explicitly close and reopen that session
343
+ before executing again.
344
+
345
+ ### Package synchronization
346
+
347
+ Immediately after connecting, before the session browser opens, the client reads
348
+ the locally configured, installed npm/git package catalog and compares it with the
349
+ remote host's global catalog. It resolves npm packages to their installed exact
350
+ versions and git packages to full installed commit pins. The confirmation previews
351
+ additions and replacements, including `extensions`, `skills`, `prompts`, `themes`
352
+ filters and `autoload`. Declining skips synchronization and continues to the
353
+ browser with the installed remote catalog. Remote-only packages are retained.
354
+
355
+ Only approved package declarations are synchronized. Credentials, settings outside
356
+ those declarations and local extension/resource sources are not copied. Unsupported
357
+ local resources are summarized once, with repeated selectors collapsed rather
358
+ than printed as dozens of identical warnings. The approved target is the remote
359
+ host's global package configuration, not a workspace chosen later in the browser.
360
+ Trusted project declarations remain untouched and can still override global
361
+ packages in that workspace; manage those declarations on the remote host.
362
+
363
+ Host-level sync requires `global-package-sync-v1`. Older daemons keep their existing
364
+ sessions and extensions; the client reports that updates are deferred and still
365
+ opens the browser. Busy work is not aborted and sessions are never closed just to
366
+ update packages. New daemons require idle sessions and refuse concurrent runtime
367
+ loading or maintenance. Approved updates automatically refresh hosted runtimes and
368
+ connected clients. Installation stops on the first failure; earlier successful
369
+ installs are not rolled back, so idle runtimes are refreshed after a partial install.
370
+ Explicit legacy and busy refusals defer the update; other installation failures
371
+ remain errors rather than being reported as success.
372
+
373
+ ### Verification status
374
+
375
+ Earlier real-host verification used bundled Pi 1.2.0 on the laptop with the native
376
+ UI: `!hostname` returned `r5`, and a model-driven remote tool call returned
377
+ `CLIENT_REMOTE_OK r5`. Disconnect, reconnect and lost-transport recovery restored
378
+ the expected local and remote histories.
379
+
380
+ The complete server suite passes on both supported SDK test layouts: **702 passed,
381
+ 18 expected skips on SDK 0.82.1**, and **713 passed, 7 expected skips on SDK 1.2.0**.
382
+ Each layout covers 720 tests with no failures or cancellations. Both TypeScript
383
+ checks pass. Skips cover SDK-specific behavior and opt-in installation checks.
384
+ Test workers are bounded to four to avoid oversubscribing subprocess-heavy fixtures.
385
+
386
+ Real-process upgrade checks attach two native session adapters to one managed
387
+ daemon, defer activation during a gated tool, reconnect both views, and continue
388
+ with their original objects, history and UI bindings. Pull-copy and move use the
389
+ replacement clients. See [upgrade integration](test/remote-upgrade-native.test.ts),
390
+ [transport races](test/remote-upgrade-reconnect.test.ts),
391
+ [startup admission](test/startup-admission.test.ts), and
392
+ [SDK quiescence](test/maintenance-sdk-quiescence.test.ts).
393
+
394
+ An actual Pi 1.2.0 terminal journey passed 44 checks against the current complete
395
+ backend and client. It verified busy deferral, transport-only recovery without
396
+ another activation, unchanged UI and session object identities, live replies,
397
+ pull-copy and disconnect. No local model ran during attachment, and cleanup left
398
+ no owned processes or sockets.
399
+
400
+ Separate private installations on macOS arm64 and Linux x64 verified Node 24.14.1,
401
+ SDK 1.2.0 and sealed-release reuse. The macOS check exercised client-download and
402
+ upload fallback. A Linux SSH cancellation check entered a bounded dependency
403
+ subprocess, aborted its transport, and verified scratch and lock cleanup while
404
+ preserving a published-release sentinel. Synthetic agent files remained unchanged;
405
+ these installer checks did not start a production daemon.
406
+
407
+ Earlier native Pi 1.2.0 checks verified browser creation and its first model
408
+ reply, live updates and controller access after pull-copy, and newly reloaded
409
+ commands and tools without reconnecting. Both native journeys used private fake
410
+ providers, not external model credentials. See the regressions for
411
+ [new-session selection](test/remote-new-session-model.test.ts),
412
+ [attached-source copies](test/remote-pull-copy-live.test.ts), and
413
+ [remote reload](test/remote-reload.test.ts).
414
+
415
+ A separate temporary daemon on `r5` verified compressed copy and handoff in both
416
+ SSH directions, returned-session continuation, and remote reload. Its repetitive
417
+ 740,842-byte seeded transcript travelled in a 3,550-byte archive, a 99.52% reduction;
418
+ original conversation entries and existing destination files were preserved.
419
+ All owned test runtimes were stopped. The active host daemon was not upgraded or
420
+ restarted. These checks are development compatibility evidence, not full custom
421
+ extension UI parity or a production release.
422
+
423
+ ## pi-remote
424
+
425
+ ```sh
426
+ node src/remote-cli.ts ls [--host <ssh-alias>]
427
+ node src/remote-cli.ts new --host <h> --cwd <dir> "<prompt>"
428
+ node src/remote-cli.ts steer <session> "<message>"
429
+ node src/remote-cli.ts tail <session>
430
+ node src/remote-cli.ts answer <session> [--request <id>] (--value <text> | --confirm | --deny | --cancel)
431
+ node src/remote-cli.ts move <session> --to <ssh-alias> [--to-remote-dir <dir>] [--to-cwd <dir>]
432
+ ```
433
+
434
+ For Pi sessions, `pi-remote attach` still opens the daemon's companion console in
435
+ tmux (over SSH for a remote host). It is not the native local `/remote` client
436
+ described above.
437
+
438
+ A session is named by id, unique id prefix, or name. `ls` shows status (running,
439
+ idle, needs-input), last activity, cwd and git branch. `steer` queues into a
440
+ running turn and starts a turn on an idle session. `tail` follows live events
441
+ until Ctrl-C and remembers the last event `seq` it saw per session; the next `tail` asks the daemon to replay what it missed (`subscribe` with `sinceSeq`). `answer` takes the controller lease, answers a dialog an extension is waiting on, and gives the lease back; without an answer flag it lists the pending dialogs.
442
+
443
+ `--host` reaches a daemon on another machine: `pi-remote` opens an SSH
444
+ ControlMaster to the alias (through `packages/ssh-core`), forwards the daemon's
445
+ Unix socket to a private local one with `ssh -O forward`, talks to that, and
446
+ cancels the forward on exit. `--remote-dir` names the daemon's server dir there;
447
+ by default the remote shell is asked (`$PI_SERVER_DIR`, else
448
+ `$PI_CODING_AGENT_DIR/server`, else `~/.pi/agent/server`). Each subcommand is its
449
+ own module under `src/remote/`, registered in `src/remote-cli.ts`.
450
+
451
+ Tests against a real host: `PI_REMOTE_TEST_HOST=<alias> PI_REMOTE_TEST_HOST_ROOT=<dir>
452
+ npm test`, where the dir holds a Node and Pi as installed by `scripts/bootstrap-host.sh`.
453
+
454
+ ## Moving a session (`pi-remote move`)
455
+
456
+ `pi-remote move <session> --to <ssh-alias>` moves a session and its git workspace to
457
+ another daemon (`--host` picks the source daemon, default local; `--to-socket <path>`
458
+ targets a daemon on this machine). Steps: wait for a safe boundary (no turn running;
459
+ `--wait <s>`, default 30) -> fence the source -> bundle -> chunked transfer over the
460
+ daemons' own sockets (the SSH forward carries it) -> target verifies the archive sha256
461
+ and every manifest checksum, rebuilds the workspace, checks the rebuilt tree against the
462
+ manifest's per-file digest, opens the session (the acknowledgement) -> source retires.
463
+ The workspace lands under the target's `<server dir>/workspaces/<session id>/` unless
464
+ `--to-cwd` is given.
465
+
466
+ Ownership: each daemon keeps `ownership.json` (`owned` -> `fenced` -> `moved`, with an
467
+ `epoch`). A fenced or moved session refuses every command and is not resumed on boot, so
468
+ there is never a second live writer. Any failure before the acknowledgement aborts the
469
+ target and unfences the source. If the target cannot be reached to learn whether it
470
+ took the session, the source stays fenced and says so; `pi-remote move --abort <session>`
471
+ unfences it once the target is known not to hold it. If the target owns the session and only
472
+ retiring the source failed, the message prints `pi-remote move --retire <session> --move-id <id>
473
+ [--moved-to <daemon-id>]`; never `--abort` in that state. A workspace holding an untracked nested
474
+ git repository or a submodule is refused (commit/push it separately or move it out), never moved
475
+ with it silently missing. Staged vs unstaged state is not
476
+ preserved (dirty changes arrive unstaged); a committed `.env` stays in history.
477
+
478
+ The agent-agnostic core lives in `src/core/` (no Pi imports): `bundle.ts`
479
+ (createBundle / verifyBundle / materializeWorkspace / digestWorktree), `ownership.ts`,
480
+ `transfer.ts`, `exclusions.ts`. `src/move/` is the Pi glue.
481
+
482
+ Bundle format (`formatVersion: 1`), a tar of regular files:
483
+
484
+ | member | content |
485
+ | --- | --- |
486
+ | `manifest.json` | below |
487
+ | `git.bundle` | `git bundle` of the branch (or `HEAD`) plus the base ref |
488
+ | `tracked.patch` | `git diff --binary HEAD` of dirty tracked files (optional) |
489
+ | `untracked/<path>` | untracked, non-ignored files that pass the exclusion rules |
490
+ | `session/<name>`, `state/<name>` | session transcript files and session-scoped harness state |
491
+
492
+ Manifest: `{formatVersion, createdAt, agent:{kind,version,extensions}, session:{id,name?,model?,createdAt?,metadata?},
493
+ ownership:{epoch,from,moveId}, repo:{remote?,branch?,head,baseRef?,baseSha?}, files:[{path,role,sha256,size}],
494
+ symlinks:[{path,target}], excluded:[{path,reason:"credential"|"generated"}], worktree:[{path,sha256,mode}],
495
+ totals:{files,bytes,worktreeFiles,worktreeBytes}}`. `files` checksums every archive member;
496
+ `worktree` is the sha256 (and `644`/`755`/`symlink` mode) of every file the restored tree must hold.
497
+ Never bundled: any file whose name starts with `.env` (`.env`, `.env.local`, `.envrc`, `.env-prod`, ...), `.npmrc`/`.netrc`/`.git-credentials`, `auth|credentials|secrets.*`, `id_*`, `*.pem|key|p12|pfx|jks`,
498
+ `.ssh/.aws/.gnupg/.kube/.docker` content, `node_modules`, build output and caches, anything git ignores, and no
499
+ Pi/`gh`/provider auth files (only the transcript and an index row are read from the agent dir).
500
+
501
+ ## Codex threads (`pi-better-server --agent codex`)
502
+
503
+ The same `move` core carries a Codex thread. Run one daemon per Codex host (`pi-better-server --agent codex`, or
504
+ `PI_SERVER_AGENT=codex`); it speaks the daemon socket protocol for `list_sessions`, the move commands and
505
+ `codex_endpoint`, and keeps Codex's own app-server running through `codex app-server daemon start`. Settings:
506
+ `PI_CODEX_BIN` (the `codex` executable), `CODEX_HOME` (default `~/.codex`), `PI_CODEX_VERSION` (refuse to run unless
507
+ `codex --version` is exactly this).
508
+
509
+ - **What travels:** the thread's rollout file (`sessions/YYYY/MM/DD/rollout-*-<id>.jsonl`) plus the workspace bundle.
510
+ The app-server rebuilds its state db and paginated history from the rollout, so nothing else is needed. The import
511
+ rewrites only the `cwd`, `runtime_workspace_roots` and `workspace_roots` fields of `session_meta`, `turn_context` and
512
+ `thread_settings_applied` records to the rebuilt workspace; conversation text is untouched. The source thread is archived (the tombstone).
513
+ - **Never travels:** `auth.json` or any Codex credential. The target host signs in on its own (`codex login`).
514
+ - **Model provider:** a thread keeps the provider it was recorded under (`session_meta.model_provider`), and a host's sign-in belongs
515
+ to the providers that host configured, so before anything is fenced `pi-remote move` asks the source for the thread's provider and
516
+ the target whether its Codex can use it (configured in `config.toml`, or built in and signed in; an API-key login belongs to the
517
+ host's default provider, not to the built-in `openai`). If not, the move is refused naming the provider and nothing is changed; the
518
+ target checks again at import. `--codex-provider <id>` (on `move` and `return`) rebinds the thread to a provider the destination
519
+ has: the import rewrites only `session_meta.model_provider` and the `model_provider_id` of `thread_settings_applied` events. The
520
+ thread's model is not changed, so pick a provider that serves it.
521
+ - **Version pin:** the bundle records `codex --version`; the target refuses unless its own is identical. `pi-remote
522
+ attach` refuses the same way. `PI_CODEX_VERSION` pins a host to one version outright.
523
+ - **Socket only:** the app-server is reached through its unix control socket, locally or ssh-forwarded; there is no
524
+ TCP listener. `pi-remote attach [--host h] <thread> [-- <codex options>]` forwards that socket and runs
525
+ `codex resume <thread> --remote unix://<forwarded socket>`.
526
+ - **Not carried:** thread goals, queued messages and read receipts live in separate Codex databases and stay behind.
527
+ The fence archives the thread on the source app-server, which unloads it for every client (pi-remote attach,
528
+ `codex resume --remote`, anything else), so none can start or continue a turn until the move is aborted
529
+ (the thread is unarchived) or retired. A turn already running is waited for before fencing; one that starts in the
530
+ instant between the last busy check and the archive is not interrupted by the fence itself.
531
+
532
+ ### Steer, list, return
533
+
534
+ - `pi-remote ls [--host h]` lists threads (status `running`, `idle`, or `error: <message>` when the thread's last turn failed, e.g. a 401 from the provider). Threads that moved away are archived and still listed, as `closed` (moved).
535
+ - `pi-remote steer [--host h] <thread> "<message>"` goes through the app-server: `turn/steer` while a turn runs (the text joins the
536
+ turn at its next model call), `turn/start` when idle. The reply says which one happened. A turn that fails right after it starts (a rejected key, say) is reported instead: `steer` prints the error and exits 1 (the watch lasts `PI_CODEX_TURN_WATCH_MS`, default 3000). A fenced or moved thread refuses.
537
+ - `pi-remote return --host h <thread> [--to-cwd <empty dir>] [--codex-provider <id>] [--wait s]` is the move in the other direction: the host's thread is the
538
+ source and this machine's Codex daemon the target (the running one in `PI_SERVER_DIR`, else one started for the command). The host
539
+ keeps the thread fenced until this machine acknowledges it, so a failed return leaves it live on the host; afterwards the host's copy is archived.
540
+ The workspace goes back to where the thread lived before it moved when that directory is free, otherwise pass `--to-cwd`.
541
+ While this machine's daemon is running it holds the thread, so a standalone `codex resume` / `codex exec resume` is refused ("already has an active writer"): continue with `pi-remote attach <thread>` or `pi-remote steer <thread> "<message>"`.
542
+ - Codex plugin: `codex plugin marketplace add <this package>/codex-plugin`, then `codex plugin add pi-remote@pi-remote`. It adds a skill and four
543
+ tools (`remote_detach`, `remote_ls`, `remote_steer`, `remote_return`) that run `pi-remote` (`PI_REMOTE_BIN` names the executable).
544
+
545
+ ## Crash recovery
546
+
547
+ A session stays `running` until explicit close or inactivity expiry. On start the
548
+ daemon reopens owned running sessions at the last entry in their JSONL. It does
549
+ not start a turn or replay interrupted tools on its own. Persisted inactivity
550
+ continues across downtime; interrupted execution receives a fresh idle window.
551
+
552
+ ## Host bootstrap
553
+
554
+ Bootstrap is optional for native `/remote connect`. It remains available for
555
+ manual installations and registered-launcher CLI startup. Managed runtime updates
556
+ do not rerun bootstrap or install the extension defaults listed here.
557
+
558
+ `scripts/bootstrap-host.sh [PREFIX]` installs a pinned Node, a pinned Pi and this
559
+ package's `src/` under `PREFIX` (default `~/.pi-better-server`) with no root, and
560
+ writes `PREFIX/bin/pi-server`. It atomically registers that launcher, agent
561
+ directory and default server directory in `$HOME/.pi/remote-server.json`, mode
562
+ `0600`. Native `/remote` and `pi-remote` use that same registration, so aliases
563
+ such as `115` and `r5` select the same default state directory. Explicit
564
+ `--remote-dir` remains authoritative. `PI_SERVER_COMMAND` may select an absolute
565
+ installed launcher path; it is not a shell command.
566
+
567
+ `pi-server ensure` prints one JSON readiness record and exits after starting or
568
+ reusing the detached daemon. Its log is `<serverDir>/daemon.log`; connection
569
+ cancellation does not kill an already launched daemon. No login script, tmux
570
+ session, or boot service is needed. Codex transport callers use
571
+ `pi-remote --agent codex ...` or `PI_SERVER_AGENT=codex`; Pi on-demand startup and
572
+ these lifecycle timers do not manage Codex daemons.
573
+
574
+ Bootstrap also installs and enables these Pi packages by default through
575
+ `pi install`:
576
+
577
+ | Package | Pinned version | Version override |
578
+ | --- | --- | --- |
579
+ | `@vanillagreen/pi-codex-minimal-tools` | `2.1.4` | `MINIMAL_TOOLS_VERSION` |
580
+ | `@juicesharp/rpiv-ask-user-question` | `2.13.9` | `ASK_USER_QUESTION_VERSION` |
581
+ | `@juicesharp/rpiv-web-tools` | `2.13.9` | `WEB_TOOLS_VERSION` |
582
+ | `pi-better-harness` | `0.31.0` | `HARNESS_VERSION` |
583
+
584
+ Pi registers the packages in `PI_CODING_AGENT_DIR` (default `~/.pi/agent`), so native
585
+ Pi and daemon sessions using that agent directory load the same extensions. Set
586
+ `PI_CODING_AGENT_DIR` both when
587
+ bootstrapping and when launching Pi/the daemon if using an isolated agent directory:
588
+
589
+ ```sh
590
+ export PI_CODING_AGENT_DIR="$HOME/.pi-server-agent"
591
+ PI_VERSION=1.2.0 scripts/bootstrap-host.sh
592
+ ~/.pi-better-server/bin/pi-server
593
+ ```
594
+
595
+ Provider and web-search credentials are still provisioned separately on the host.
596
+ The daemon's attach console does not gain native Pi's custom extension screens;
597
+ use native Pi on the host in tmux for those screens. The local native `/remote`
598
+ client above also cannot transport arbitrary custom screens. Project workspaces
599
+ belong outside the runtime installation, for example under `~/workspaces/`.
600
+
601
+ `PI_VERSION=1.0.0` picks the Pi version (default 0.82.1);
602
+ the daemon works on Pi 0.82 and 1.x, and `hello` reports the installed one. On Pi 1.x the
603
+ `prompt`, `steer` and `follow_up` responses carry Pi's `data.disposition`
604
+ (`started`, `handled` or `queued`); on 0.82 they carry no data.
605
+ `scripts/test-on-pi.sh <pi-version>` runs the package tests against any Pi version in an
606
+ isolated install, leaving the repo's lockfile alone.
607
+
608
+ ## Detach and return (`/detach`, `pi-remote return`)
609
+
610
+ `/detach <ssh-alias> [--remote-dir <dir>] [--to-cwd <dir>]` is a Pi command (registered by `src/detach/extension.ts`, listed under `pi.extensions`). It moves the current plain local session and its workspace into the daemon on that host with the same move protocol as `pi-remote move`; this machine stands in as the source (`LocalSource`). Afterwards the local session is read-only (input is refused with a pointer to `return`); follow the remote one with `pi-remote tail <session> --host <alias>` and `steer`, use `pi-remote attach` for the companion console, or connect from another local Pi process with native `/remote` above.
611
+
612
+ `pi-remote return --host <alias> <session> [--to-cwd <empty dir>]` pulls it back: the workspace is rebuilt (default: where it lived before the detach if that directory is gone or empty; /detach leaves the original in place, so normally a new `<name>-returned` directory beside it, which the command prints; the original is never touched), the transcript is placed in Pi's session directory, and the daemon's copy is retired (`moved`; its workspace directory is left on the host). A returned session can be detached again.
613
+
614
+ Preflight runs before anything is fenced, and a refusal leaves the source untouched:
615
+
616
+ - the daemon answers and speaks this protocol; Pi (same major.minor) and pi-better-server are the pinned versions. Otherwise the refusal names `scripts/bootstrap-host.sh` (user-local install) as the fix.
617
+ - provider credentials resolve on the receiving side (a dry run, no model call); `gh auth status` passes when the repo remote is on GitHub (`PI_REMOTE_GH` overrides the binary).
618
+ - free disk at the workspace location is at least 3x the bundle plus a reserve (`PI_REMOTE_MIN_FREE_BYTES`, default 256 MiB).
619
+ - the repo remote answers `git ls-remote` from the receiving side.
620
+
621
+ The daemon exposes these checks as `move_preflight`; that RPC does not install
622
+ or upgrade a runtime. Connection setup follows the managed or registered-launcher
623
+ policy above before transfer preflight runs.
624
+
625
+ If `/detach` leaves this machine's copy fenced (the target was unreachable, or its reply was lost), the error prints the recovery command. It acts on this machine's record and first asks the daemon whether it holds the session: `pi-remote recover <session> --abort --host <alias>` reopens the local session when the daemon does not hold it; `pi-remote recover <session> --retire --move-id <id> --host <alias>` records it as moved when the daemon does. A Pi process that detached a session never runs it again, even after a `return`; resume it with `pi --session` in a new process.
@@ -0,0 +1,17 @@
1
+ {
2
+ "name": "pi-remote",
3
+ "plugins": [
4
+ {
5
+ "name": "pi-remote",
6
+ "source": {
7
+ "source": "local",
8
+ "path": "./plugins/pi-remote"
9
+ },
10
+ "policy": {
11
+ "installation": "AVAILABLE",
12
+ "authentication": "ON_USE"
13
+ },
14
+ "category": "Developer Tools"
15
+ }
16
+ ]
17
+ }