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
@@ -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
+ }
@@ -0,0 +1,13 @@
1
+ {
2
+ "mcpServers": {
3
+ "pi_remote": {
4
+ "command": "node",
5
+ "args": ["./server.mjs"],
6
+ "cwd": ".",
7
+ "env_vars": ["PI_REMOTE_BIN", "PI_SERVER_DIR", "PI_REMOTE_SERVER_DIR", "CODEX_HOME", "PI_CODEX_BIN", "PATH", "HOME"],
8
+ "default_tools_approval_mode": "prompt",
9
+ "startup_timeout_sec": 10,
10
+ "tool_timeout_sec": 900
11
+ }
12
+ }
13
+ }
@@ -0,0 +1,118 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Thin MCP server (stdio, newline-delimited JSON-RPC) that hands each tool call to the
4
+ * shared `pi-remote` CLI. It holds no logic of its own: the CLI does the work, so the
5
+ * Codex plugin and a terminal behave the same. `PI_REMOTE_BIN` names the executable
6
+ * (default `pi-remote`).
7
+ */
8
+ import { execFile } from "node:child_process";
9
+ import { createInterface } from "node:readline";
10
+
11
+ const BIN = process.env.PI_REMOTE_BIN || "pi-remote";
12
+
13
+ const string = (description) => ({ type: "string", description });
14
+ const HOST = string("ssh alias of the machine that runs the Codex daemon (omit for this machine)");
15
+
16
+ /** name -> { description, schema, argv(args) } */
17
+ const TOOLS = {
18
+ remote_ls: {
19
+ description: "List Codex threads on a host with their status (running, idle, needs-input), working directory and last activity.",
20
+ properties: { host: HOST },
21
+ required: [],
22
+ argv: (a) => ["ls", ...hostArgs(a), "--json"],
23
+ },
24
+ remote_steer: {
25
+ description: "Send a message to a Codex thread on a host. Mid-turn it steers the running turn; when idle it starts a turn.",
26
+ properties: { session: string("thread id, unique id prefix, or name"), message: string("text to send"), host: HOST },
27
+ required: ["session", "message"],
28
+ // "--" so a message that starts with "-" stays a message.
29
+ argv: (a) => ["steer", ...hostArgs(a), "--json", "--", need(a, "session"), need(a, "message")],
30
+ },
31
+ remote_detach: {
32
+ description: "Move a Codex thread and its workspace (including uncommitted and untracked files) from this machine to another host. The thread continues there; this machine's copy is archived.",
33
+ properties: {
34
+ session: string("thread id, unique id prefix, or name on this machine"),
35
+ to: string("ssh alias of the destination host"),
36
+ to_cwd: string("absolute directory on the destination for the workspace (optional)"),
37
+ codex_provider: string("model provider id configured on the destination to bind the thread to; needed when the destination cannot use the thread's provider (optional)"),
38
+ wait_seconds: { type: "number", description: "how long to wait for a running turn to finish first (optional)" },
39
+ },
40
+ required: ["session", "to"],
41
+ argv: (a) => ["move", "--json", need(a, "session"), "--to", need(a, "to"), ...opt("--to-cwd", a.to_cwd), ...opt("--codex-provider", a.codex_provider), ...opt("--wait", a.wait_seconds)],
42
+ },
43
+ remote_return: {
44
+ description: "Bring a Codex thread and its workspace back from a host to this machine, then resume it here.",
45
+ properties: {
46
+ session: string("thread id, unique id prefix, or name on the host"),
47
+ host: string("ssh alias of the machine that has the thread"),
48
+ to_cwd: string("empty directory on this machine for the workspace (optional)"),
49
+ codex_provider: string("model provider id configured on this machine to bind the thread to; needed when this machine cannot use the thread's provider (optional)"),
50
+ wait_seconds: { type: "number", description: "how long to wait for a running turn to finish first (optional)" },
51
+ },
52
+ required: ["session", "host"],
53
+ argv: (a) => ["return", "--host", need(a, "host"), "--json", need(a, "session"), ...opt("--to-cwd", a.to_cwd), ...opt("--codex-provider", a.codex_provider), ...opt("--wait", a.wait_seconds)],
54
+ },
55
+ };
56
+
57
+ function need(args, key) {
58
+ const value = args?.[key];
59
+ if (typeof value !== "string" || value.length === 0) throw new Error(`"${key}" is required`);
60
+ if (value.startsWith("-") && key !== "message") throw new Error(`"${key}" must not start with "-"`);
61
+ return value;
62
+ }
63
+ function opt(flag, value) {
64
+ return value === undefined || value === null || value === "" ? [] : [flag, String(value)];
65
+ }
66
+ function hostArgs(args) {
67
+ return typeof args?.host === "string" && args.host ? ["--host", need(args, "host")] : [];
68
+ }
69
+
70
+ function run(argv) {
71
+ return new Promise((resolve) => {
72
+ execFile(BIN, argv, { env: { ...process.env, PI_SERVER_AGENT: "codex" }, encoding: "utf8", maxBuffer: 16 * 1024 * 1024, timeout: 15 * 60_000 }, (error, stdout, stderr) => {
73
+ // Progress goes to stderr; show it only when the command failed, so a successful result stays one JSON document.
74
+ const text = (error ? [stdout.trim(), stderr.trim() && `[stderr]\n${stderr.trim()}`] : [stdout.trim() || stderr.trim()]).filter(Boolean).join("\n");
75
+ resolve({ isError: Boolean(error), text: text || (error ? error.message : "ok") });
76
+ });
77
+ });
78
+ }
79
+
80
+ function send(message) {
81
+ process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", ...message })}\n`);
82
+ }
83
+
84
+ async function handle(request) {
85
+ const { id, method, params } = request;
86
+ if (method === "initialize") {
87
+ return send({ id, result: { protocolVersion: params?.protocolVersion ?? "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "pi-remote", version: "0.1.0" } } });
88
+ }
89
+ if (method === "tools/list") {
90
+ const tools = Object.entries(TOOLS).map(([name, t]) => ({ name, description: t.description, inputSchema: { type: "object", properties: t.properties, required: t.required, additionalProperties: false } }));
91
+ return send({ id, result: { tools } });
92
+ }
93
+ if (method === "tools/call") {
94
+ const tool = TOOLS[params?.name];
95
+ if (!tool) return send({ id, error: { code: -32602, message: `Unknown tool: ${params?.name}` } });
96
+ let argv;
97
+ try {
98
+ argv = tool.argv(params.arguments ?? {});
99
+ } catch (error) {
100
+ return send({ id, result: { isError: true, content: [{ type: "text", text: error.message }] } });
101
+ }
102
+ const outcome = await run(argv);
103
+ return send({ id, result: { isError: outcome.isError, content: [{ type: "text", text: outcome.text }] } });
104
+ }
105
+ if (method === "ping") return send({ id, result: {} });
106
+ if (id !== undefined) send({ id, error: { code: -32601, message: `Method not found: ${method}` } });
107
+ }
108
+
109
+ createInterface({ input: process.stdin }).on("line", (line) => {
110
+ if (!line.trim()) return;
111
+ let request;
112
+ try {
113
+ request = JSON.parse(line);
114
+ } catch {
115
+ return;
116
+ }
117
+ void handle(request).catch((error) => request.id !== undefined && send({ id: request.id, error: { code: -32603, message: String(error?.message ?? error) } }));
118
+ });
@@ -0,0 +1,19 @@
1
+ ---
2
+ name: pi-remote
3
+ description: Move a Codex thread and its workspace to another machine and back, list threads running on a remote host, and send them instructions. Use when the user wants to detach work to a server, check on or steer a remote thread, or bring it back to this machine.
4
+ ---
5
+
6
+ # Pi Remote
7
+
8
+ Four tools from the `pi_remote` MCP server drive the `pi-remote` CLI. They need an ssh alias for the other machine, and `pi-better-server --agent codex` running on it.
9
+
10
+ - `remote_ls`: list threads on a host (or on this machine without `host`). Shows status: `running`, `idle`, `needs-input`.
11
+ - `remote_steer`: send a message to a thread. A running turn takes it at its next model call; an idle thread starts a turn.
12
+ - `remote_detach`: move a thread and its workspace (dirty and untracked files included) from this machine to a host. Do this only when the user asked for it. It waits for the current turn to finish, and this machine's copy is archived afterwards.
13
+ - `remote_return`: bring a thread back from a host and rebuild its workspace here. If the original directory is not empty, pass `to_cwd` with an empty directory. Continue locally with `remote_steer` (or `pi-remote attach <thread id>`); a standalone `codex resume` is refused while the local daemon holds the thread.
14
+
15
+ Rules:
16
+ - Ask for the host alias if the user has not given one. Never guess it.
17
+ - After `remote_detach` the thread lives on the host only. Do not keep working on it here; use `remote_steer` to talk to it and `remote_return` to get it back.
18
+ - Report errors as they come; a failed move leaves the thread where it was.
19
+ - Codex sign-in is never copied between machines. The host needs its own `codex login` before it can run new turns.
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
2
  "name": "pi-better-server",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Daemon that hosts Pi agent sessions behind a local Unix socket with session-addressed Pi RPC.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "src/index.ts",
8
+ "bin": {
9
+ "pi-better-server": "src/cli.ts",
10
+ "pi-remote": "src/remote-cli.ts"
11
+ },
12
+ "files": [
13
+ "src",
14
+ "!src/shared-ssh-core/test-support/**",
15
+ "scripts",
16
+ "codex-plugin",
17
+ "README.md"
18
+ ],
19
+ "keywords": [
20
+ "pi",
21
+ "daemon",
22
+ "rpc"
23
+ ],
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "git+https://github.com/1aboveio/pi-better-harness.git",
27
+ "directory": "packages/pi-better-server"
28
+ },
29
+ "bugs": {
30
+ "url": "https://github.com/1aboveio/pi-better-harness/issues"
31
+ },
32
+ "homepage": "https://github.com/1aboveio/pi-better-harness/tree/main/packages/pi-better-server#readme",
33
+ "publishConfig": {
34
+ "access": "public"
35
+ },
36
+ "pi": {
37
+ "extensions": [
38
+ "./src/detach/extension.ts",
39
+ "./src/remote-client/extension.ts"
40
+ ]
41
+ },
42
+ "scripts": {
43
+ "pretest": "node ../../scripts/sync-shared-ssh-core.mjs",
44
+ "prepack": "node ../../scripts/sync-shared-ssh-core.mjs",
45
+ "test": "node --import tsx --import ../../scripts/isolate-registry.mjs --test --test-concurrency=4 test/*.test.ts",
46
+ "typecheck": "tsc --noEmit",
47
+ "verify": "npm run typecheck && npm test"
48
+ },
49
+ "peerDependencies": {
50
+ "@earendil-works/pi-coding-agent": ">=0.82.0"
51
+ },
52
+ "devDependencies": {
53
+ "@earendil-works/pi-ai": "^0.82.0",
54
+ "@earendil-works/pi-coding-agent": "^0.82.0",
55
+ "@types/node": "^25.0.0",
56
+ "tsx": "^4.22.3",
57
+ "typescript": "^6.0.0"
58
+ },
59
+ "engines": {
60
+ "node": ">=22.0.0"
61
+ }
62
+ }
@@ -0,0 +1,107 @@
1
+ #!/usr/bin/env bash
2
+ # Bootstrap a user-local pi-better-server on a host that has neither node nor pi.
3
+ #
4
+ # scripts/bootstrap-host.sh [PREFIX] (default PREFIX: $HOME/.pi-better-server)
5
+ #
6
+ # The runtime/server live under PREFIX; Pi packages live in the Pi agent directory.
7
+ # Nothing system-wide is touched and no root is needed. The setup pins:
8
+ # NODE_VERSION the Node.js runtime (>= 22.18 so .ts runs without a loader)
9
+ # PI_VERSION @earendil-works/pi-coding-agent
10
+ # HARNESS_VERSION pi-better-harness, installed as a Pi package
11
+ # MINIMAL_TOOLS_VERSION, ASK_USER_QUESTION_VERSION, WEB_TOOLS_VERSION
12
+ # the server this package's own src/, copied from the checkout that holds this script
13
+ # Override package versions with environment variables. Pi registers extensions
14
+ # in PI_CODING_AGENT_DIR (default ~/.pi/agent), shared by native Pi and the daemon.
15
+ set -euo pipefail
16
+
17
+ PREFIX="${1:-${PI_SERVER_PREFIX:-$HOME/.pi-better-server}}"
18
+ NODE_VERSION="${NODE_VERSION:-24.14.1}"
19
+ PI_VERSION="${PI_VERSION:-0.82.1}"
20
+ HARNESS_VERSION="${HARNESS_VERSION:-0.31.0}"
21
+ MINIMAL_TOOLS_VERSION="${MINIMAL_TOOLS_VERSION:-2.1.4}"
22
+ ASK_USER_QUESTION_VERSION="${ASK_USER_QUESTION_VERSION:-2.13.9}"
23
+ WEB_TOOLS_VERSION="${WEB_TOOLS_VERSION:-2.13.9}"
24
+ PKG_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
25
+
26
+ case "$(uname -s)-$(uname -m)" in
27
+ Linux-x86_64) NODE_DIST="linux-x64" ;;
28
+ Linux-aarch64 | Linux-arm64) NODE_DIST="linux-arm64" ;;
29
+ Darwin-arm64) NODE_DIST="darwin-arm64" ;;
30
+ Darwin-x86_64) NODE_DIST="darwin-x64" ;;
31
+ *) echo "unsupported platform: $(uname -s)-$(uname -m)" >&2; exit 1 ;;
32
+ esac
33
+
34
+ mkdir -p "$PREFIX/bin"
35
+ chmod 700 "$PREFIX"
36
+
37
+ NODE_HOME="$PREFIX/node-v$NODE_VERSION-$NODE_DIST"
38
+ if [ ! -x "$NODE_HOME/bin/node" ]; then
39
+ tmp="$(mktemp -d "$PREFIX/.node-download.XXXXXX")"
40
+ trap 'rm -rf "$tmp"' EXIT
41
+ curl -fsSL "https://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-$NODE_DIST.tar.xz" -o "$tmp/node.tar.xz"
42
+ tar -xJf "$tmp/node.tar.xz" -C "$PREFIX"
43
+ fi
44
+ export PATH="$NODE_HOME/bin:$PATH"
45
+ PREFIX="$(node -e 'process.stdout.write(require("node:path").resolve(process.argv[1]))' "$PREFIX")"
46
+ NODE_HOME="$PREFIX/node-v$NODE_VERSION-$NODE_DIST"
47
+ export PATH="$NODE_HOME/bin:$PATH"
48
+ export PI_CODING_AGENT_DIR="${PI_CODING_AGENT_DIR:-$HOME/.pi/agent}"
49
+ export PI_SERVER_DIR="${PI_SERVER_DIR:-$PI_CODING_AGENT_DIR/server}"
50
+
51
+ # Pi itself, pinned. The package.json keeps `npm` from treating $PREFIX as part of another project.
52
+ if [ ! -f "$PREFIX/package.json" ]; then
53
+ printf '{ "name": "pi-better-server-host", "private": true }\n' > "$PREFIX/package.json"
54
+ fi
55
+ (cd "$PREFIX" && npm install --no-audit --no-fund --save-exact "@earendil-works/pi-coding-agent@$PI_VERSION")
56
+
57
+ # Register extensions with Pi, not just npm: the SDK loads configured Pi packages.
58
+ for package in \
59
+ "npm:@vanillagreen/pi-codex-minimal-tools@$MINIMAL_TOOLS_VERSION" \
60
+ "npm:@juicesharp/rpiv-ask-user-question@$ASK_USER_QUESTION_VERSION" \
61
+ "npm:@juicesharp/rpiv-web-tools@$WEB_TOOLS_VERSION" \
62
+ "npm:pi-better-harness@$HARNESS_VERSION"; do
63
+ "$PREFIX/node_modules/.bin/pi" install "$package"
64
+ done
65
+
66
+ # The server stays outside node_modules: Node refuses to run .ts files from there.
67
+ rm -rf "$PREFIX/server"
68
+ mkdir -p "$PREFIX/server"
69
+ cp -R "$PKG_DIR/src" "$PREFIX/server/src"
70
+ printf '{ "type": "module" }\n' > "$PREFIX/server/package.json"
71
+ rev="$(git -C "$PKG_DIR" rev-parse HEAD 2>/dev/null || echo unknown)"
72
+ printf 'node %s\npi %s\npi-better-harness %s\nharness-rev %s\n' "$NODE_VERSION" "$PI_VERSION" "$HARNESS_VERSION" "$rev" > "$PREFIX/VERSIONS"
73
+ printf 'pi-codex-minimal-tools %s\nrpiv-ask-user-question %s\nrpiv-web-tools %s\n' "$MINIMAL_TOOLS_VERSION" "$ASK_USER_QUESTION_VERSION" "$WEB_TOOLS_VERSION" >> "$PREFIX/VERSIONS"
74
+
75
+ # Register only runtime identity, never credentials or project/agent settings. Write atomically.
76
+ PI_BOOTSTRAP_PREFIX="$PREFIX" PI_BOOTSTRAP_NODE_HOME="$NODE_HOME" node --input-type=module <<'NODE'
77
+ import { chmodSync, mkdirSync, renameSync, writeFileSync } from "node:fs";
78
+ import { join, resolve } from "node:path";
79
+ const prefix = process.env.PI_BOOTSTRAP_PREFIX;
80
+ const nodeHome = process.env.PI_BOOTSTRAP_NODE_HOME;
81
+ const launcher = join(prefix, "bin", "pi-server");
82
+ const agentDir = resolve(process.env.PI_CODING_AGENT_DIR);
83
+ const defaultServerDir = resolve(process.env.PI_SERVER_DIR);
84
+ for (const value of [launcher, agentDir, defaultServerDir]) {
85
+ if (/[\0\r\n]/.test(value)) throw new Error("Runtime registration paths cannot contain NUL or line breaks");
86
+ }
87
+ const quote = (value) => "'" + value.replaceAll("'", "'\"'\"'") + "'";
88
+ writeFileSync(launcher, [
89
+ "#!/bin/sh",
90
+ `export PATH=${quote(join(nodeHome, "bin"))}:"$PATH"`,
91
+ `export PI_SERVER_LAUNCHER=${quote(launcher)}`,
92
+ `if [ -z "\${PI_CODING_AGENT_DIR:-}" ]; then export PI_CODING_AGENT_DIR=${quote(agentDir)}; fi`,
93
+ `if [ -z "\${PI_SERVER_DIR:-}" ]; then export PI_SERVER_DIR=${quote(defaultServerDir)}; fi`,
94
+ `exec ${quote(join(nodeHome, "bin", "node"))} ${quote(join(prefix, "server", "src", "cli.ts"))} "$@"`,
95
+ "",
96
+ ].join("\n"));
97
+ chmodSync(launcher, 0o755);
98
+ const directory = join(process.env.HOME, ".pi");
99
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
100
+ const manifest = join(directory, "remote-server.json");
101
+ const temporary = `${manifest}.${process.pid}.tmp`;
102
+ writeFileSync(temporary, JSON.stringify({ version: 1, agent: "pi", launcher, agentDir, defaultServerDir }) + "\n", { mode: 0o600, flag: "wx" });
103
+ renameSync(temporary, manifest);
104
+ NODE
105
+
106
+ cat "$PREFIX/VERSIONS"
107
+ echo "installed: $PREFIX/bin/pi-server"
@@ -0,0 +1,65 @@
1
+ import { createHash } from "node:crypto";
2
+ import { isAbsolute, posix } from "node:path";
3
+ import type { RuntimePlatform, ServerBuild, StagedRuntime } from "../../src/startup/managed-types.ts";
4
+
5
+ export const NODE_CHECKSUMS: Record<RuntimePlatform, string> = {
6
+ "linux-x64": "ace9fa104992ed0829642629c46ca7bd7fd6e76278cb96c958c4b387d29658ea",
7
+ "linux-arm64": "734ff04fa7f8ed2e8a78d40cacf5ac3fc4515dac2858757cbab313eb483ba8a2",
8
+ "darwin-x64": "2526230ad7d922be82d4fdb1e7ee1e84303e133e3b4b0ec4c2897ab31de0253d",
9
+ "darwin-arm64": "25495ff85bd89e2d8a24d88566d7e2f827c6b0d3d872b2cebf75371f93fcb1fe",
10
+ };
11
+ export function digest(value: string | Buffer): string { return createHash("sha256").update(value).digest("hex"); }
12
+ export function stable(value: any): string {
13
+ if (Array.isArray(value)) return `[${value.map(stable).join(",")}]`;
14
+ if (value && typeof value === "object") return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stable(value[key])}`).join(",")}}`;
15
+ return JSON.stringify(value);
16
+ }
17
+ export function validateBuild(value: any): ServerBuild {
18
+ if (!value || value.format !== 1 || !Object.hasOwn(NODE_CHECKSUMS, value.platform) || value.nodeVersion !== "24.14.1"
19
+ || !/^\d+\.\d+\.\d+$/.test(value.piSdkVersion) || !/^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/.test(value.serverVersion)
20
+ || !Number.isSafeInteger(value.protocolVersion) || value.protocolVersion < 1
21
+ || ![value.contentId, value.sourceDigest, value.dependencyLockDigest].every((v) => typeof v === "string" && /^[a-f0-9]{64}$/.test(v))) throw new Error("Artifact: invalid build metadata or unsupported platform");
22
+ const { contentId, ...identity } = value;
23
+ if (digest(stable(identity)) !== contentId) throw new Error("Artifact: content identity mismatch");
24
+ return value;
25
+ }
26
+ export interface ArtifactPayload { format: 1; build: ServerBuild; files: { path: string; data: string }[] }
27
+ export function safeSourcePath(path: unknown): path is string {
28
+ return typeof path === "string" && path.length <= 512 && !path.includes("\\") && !/[\0-\x1f\x7f]/.test(path)
29
+ && !isAbsolute(path) && path === posix.normalize(path) && !path.split("/").some((p) => !p || p === ".." || p === "." || p === "node_modules" || p === ".git" || p === "test-support" || p.startsWith(".env") || p === "auth.json" || p === "settings.json")
30
+ && (path.startsWith("src/") || ["package.json", "scripts/private-runtime/format.ts", "scripts/private-runtime/installer.ts", "scripts/private-runtime/package.json", "scripts/private-runtime/package-lock.json"].includes(path));
31
+ }
32
+ export function validatePayload(value: any): ArtifactPayload {
33
+ if (!value || value.format !== 1 || !Array.isArray(value.files) || value.files.length > 10000) throw new Error("Artifact: invalid file table");
34
+ validateBuild(value.build);
35
+ const paths = new Set<string>();
36
+ let size = 0;
37
+ for (const file of value.files) {
38
+ if (!file || Object.keys(file).sort().join(",") !== "data,path" || !safeSourcePath(file.path) || paths.has(file.path)) throw new Error("Artifact: unsafe or duplicate path");
39
+ if (typeof file.data !== "string" || file.data.length > 16 * 1024 * 1024 || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(file.data)) throw new Error("Artifact: invalid or oversized file");
40
+ size += Buffer.byteLength(file.data, "base64");
41
+ if (size > 48 * 1024 * 1024) throw new Error("Artifact: decoded size limit");
42
+ paths.add(file.path);
43
+ }
44
+ for (const path of paths) {
45
+ for (let parent = posix.dirname(path); parent !== "."; parent = posix.dirname(parent)) if (paths.has(parent)) throw new Error("Artifact: file/directory path collision");
46
+ }
47
+ for (const required of ["src/cli.ts", "src/server.ts", "package.json", "scripts/private-runtime/format.ts", "scripts/private-runtime/installer.ts", "scripts/private-runtime/package-lock.json", "scripts/private-runtime/package.json"]) if (!paths.has(required)) throw new Error(`Artifact: missing ${required}`);
48
+ if (digest(stable(value.files)) !== value.build.sourceDigest) throw new Error("Artifact: source integrity mismatch");
49
+ const lock = JSON.parse(Buffer.from(value.files.find((f: any) => f.path === "scripts/private-runtime/package-lock.json").data, "base64").toString());
50
+ if (digest(stable(lock)) !== value.build.dependencyLockDigest || lock.lockfileVersion !== 3 || lock.packages?.[""]?.dependencies?.["@earendil-works/pi-coding-agent"] !== value.build.piSdkVersion) throw new Error("Artifact: dependency lock mismatch");
51
+ for (const [path, pkg] of Object.entries(lock.packages) as [string, any][]) {
52
+ if (!path) continue;
53
+ if (!path.startsWith("node_modules/") || path.includes("..") || pkg.link || !/^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/.test(pkg.version)
54
+ || typeof pkg.resolved !== "string" || !pkg.resolved.startsWith("https://registry.npmjs.org/") || !/^sha512-[A-Za-z0-9+/]{86}==$/.test(pkg.integrity)) throw new Error(`Artifact: dependency lacks official locked integrity: ${path}`);
55
+ }
56
+ return value;
57
+ }
58
+ export function validateStaged(value: any): StagedRuntime {
59
+ if (!value || value.format !== 1) throw new Error("Staging: invalid runtime manifest");
60
+ validateBuild(value.build);
61
+ for (const key of ["root", "node", "entrypoint", "manifestPath", "installRoot"]) if (typeof value[key] !== "string" || !isAbsolute(value[key]) || /[\0\r\n]/.test(value[key]) || posix.normalize(value[key]) !== value[key]) throw new Error(`Staging: invalid ${key}`);
62
+ if (value.root !== `${value.installRoot}/releases/${value.build.contentId}` || value.root.split("/").includes("node_modules")
63
+ || value.node !== `${value.root}/node/bin/node` || value.entrypoint !== `${value.root}/src/cli.ts` || value.manifestPath !== `${value.root}/runtime.json`) throw new Error("Staging: runtime path identity mismatch");
64
+ return value;
65
+ }
@@ -0,0 +1,166 @@
1
+ import { createHash } from "node:crypto";
2
+ import { cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, writeFileSync, chmodSync } from "node:fs";
3
+ import { dirname, join, relative, resolve } from "node:path";
4
+ import { spawnSync } from "node:child_process";
5
+ import { gunzipSync } from "node:zlib";
6
+ import { setTimeout as delay } from "node:timers/promises";
7
+ import { digest, stable, validatePayload, validateStaged } from "./format.ts";
8
+
9
+ const [work, installRoot, expectedSha, mode] = process.argv.slice(2) as [string, string, string, string];
10
+ let lock: string | undefined;
11
+ let acquired = false;
12
+ let ownsWork = false;
13
+ let candidate: string | undefined;
14
+ function cancelled() { if (existsSync(join(work, "cancel"))) throw new Error("installation cancelled"); }
15
+ function plainDirectory(path: string) {
16
+ if (existsSync(path) && (!lstatSync(path).isDirectory() || lstatSync(path).isSymbolicLink())) throw new Error(`permission: unsafe directory ${path}`);
17
+ mkdirSync(path, { recursive: true, mode: 0o700 });
18
+ }
19
+ function inventory(root: string): Record<string, string> {
20
+ const result: Record<string, string> = {};
21
+ function visit(path: string) {
22
+ for (const name of readdirSync(join(root, path)).sort()) {
23
+ const rel = path ? `${path}/${name}` : name;
24
+ if (rel === "integrity.json") continue;
25
+ const full = join(root, rel);
26
+ const stat = lstatSync(full);
27
+ if (stat.isSymbolicLink()) {
28
+ const target = realpathSync(full);
29
+ if (!target.startsWith(`${realpathSync(root)}/`)) throw new Error(`corrupt cache: symlink escape ${rel}`);
30
+ result[rel] = `link:${readlinkSync(full)}`;
31
+ } else if (stat.isDirectory()) visit(rel);
32
+ else if (stat.isFile()) result[rel] = `${stat.mode & 0o111}:${digest(readFileSync(full))}`;
33
+ else throw new Error(`corrupt cache: special file ${rel}`);
34
+ }
35
+ }
36
+ visit("");
37
+ return result;
38
+ }
39
+ function seal(root: string) {
40
+ for (const name of readdirSync(root)) {
41
+ const path = join(root, name);
42
+ const stat = lstatSync(path);
43
+ if (stat.isSymbolicLink()) continue;
44
+ if (stat.isDirectory()) seal(path);
45
+ else chmodSync(path, stat.mode & 0o111 ? 0o500 : 0o400);
46
+ }
47
+ chmodSync(root, 0o500);
48
+ }
49
+ function removeOwned(path: string) {
50
+ // Undo this attempt's sealing only; never touch a published release.
51
+ if (!existsSync(path)) return;
52
+ function writable(dir: string) {
53
+ chmodSync(dir, 0o700);
54
+ for (const name of readdirSync(dir)) { const p = join(dir, name); if (lstatSync(p).isDirectory() && !lstatSync(p).isSymbolicLink()) writable(p); }
55
+ }
56
+ writable(path);
57
+ rmSync(path, { recursive: true, force: true });
58
+ }
59
+
60
+ try {
61
+ writeFileSync(join(work, "installer.pid"), String(process.pid), { flag: "wx", mode: 0o600 });
62
+ ownsWork = true;
63
+ cancelled();
64
+ const bytes = readFileSync(join(work, "artifact.gz"));
65
+ if (bytes.length > 32 * 1024 * 1024 || digest(bytes) !== expectedSha) throw new Error("artifact integrity mismatch or size limit");
66
+ const payload = validatePayload(JSON.parse(gunzipSync(bytes, { maxOutputLength: 64 * 1024 * 1024 }).toString()));
67
+ if (`${process.platform}-${process.arch}` !== payload.build.platform || process.versions.node !== payload.build.nodeVersion) throw new Error("unsupported platform or Node version mismatch");
68
+ if (realpathSync(installRoot) !== resolve(installRoot)) throw new Error("permission: install root contains symlink");
69
+ const releases = join(installRoot, "releases");
70
+ const locks = join(installRoot, "locks");
71
+ plainDirectory(releases); plainDirectory(locks);
72
+ const finalRoot = join(releases, payload.build.contentId);
73
+ lock = join(locks, payload.build.contentId);
74
+ // Never reclaim an owner on elapsed time. A crashed owner requires explicit repair.
75
+ const deadline = Date.now() + 300_000;
76
+ let reportedWait = false;
77
+ for (;;) {
78
+ cancelled();
79
+ try { mkdirSync(lock, { mode: 0o700 }); acquired = true; break; }
80
+ catch (error) {
81
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
82
+ if (lstatSync(lock).isSymbolicLink()) throw new Error("permission: unsafe build lock");
83
+ if (!reportedWait) { process.stderr.write("Waiting for runtime build owner; the lock will not be reclaimed by age.\n"); reportedWait = true; }
84
+ if (Date.now() >= deadline) throw new Error("build lock busy: owner was not reclaimed");
85
+ await delay(200);
86
+ }
87
+ }
88
+ writeFileSync(join(lock, "owner.json"), JSON.stringify({ pid: process.pid, work }), { flag: "wx", mode: 0o600 });
89
+ const runtime = validateStaged({ format: 1, build: payload.build, root: finalRoot, node: join(finalRoot, "node/bin/node"), entrypoint: join(finalRoot, "src/cli.ts"), manifestPath: join(finalRoot, "runtime.json"), installRoot });
90
+ if (existsSync(finalRoot)) {
91
+ if (lstatSync(finalRoot).isSymbolicLink()) throw new Error("corrupt cache: release symlink");
92
+ for (const path of [runtime.manifestPath, join(finalRoot, "integrity.json"), ...payload.files.map((file) => join(finalRoot, file.path))]) {
93
+ if (!existsSync(path) || !lstatSync(path).isFile() || lstatSync(path).isSymbolicLink()) throw new Error(`corrupt cache: expected regular file ${path}`);
94
+ }
95
+ if (stable(inventory(finalRoot)) !== stable(JSON.parse(readFileSync(join(finalRoot, "integrity.json"), "utf8")))) throw new Error("corrupt cache: runtime closure integrity mismatch");
96
+ if (stable(JSON.parse(readFileSync(runtime.manifestPath, "utf8"))) !== stable(runtime)) throw new Error("corrupt cache: manifest mismatch");
97
+ for (const file of payload.files) if (!readFileSync(join(finalRoot, file.path)).equals(Buffer.from(file.data, "base64"))) throw new Error(`corrupt cache: source mismatch ${file.path}`);
98
+ cancelled();
99
+ process.stdout.write(JSON.stringify(runtime));
100
+ } else {
101
+ candidate = join(work, "release");
102
+ removeOwned(candidate);
103
+ mkdirSync(candidate, { mode: 0o700 });
104
+ for (const file of payload.files) {
105
+ const path = join(candidate, file.path);
106
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
107
+ writeFileSync(path, Buffer.from(file.data, "base64"), { flag: "wx", mode: 0o600 });
108
+ }
109
+ cpSync(join(work, "node"), join(candidate, "node"), { recursive: true, dereference: false, verbatimSymlinks: true });
110
+ const deps = join(work, "dependencies");
111
+ plainDirectory(deps);
112
+ for (const file of ["package.json", "package-lock.json"]) cpSync(join(candidate, "scripts/private-runtime", file), join(deps, file));
113
+ const home = join(work, "home");
114
+ plainDirectory(home); plainDirectory(join(home, "agent"));
115
+ const env = { HOME: home, PATH: `${join(candidate, "node/bin") }:/usr/bin:/bin`, PI_CODING_AGENT_DIR: join(home, "agent"), PI_SERVER_DIR: join(home, "server"), npm_config_userconfig: join(home, "npmrc"), npm_config_globalconfig: join(home, "global-npmrc"), npm_config_cache: join(work, "npm-cache"), npm_config_registry: "https://registry.npmjs.org", npm_config_update_notifier: "false" };
116
+ writeFileSync(env.npm_config_userconfig, ""); writeFileSync(env.npm_config_globalconfig, "");
117
+ const node = join(candidate, "node/bin/node");
118
+ const npm = join(candidate, "node/lib/node_modules/npm/bin/npm-cli.js");
119
+ function npmRun(args: string[]) {
120
+ cancelled();
121
+ const child = spawnSync(node, [npm, ...args, "--ignore-scripts", "--no-audit", "--no-fund"], { cwd: deps, env, encoding: "utf8", timeout: 240_000, maxBuffer: 4 * 1024 * 1024 });
122
+ cancelled();
123
+ return child;
124
+ }
125
+ if (mode === "offline") {
126
+ for (const archive of readdirSync(join(work, "archives"))) {
127
+ const result = npmRun(["cache", "add", join(work, "archives", archive), "--offline"]);
128
+ if (result.status !== 0) throw new Error(`dependency cache import: ${result.stderr}`);
129
+ }
130
+ }
131
+ const installed = npmRun(["ci", ...(mode === "offline" ? ["--offline"] : [] )]);
132
+ if (installed.status !== 0) {
133
+ if (mode === "online" && !/ENOSPC|EACCES|EPERM/.test(installed.stderr)) {
134
+ process.stderr.write(`dependency download failed; client upload required: ${installed.stderr}`);
135
+ process.exitCode = 75;
136
+ } else throw new Error(`dependency installation: ${installed.error ?? installed.stderr}`);
137
+ } else {
138
+ renameSync(join(deps, "node_modules"), join(candidate, "node_modules"));
139
+ writeFileSync(join(candidate, "managed-build.json"), stable(payload.build));
140
+ writeFileSync(join(candidate, "runtime.json"), stable(runtime));
141
+ const check = spawnSync(node, ["--input-type=module", "-e", `const sdk = await import('@earendil-works/pi-coding-agent'); if (sdk.VERSION !== ${JSON.stringify(payload.build.piSdkVersion)}) throw new Error('SDK version mismatch'); await import('./src/server.ts');`], { cwd: candidate, env, encoding: "utf8", timeout: 60_000, maxBuffer: 1024 * 1024 });
142
+ if (check.status !== 0) throw new Error(`isolated import/version check: ${check.error ?? check.stderr}`);
143
+ cancelled();
144
+ seal(candidate);
145
+ // macOS requires write permission on a directory while renaming it.
146
+ chmodSync(candidate, 0o700);
147
+ writeFileSync(join(candidate, "integrity.json"), stable(inventory(candidate)), { mode: 0o400 });
148
+ cancelled();
149
+ renameSync(candidate, finalRoot);
150
+ candidate = undefined;
151
+ chmodSync(finalRoot, 0o500);
152
+ process.stdout.write(JSON.stringify(runtime));
153
+ }
154
+ }
155
+ } catch (error) {
156
+ const code = (error as NodeJS.ErrnoException).code;
157
+ process.stderr.write(`Runtime staging ${code === "ENOSPC" ? "disk space" : code === "EACCES" || code === "EPERM" ? "permission" : "verification/install"}: ${String(error)}\n`);
158
+ process.exitCode = 1;
159
+ } finally {
160
+ if (candidate) removeOwned(candidate);
161
+ if (acquired && lock) rmSync(lock, { recursive: true, force: true });
162
+ if (ownsWork) {
163
+ rmSync(join(work, "installer.pid"), { force: true });
164
+ if (existsSync(join(work, "cancel"))) removeOwned(work);
165
+ }
166
+ }