pi-better-server 0.0.0-stage → 0.1.0

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