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.
- package/README.md +624 -2
- package/codex-plugin/.agents/plugins/marketplace.json +17 -0
- package/codex-plugin/plugins/pi-remote/.codex-plugin/plugin.json +20 -0
- package/codex-plugin/plugins/pi-remote/.mcp.json +13 -0
- package/codex-plugin/plugins/pi-remote/server.mjs +118 -0
- package/codex-plugin/plugins/pi-remote/skills/pi-remote/SKILL.md +19 -0
- package/package.json +60 -4
- package/scripts/bootstrap-host.sh +107 -0
- package/scripts/private-runtime/format.ts +65 -0
- package/scripts/private-runtime/installer.ts +166 -0
- package/scripts/private-runtime/package-lock.json +1491 -0
- package/scripts/private-runtime/package.json +17 -0
- package/scripts/test-on-pi.sh +34 -0
- package/src/cli-args.ts +38 -0
- package/src/cli.ts +90 -0
- package/src/client.ts +152 -0
- package/src/codex/adapter.ts +299 -0
- package/src/codex/app-server.ts +112 -0
- package/src/codex/daemon.ts +232 -0
- package/src/codex/deliver.ts +103 -0
- package/src/codex/preflight.ts +15 -0
- package/src/codex/provider.ts +55 -0
- package/src/codex/return.ts +110 -0
- package/src/codex/rollout.ts +160 -0
- package/src/codex/runtime.ts +126 -0
- package/src/codex/ws-unix.ts +112 -0
- package/src/companion.ts +96 -0
- package/src/control.ts +85 -0
- package/src/core/adapter.ts +109 -0
- package/src/core/bundle.ts +764 -0
- package/src/core/exclusions.ts +53 -0
- package/src/core/move-host.ts +268 -0
- package/src/core/ownership.ts +135 -0
- package/src/core/transfer.ts +73 -0
- package/src/daemon-owner.ts +130 -0
- package/src/detach/detach.ts +150 -0
- package/src/detach/extension.ts +244 -0
- package/src/detach/local-sink.ts +203 -0
- package/src/detach/local-source.ts +133 -0
- package/src/detach/local-state.ts +87 -0
- package/src/detach/recover.ts +53 -0
- package/src/event-log.ts +163 -0
- package/src/git.ts +35 -0
- package/src/handshake.ts +57 -0
- package/src/hosted-session.ts +576 -0
- package/src/index.ts +31 -0
- package/src/lifecycle-config.ts +29 -0
- package/src/maintenance.ts +317 -0
- package/src/move/auth.ts +16 -0
- package/src/move/orchestrate.ts +163 -0
- package/src/move/pi-adapter.ts +181 -0
- package/src/move/preflight.ts +197 -0
- package/src/move/service.ts +16 -0
- package/src/paths.ts +52 -0
- package/src/protocol.ts +212 -0
- package/src/registry.ts +559 -0
- package/src/remote/answer.ts +95 -0
- package/src/remote/attach-codex.ts +41 -0
- package/src/remote/attach.ts +41 -0
- package/src/remote/console.ts +126 -0
- package/src/remote/context.ts +75 -0
- package/src/remote/cursors.ts +36 -0
- package/src/remote/ls.ts +44 -0
- package/src/remote/move.ts +85 -0
- package/src/remote/new.ts +37 -0
- package/src/remote/process-runner.ts +51 -0
- package/src/remote/recover.ts +35 -0
- package/src/remote/return.ts +49 -0
- package/src/remote/sessions.ts +33 -0
- package/src/remote/steer.ts +40 -0
- package/src/remote/tail.ts +91 -0
- package/src/remote/target.ts +313 -0
- package/src/remote-cli.ts +73 -0
- package/src/remote-client/connection-progress.ts +62 -0
- package/src/remote-client/extension.ts +396 -0
- package/src/remote-client/folder-browser.ts +165 -0
- package/src/remote-client/host.ts +130 -0
- package/src/remote-client/local-work.ts +62 -0
- package/src/remote-client/menu.ts +68 -0
- package/src/remote-client/packages.ts +345 -0
- package/src/remote-client/pi-1.2-bridge.ts +542 -0
- package/src/remote-client/profiles.ts +38 -0
- package/src/remote-client/remote-progress.ts +39 -0
- package/src/remote-client/session-browser.ts +270 -0
- package/src/remote-client/session.ts +1205 -0
- package/src/remote-client/ssh-hosts.ts +185 -0
- package/src/remote-client/transfer-command.ts +189 -0
- package/src/remote-client/upgrade-transport.ts +105 -0
- package/src/server.ts +398 -0
- package/src/session-activity.ts +173 -0
- package/src/shared-ssh-core/index.ts +950 -0
- package/src/startup/activation.ts +621 -0
- package/src/startup/admission.ts +98 -0
- package/src/startup/artifact.ts +65 -0
- package/src/startup/commands.ts +37 -0
- package/src/startup/ensure.ts +137 -0
- package/src/startup/install.ts +115 -0
- package/src/startup/managed-types.ts +61 -0
- package/src/startup/runtime.ts +138 -0
- package/src/ui-bridge.ts +124 -0
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "pi-better-server-private-runtime",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"private": true,
|
|
5
|
+
"type": "module",
|
|
6
|
+
"dependencies": {
|
|
7
|
+
"@earendil-works/pi-coding-agent": "1.2.0",
|
|
8
|
+
"@earendil-works/pi-ai": "1.2.0",
|
|
9
|
+
"@earendil-works/pi-tui": "1.2.0"
|
|
10
|
+
},
|
|
11
|
+
"overrides": {
|
|
12
|
+
"@earendil-works/pi-agent-core": "1.2.0",
|
|
13
|
+
"@earendil-works/pi-mcp": "1.2.0",
|
|
14
|
+
"@earendil-works/pi-codemode": "1.2.0",
|
|
15
|
+
"@earendil-works/pi-telemetry": "1.2.0"
|
|
16
|
+
}
|
|
17
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# Run this package's test suite against a given Pi version without touching the repo's lockfile.
|
|
3
|
+
#
|
|
4
|
+
# scripts/test-on-pi.sh 1.2.0 [PREFIX] (default PREFIX: <package>/.pi-compat/<version>)
|
|
5
|
+
#
|
|
6
|
+
# Installs @earendil-works/pi-coding-agent@VERSION and pi-ai@VERSION into PREFIX,
|
|
7
|
+
# copies the package next to them, and runs `node --test` there so every import
|
|
8
|
+
# resolves to that Pi and not to the workspace's.
|
|
9
|
+
set -euo pipefail
|
|
10
|
+
|
|
11
|
+
PI_VERSION="${1:?usage: test-on-pi.sh <pi-version> [prefix]}"
|
|
12
|
+
PKG_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
|
13
|
+
ROOT_DIR="$(cd "$PKG_DIR/../.." && pwd)"
|
|
14
|
+
PREFIX="${2:-$PKG_DIR/.pi-compat/$PI_VERSION}"
|
|
15
|
+
|
|
16
|
+
node "$ROOT_DIR/scripts/sync-shared-ssh-core.mjs"
|
|
17
|
+
|
|
18
|
+
rm -rf "$PREFIX"
|
|
19
|
+
mkdir -p "$PREFIX/packages/pi-better-server" "$PREFIX/scripts"
|
|
20
|
+
printf '{ "name": "pi-compat", "private": true }\n' > "$PREFIX/package.json"
|
|
21
|
+
(cd "$PREFIX" && npm install --no-audit --no-fund \
|
|
22
|
+
"@earendil-works/pi-coding-agent@$PI_VERSION" "@earendil-works/pi-ai@$PI_VERSION" \
|
|
23
|
+
tsx@^4.22.3 typescript@^6.0.0 @types/node@^25.0.0)
|
|
24
|
+
|
|
25
|
+
cp "$ROOT_DIR/scripts/isolate-registry.mjs" "$PREFIX/scripts/"
|
|
26
|
+
cp -R "$PKG_DIR/src" "$PKG_DIR/test" "$PKG_DIR/scripts" "$PKG_DIR/package.json" "$PKG_DIR/tsconfig.json" "$PREFIX/packages/pi-better-server/"
|
|
27
|
+
[ -d "$PKG_DIR/codex-plugin" ] && cp -R "$PKG_DIR/codex-plugin" "$PREFIX/packages/pi-better-server/"
|
|
28
|
+
# Background-activity regressions load the real sibling provider against this SDK.
|
|
29
|
+
cp -R "$ROOT_DIR/packages/pi-better-subagents" "$PREFIX/packages/pi-better-subagents"
|
|
30
|
+
|
|
31
|
+
cd "$PREFIX/packages/pi-better-server"
|
|
32
|
+
installed="$(node -p "require('$PREFIX/node_modules/@earendil-works/pi-coding-agent/package.json').version")"
|
|
33
|
+
echo "testing against pi-coding-agent $installed"
|
|
34
|
+
node --import tsx --import ../../scripts/isolate-registry.mjs --test --test-concurrency=4 test/*.test.ts
|
package/src/cli-args.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { parseArgs } from "node:util";
|
|
2
|
+
|
|
3
|
+
export type ServerAgent = "pi" | "codex";
|
|
4
|
+
|
|
5
|
+
/** Resolves the daemon agent from argv (`--agent codex` or `--agent=codex`), falling back to the env value, then "pi". */
|
|
6
|
+
export function resolveAgent(argv: readonly string[], envAgent?: string): ServerAgent {
|
|
7
|
+
let value: string | undefined = envAgent;
|
|
8
|
+
for (let i = 0; i < argv.length; i++) {
|
|
9
|
+
const arg = argv[i]!;
|
|
10
|
+
if (arg === "--agent") {
|
|
11
|
+
const next = argv[i + 1];
|
|
12
|
+
if (next === undefined || next.startsWith("-")) throw new Error("--agent requires a value; expected pi or codex");
|
|
13
|
+
value = next;
|
|
14
|
+
i++;
|
|
15
|
+
} else if (arg.startsWith("--agent=")) {
|
|
16
|
+
value = arg.slice("--agent=".length);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
const agent = value ?? "pi";
|
|
20
|
+
if (agent !== "pi" && agent !== "codex") throw new Error(`Unknown --agent ${agent}; expected pi or codex`);
|
|
21
|
+
return agent;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Shared managed-startup grammar; flags follow the same --name/--name=value rules as ensure. */
|
|
25
|
+
export function parseManagedStartupArgs(argv: string[]) {
|
|
26
|
+
return parseArgs({ args: argv, options: {
|
|
27
|
+
agent: { type: "string" },
|
|
28
|
+
"server-dir": { type: "string" },
|
|
29
|
+
"agent-dir": { type: "string" },
|
|
30
|
+
runtime: { type: "string" },
|
|
31
|
+
"desired-runtime": { type: "string" },
|
|
32
|
+
"operation-id": { type: "string" },
|
|
33
|
+
"timeout-ms": { type: "string" },
|
|
34
|
+
"pi-version": { type: "string" },
|
|
35
|
+
"protocol-version": { type: "string" },
|
|
36
|
+
"require-capability": { type: "string", multiple: true },
|
|
37
|
+
} }).values;
|
|
38
|
+
}
|
package/src/cli.ts
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { parseManagedStartupArgs, resolveAgent, type ServerAgent } from "./cli-args.ts";
|
|
4
|
+
import { absolutePath, launcherRuntime, registeredRuntime } from "./startup/runtime.ts";
|
|
5
|
+
|
|
6
|
+
const log = (message: string): void => void process.stderr.write(`[pi-better-server] ${message}\n`);
|
|
7
|
+
|
|
8
|
+
async function main(): Promise<void> {
|
|
9
|
+
const argv = process.argv.slice(2);
|
|
10
|
+
let agent: ServerAgent;
|
|
11
|
+
try { agent = resolveAgent(argv, process.env.PI_SERVER_AGENT); }
|
|
12
|
+
catch (error) {
|
|
13
|
+
log(error instanceof Error ? error.message : String(error));
|
|
14
|
+
process.exitCode = 2;
|
|
15
|
+
return;
|
|
16
|
+
}
|
|
17
|
+
// A launcher describes its own runtime; direct Pi CLI users share the per-user registration.
|
|
18
|
+
const runtime = (): ReturnType<typeof launcherRuntime> => process.env.PI_SERVER_LAUNCHER || process.env.PI_SERVER_COMMAND
|
|
19
|
+
? launcherRuntime() : registeredRuntime() ?? launcherRuntime();
|
|
20
|
+
if (argv[0] === "runtime") {
|
|
21
|
+
if (agent !== "pi") throw new Error("Runtime discovery supports Pi only");
|
|
22
|
+
process.stdout.write(`${JSON.stringify(runtime())}\n`);
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
if (agent === "pi") {
|
|
26
|
+
const selected = runtime();
|
|
27
|
+
process.env.PI_CODING_AGENT_DIR ||= selected.agentDir;
|
|
28
|
+
process.env.PI_SERVER_DIR ||= selected.defaultServerDir;
|
|
29
|
+
}
|
|
30
|
+
if (["ensure", "activate", "activation-worker"].includes(argv[0] ?? "")) {
|
|
31
|
+
if (agent !== "pi") throw new Error("Server ensure supports Pi only; start the Codex daemon explicitly");
|
|
32
|
+
const values = parseManagedStartupArgs(argv.slice(1));
|
|
33
|
+
const controller = new AbortController();
|
|
34
|
+
const stop = (): void => controller.abort();
|
|
35
|
+
process.on("SIGINT", stop);
|
|
36
|
+
process.on("SIGTERM", stop);
|
|
37
|
+
try {
|
|
38
|
+
const manifest = values["desired-runtime"] ?? values.runtime;
|
|
39
|
+
if (argv[0] !== "ensure" && !manifest) throw new Error("--runtime is required");
|
|
40
|
+
if (manifest) {
|
|
41
|
+
const { readStagedRuntime } = await import("./startup/artifact.ts");
|
|
42
|
+
const { activateStagedRuntime, runActivationWorker } = await import("./startup/activation.ts");
|
|
43
|
+
const request = {
|
|
44
|
+
runtime: readStagedRuntime(absolutePath(manifest, "runtime manifest")),
|
|
45
|
+
serverDir: absolutePath(values["server-dir"] ?? process.env.PI_SERVER_DIR, "serverDir"),
|
|
46
|
+
agentDir: absolutePath(values["agent-dir"] ?? process.env.PI_CODING_AGENT_DIR, "agentDir"),
|
|
47
|
+
operationId: values["operation-id"] ?? randomUUID(), signal: controller.signal,
|
|
48
|
+
timeoutMs: values["timeout-ms"] === undefined ? undefined : Number(values["timeout-ms"]),
|
|
49
|
+
};
|
|
50
|
+
const outcome = argv[0] === "activation-worker" ? await runActivationWorker(request) : await activateStagedRuntime(request);
|
|
51
|
+
process.stdout.write(`${JSON.stringify(argv[0] === "ensure" && outcome.status === "ready" ? outcome.readiness : outcome)}\n`);
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
const { ensureDaemon } = await import("./startup/ensure.ts");
|
|
55
|
+
const record = await ensureDaemon({
|
|
56
|
+
serverDir: absolutePath(values["server-dir"] ?? process.env.PI_SERVER_DIR, "serverDir"),
|
|
57
|
+
agentDir: absolutePath(process.env.PI_CODING_AGENT_DIR, "agentDir"),
|
|
58
|
+
timeoutMs: values["timeout-ms"] === undefined ? undefined : Number(values["timeout-ms"]),
|
|
59
|
+
piVersion: values["pi-version"],
|
|
60
|
+
protocolVersion: values["protocol-version"] === undefined ? undefined : Number(values["protocol-version"]),
|
|
61
|
+
requiredCapabilities: values["require-capability"],
|
|
62
|
+
signal: controller.signal,
|
|
63
|
+
});
|
|
64
|
+
process.stdout.write(`${JSON.stringify(record)}\n`);
|
|
65
|
+
} finally {
|
|
66
|
+
process.off("SIGINT", stop);
|
|
67
|
+
process.off("SIGTERM", stop);
|
|
68
|
+
}
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const serverDir = process.env.PI_SERVER_DIR ? { serverDir: process.env.PI_SERVER_DIR } : {};
|
|
73
|
+
const daemon = agent === "codex"
|
|
74
|
+
? await (await import("./codex/daemon.ts")).startCodexDaemon({ ...serverDir, log })
|
|
75
|
+
: await (await import("./server.ts")).startDaemon({ ...serverDir, log });
|
|
76
|
+
|
|
77
|
+
let stopping = false;
|
|
78
|
+
const shutdown = (): void => {
|
|
79
|
+
if (stopping) return;
|
|
80
|
+
stopping = true;
|
|
81
|
+
void daemon.stop().finally(() => process.exit(0));
|
|
82
|
+
};
|
|
83
|
+
process.on("SIGINT", shutdown);
|
|
84
|
+
process.on("SIGTERM", shutdown);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
await main().catch((error) => {
|
|
88
|
+
log(error instanceof Error ? error.message : String(error));
|
|
89
|
+
process.exitCode = 1;
|
|
90
|
+
});
|
package/src/client.ts
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { connect, type Socket } from "node:net";
|
|
2
|
+
import { VERSION as PI_VERSION } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import { SERVER_EXTENSION_VERSIONS } from "./handshake.ts";
|
|
4
|
+
import { encodeLine, LineDecoder, PROTOCOL_VERSION, type HelloData } from "./protocol.ts";
|
|
5
|
+
|
|
6
|
+
/** The daemon refused the `hello`; the message is the daemon's own explanation. */
|
|
7
|
+
export class HandshakeError extends Error {
|
|
8
|
+
constructor(message: string) {
|
|
9
|
+
super(message);
|
|
10
|
+
this.name = "HandshakeError";
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface ConnectOptions {
|
|
15
|
+
/** Cancels Unix connect and hello only; ignored after the client is returned. */
|
|
16
|
+
signal?: AbortSignal;
|
|
17
|
+
/** Override what the client announces (tests use this to play an incompatible client). `false` skips the handshake. */
|
|
18
|
+
hello?: { protocolVersion?: number; piVersion?: string; extensionVersions?: Record<string, string>; capabilities?: string[] } | false;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
type Message = { id?: string; type: string; success?: boolean; error?: string; data?: any; sessionId?: string; [key: string]: unknown };
|
|
22
|
+
|
|
23
|
+
/** Newline-JSON client for the daemon socket. Connects, says hello, then multiplexes requests and events. */
|
|
24
|
+
export class DaemonClient {
|
|
25
|
+
/** What the daemon announced in its hello reply; undefined when the handshake was skipped. */
|
|
26
|
+
server: HelloData | undefined;
|
|
27
|
+
private readonly socket: Socket;
|
|
28
|
+
private readonly pending = new Map<string, { resolve: (message: Message) => void; reject: (error: Error) => void }>();
|
|
29
|
+
private readonly eventListeners = new Set<(message: Message) => void>();
|
|
30
|
+
private readonly closeListeners = new Set<() => void>();
|
|
31
|
+
private nextId = 1;
|
|
32
|
+
private closed = false;
|
|
33
|
+
|
|
34
|
+
private constructor(socket: Socket, server: HelloData | undefined) {
|
|
35
|
+
this.socket = socket;
|
|
36
|
+
this.server = server;
|
|
37
|
+
socket.setEncoding("utf8");
|
|
38
|
+
const decoder = new LineDecoder(
|
|
39
|
+
(line) => this.onLine(line),
|
|
40
|
+
() => socket.destroy(),
|
|
41
|
+
);
|
|
42
|
+
socket.on("data", (chunk: string) => decoder.push(chunk));
|
|
43
|
+
socket.on("error", () => undefined);
|
|
44
|
+
socket.on("close", () => this.onClosed());
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
static async connect(socketPath: string, options: ConnectOptions = {}): Promise<DaemonClient> {
|
|
48
|
+
const { signal } = options;
|
|
49
|
+
const abortError = () => new DOMException("The operation was aborted", "AbortError");
|
|
50
|
+
if (signal?.aborted) throw abortError();
|
|
51
|
+
const socket = connect(socketPath);
|
|
52
|
+
let onAbort: () => void = () => undefined;
|
|
53
|
+
const aborted = new Promise<never>((_resolve, reject) => {
|
|
54
|
+
onAbort = () => {
|
|
55
|
+
socket.destroy();
|
|
56
|
+
reject(abortError());
|
|
57
|
+
};
|
|
58
|
+
});
|
|
59
|
+
let removeConnectListeners!: () => void;
|
|
60
|
+
const connected = new Promise<void>((resolve, reject) => {
|
|
61
|
+
socket.once("connect", resolve);
|
|
62
|
+
socket.once("error", reject);
|
|
63
|
+
removeConnectListeners = () => {
|
|
64
|
+
socket.removeListener("connect", resolve);
|
|
65
|
+
socket.removeListener("error", reject);
|
|
66
|
+
};
|
|
67
|
+
});
|
|
68
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
69
|
+
try {
|
|
70
|
+
if (signal?.aborted) onAbort();
|
|
71
|
+
await Promise.race([connected, aborted]);
|
|
72
|
+
if (signal?.aborted) throw abortError();
|
|
73
|
+
const client = new DaemonClient(socket, undefined);
|
|
74
|
+
if (options.hello === false) return client;
|
|
75
|
+
const response = await Promise.race([client.request({
|
|
76
|
+
type: "hello",
|
|
77
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
78
|
+
piVersion: PI_VERSION,
|
|
79
|
+
extensionVersions: { ...SERVER_EXTENSION_VERSIONS },
|
|
80
|
+
...options.hello,
|
|
81
|
+
}), aborted]);
|
|
82
|
+
if (signal?.aborted) throw abortError();
|
|
83
|
+
if (!response.success) throw new HandshakeError(response.error ?? "daemon rejected the handshake");
|
|
84
|
+
client.server = response.data as HelloData;
|
|
85
|
+
return client;
|
|
86
|
+
} catch (error) {
|
|
87
|
+
socket.destroy();
|
|
88
|
+
if (signal?.aborted) throw abortError();
|
|
89
|
+
throw error;
|
|
90
|
+
} finally {
|
|
91
|
+
removeConnectListeners();
|
|
92
|
+
signal?.removeEventListener("abort", onAbort);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Send one command and wait for its response. A `success:false` response resolves; it is not thrown. */
|
|
97
|
+
request(command: Record<string, unknown>): Promise<Message> {
|
|
98
|
+
if (this.closed) return Promise.reject(new Error("connection closed"));
|
|
99
|
+
const id = `c${this.nextId++}`;
|
|
100
|
+
return new Promise((resolve, reject) => {
|
|
101
|
+
this.pending.set(id, { resolve, reject });
|
|
102
|
+
this.socket.write(encodeLine({ ...command, id }));
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Like `request`, but a failed response throws with the daemon's error text. */
|
|
107
|
+
async call(command: Record<string, unknown>): Promise<Message> {
|
|
108
|
+
const response = await this.request(command);
|
|
109
|
+
if (!response.success) throw new Error(response.error ?? `${String(command.type)} failed`);
|
|
110
|
+
return response;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Every pushed `{type:"event"}` line, for sessions this connection created or `subscribe`d to (each carries `seq`). */
|
|
114
|
+
onEvent(listener: (message: Message) => void): () => void {
|
|
115
|
+
this.eventListeners.add(listener);
|
|
116
|
+
return () => this.eventListeners.delete(listener);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
onClose(listener: () => void): () => void {
|
|
120
|
+
this.closeListeners.add(listener);
|
|
121
|
+
return () => this.closeListeners.delete(listener);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
close(): void {
|
|
125
|
+
this.socket.destroy();
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
private onLine(line: string): void {
|
|
129
|
+
let message: Message;
|
|
130
|
+
try {
|
|
131
|
+
message = JSON.parse(line) as Message;
|
|
132
|
+
} catch {
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
if (message.type === "event") {
|
|
136
|
+
for (const listener of this.eventListeners) listener(message);
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
const waiter = message.id ? this.pending.get(message.id) : undefined;
|
|
140
|
+
if (waiter && message.id) {
|
|
141
|
+
this.pending.delete(message.id);
|
|
142
|
+
waiter.resolve(message);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
private onClosed(): void {
|
|
147
|
+
this.closed = true;
|
|
148
|
+
for (const waiter of this.pending.values()) waiter.reject(new Error("connection closed"));
|
|
149
|
+
this.pending.clear();
|
|
150
|
+
for (const listener of this.closeListeners) listener();
|
|
151
|
+
}
|
|
152
|
+
}
|
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Codex side of the move core. A Codex thread is one rollout file plus whatever
|
|
3
|
+
* the app-server derives from it, so a move carries the rollout and the workspace;
|
|
4
|
+
* the target app-server indexes the imported rollout itself. Codex credentials
|
|
5
|
+
* (auth.json) are never part of a bundle: the target host signs in on its own.
|
|
6
|
+
*
|
|
7
|
+
* Source threads stay on the local Codex app-server; a retired thread is archived
|
|
8
|
+
* there (the tombstone) so no client can continue it by accident.
|
|
9
|
+
*/
|
|
10
|
+
import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
11
|
+
import { basename, dirname, join, relative, resolve } from "node:path";
|
|
12
|
+
import type { AgentMoveAdapter, ImportRequest, MovePreflightContext, ReadinessReport, ReadinessRequest, SessionBundleSpec } from "../core/adapter.ts";
|
|
13
|
+
import type { BundleManifest } from "../core/bundle.ts";
|
|
14
|
+
import { OwnershipStore } from "../core/ownership.ts";
|
|
15
|
+
import { ownershipPathFor } from "../paths.ts";
|
|
16
|
+
import { SERVER_EXTENSION_VERSIONS } from "../handshake.ts";
|
|
17
|
+
import { checkHostProvider } from "./provider.ts";
|
|
18
|
+
import { readRolloutMeta, readThreadName, rewriteRolloutCwd, rewriteRolloutProvider } from "./rollout.ts";
|
|
19
|
+
import type { CodexRuntime } from "./runtime.ts";
|
|
20
|
+
|
|
21
|
+
export const CODEX_AGENT_KIND = "codex";
|
|
22
|
+
const THREAD_STATE_FILE = "codex-thread.json";
|
|
23
|
+
|
|
24
|
+
interface ThreadState {
|
|
25
|
+
/** Rollout path relative to the sessions directory, so the target files it in the same place. */
|
|
26
|
+
rolloutRelPath: string;
|
|
27
|
+
originalCwd: string;
|
|
28
|
+
/** `session_meta.model_provider` on the source: the provider the thread's turns ran under. */
|
|
29
|
+
modelProvider?: string;
|
|
30
|
+
threadName?: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface CodexImportSnapshot {
|
|
34
|
+
/** The rollout this import replaced, kept until the move commits or is rolled back. */
|
|
35
|
+
backup?: { path: string; saved: string };
|
|
36
|
+
/** Path the import wrote, if it created a new rollout. */
|
|
37
|
+
created?: string;
|
|
38
|
+
wasArchived: boolean;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export class CodexMoveAdapter implements AgentMoveAdapter {
|
|
42
|
+
readonly kind = CODEX_AGENT_KIND;
|
|
43
|
+
readonly ownership: OwnershipStore;
|
|
44
|
+
private readonly runtime: CodexRuntime;
|
|
45
|
+
private readonly serverDir: string;
|
|
46
|
+
private readonly busy = new Map<string, boolean>();
|
|
47
|
+
|
|
48
|
+
constructor(runtime: CodexRuntime, serverDir: string) {
|
|
49
|
+
this.runtime = runtime;
|
|
50
|
+
this.serverDir = serverDir;
|
|
51
|
+
this.ownership = new OwnershipStore(ownershipPathFor(serverDir));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Receiver checks before anything is fenced: can this host's Codex run the thread under its provider (or the
|
|
56
|
+
* one the move rebinds it to)? With a `sessionId`, also describes that thread, so the sender can ask the
|
|
57
|
+
* source which provider the thread has before asking the target.
|
|
58
|
+
*/
|
|
59
|
+
async readiness(request: ReadinessRequest): Promise<ReadinessReport> {
|
|
60
|
+
this.runtime.assertPinned();
|
|
61
|
+
const checks: ReadinessReport["checks"] = [];
|
|
62
|
+
const wanted = request.rebindProvider ?? request.modelProvider;
|
|
63
|
+
if (wanted) {
|
|
64
|
+
const verdict = await checkHostProvider(await this.runtime.client(), wanted);
|
|
65
|
+
checks.push({ name: "provider-auth", ok: verdict.ok, detail: verdict.detail });
|
|
66
|
+
}
|
|
67
|
+
if (!request.sessionId) return { checks };
|
|
68
|
+
const blocked = this.ownership.blockedReason(request.sessionId);
|
|
69
|
+
if (blocked) throw new Error(blocked);
|
|
70
|
+
const file = this.runtime.rolloutPath(request.sessionId) ?? this.runtime.archivedRolloutPath(request.sessionId);
|
|
71
|
+
if (!file) throw new Error(`Unknown Codex thread: ${request.sessionId}`);
|
|
72
|
+
const meta = readRolloutMeta(file);
|
|
73
|
+
return { checks, session: { cwd: meta.cwd, cwdName: basename(meta.cwd), ...(meta.modelProvider ? { modelProvider: meta.modelProvider } : {}) } };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// ---- source side ----
|
|
77
|
+
|
|
78
|
+
hasSession(sessionId: string): boolean {
|
|
79
|
+
// A fenced thread sits in archived_sessions (see stop), so look there too.
|
|
80
|
+
return (this.runtime.rolloutPath(sessionId) ?? this.runtime.archivedRolloutPath(sessionId)) !== undefined;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* The app-server owns the truth about a running turn. isBusy is synchronous, so it
|
|
85
|
+
* answers from the last status it read and refreshes in the background; the fence
|
|
86
|
+
* loop polls it, and the source preflight primes it.
|
|
87
|
+
*/
|
|
88
|
+
isBusy(sessionId: string): boolean {
|
|
89
|
+
void this.refreshBusy(sessionId);
|
|
90
|
+
return this.busy.get(sessionId) ?? false;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
private async refreshBusy(sessionId: string): Promise<boolean> {
|
|
94
|
+
try {
|
|
95
|
+
const client = await this.runtime.client();
|
|
96
|
+
const { thread } = await client.call<{ thread: { status?: { type?: string } } }>("thread/read", { threadId: sessionId, includeTurns: false });
|
|
97
|
+
const active = thread.status?.type === "active";
|
|
98
|
+
this.busy.set(sessionId, active);
|
|
99
|
+
return active;
|
|
100
|
+
} catch {
|
|
101
|
+
// Unreachable app-server: nothing is running through it.
|
|
102
|
+
this.busy.set(sessionId, false);
|
|
103
|
+
return false;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Fence the thread against every client of the source app-server, not just this daemon's own
|
|
109
|
+
* connection: archiving unloads the thread for all of them and turn/start then fails with
|
|
110
|
+
* "thread not found", so a TUI attached through `pi-remote attach` or `codex resume --remote`
|
|
111
|
+
* cannot start or continue a turn until the move is aborted (resume() unarchives) or retired.
|
|
112
|
+
*/
|
|
113
|
+
async stop(sessionId: string): Promise<void> {
|
|
114
|
+
await this.archive(sessionId);
|
|
115
|
+
this.busy.set(sessionId, false);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
private async archive(sessionId: string): Promise<void> {
|
|
119
|
+
if (!this.runtime.rolloutPath(sessionId)) return; // already archived
|
|
120
|
+
try {
|
|
121
|
+
const client = await this.runtime.client();
|
|
122
|
+
await client.call("thread/unsubscribe", { threadId: sessionId }).catch(() => undefined);
|
|
123
|
+
await client.call("thread/archive", { threadId: sessionId });
|
|
124
|
+
} catch (error) {
|
|
125
|
+
// No app-server to ask: nobody can drive the thread through it, but keep it out of sessions/ ourselves.
|
|
126
|
+
const file = this.runtime.rolloutPath(sessionId);
|
|
127
|
+
if (!file) return;
|
|
128
|
+
try {
|
|
129
|
+
mkdirSync(this.runtime.archivedDir, { recursive: true });
|
|
130
|
+
renameSync(file, join(this.runtime.archivedDir, basename(file)));
|
|
131
|
+
} catch {
|
|
132
|
+
throw error;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
if (this.runtime.rolloutPath(sessionId)) throw new Error(`Could not take Codex thread ${sessionId} out of service on the source`);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
private async unarchive(sessionId: string): Promise<void> {
|
|
139
|
+
if (this.runtime.rolloutPath(sessionId)) return;
|
|
140
|
+
const archived = this.runtime.archivedRolloutPath(sessionId);
|
|
141
|
+
if (!archived) return;
|
|
142
|
+
try {
|
|
143
|
+
const client = await this.runtime.client();
|
|
144
|
+
await client.call("thread/unarchive", { threadId: sessionId });
|
|
145
|
+
} catch (error) {
|
|
146
|
+
const name = basename(archived);
|
|
147
|
+
const day = /^rollout-(\d{4})-(\d{2})-(\d{2})T/.exec(name);
|
|
148
|
+
const dir = day ? join(this.runtime.sessionsDir, day[1]!, day[2]!, day[3]!) : this.runtime.sessionsDir;
|
|
149
|
+
try {
|
|
150
|
+
mkdirSync(dir, { recursive: true });
|
|
151
|
+
renameSync(archived, join(dir, name));
|
|
152
|
+
} catch {
|
|
153
|
+
throw error;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
bundleSession(sessionId: string): SessionBundleSpec {
|
|
159
|
+
const file = this.runtime.rolloutPath(sessionId) ?? this.runtime.archivedRolloutPath(sessionId);
|
|
160
|
+
if (!file) throw new Error(`Unknown Codex thread: ${sessionId}`);
|
|
161
|
+
const meta = readRolloutMeta(file);
|
|
162
|
+
const name = readThreadName(this.runtime.home, sessionId);
|
|
163
|
+
const state: ThreadState = { rolloutRelPath: this.sessionsRelPath(file), originalCwd: meta.cwd, ...(meta.modelProvider ? { modelProvider: meta.modelProvider } : {}), ...(name ? { threadName: name } : {}) };
|
|
164
|
+
return {
|
|
165
|
+
cwd: meta.cwd,
|
|
166
|
+
agent: { kind: this.kind, version: this.runtime.version(), extensions: { ...SERVER_EXTENSION_VERSIONS } },
|
|
167
|
+
session: {
|
|
168
|
+
id: sessionId,
|
|
169
|
+
...(name ? { name } : {}),
|
|
170
|
+
...(meta.createdAt ? { createdAt: meta.createdAt } : {}),
|
|
171
|
+
metadata: { cwdName: basename(meta.cwd) },
|
|
172
|
+
},
|
|
173
|
+
sessionFiles: [{ name: basename(file), path: file }],
|
|
174
|
+
stateFiles: [{ name: THREAD_STATE_FILE, content: JSON.stringify(state) }],
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Where the rollout files under sessions/: YYYY/MM/DD/<name>, derived from the name for an archived one. */
|
|
179
|
+
private sessionsRelPath(file: string): string {
|
|
180
|
+
const name = basename(file);
|
|
181
|
+
const day = /^rollout-(\d{4})-(\d{2})-(\d{2})T/.exec(name);
|
|
182
|
+
return day ? join(day[1]!, day[2]!, day[3]!, name) : relative(this.runtime.sessionsDir, file);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
async retire(sessionId: string): Promise<void> {
|
|
186
|
+
// Already archived by stop(); archive() is a no-op then and keeps the tombstone.
|
|
187
|
+
await this.archive(sessionId);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
async resume(sessionId: string): Promise<void> {
|
|
191
|
+
// The move failed or was aborted: put the thread back where clients can load it.
|
|
192
|
+
await this.unarchive(sessionId);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// ---- target side ----
|
|
196
|
+
|
|
197
|
+
assertCanImport(sessionId: string): void {
|
|
198
|
+
if (this.runtime.rolloutPath(sessionId) && !this.ownership.blockedReason(sessionId)) {
|
|
199
|
+
throw new Error(`Codex thread ${sessionId} already exists on this host`);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
checkBundle(manifest: BundleManifest): void {
|
|
204
|
+
if (manifest.agent.kind !== this.kind) throw new Error(`Bundle was made by ${manifest.agent.kind}; this daemon hosts Codex threads`);
|
|
205
|
+
const local = this.runtime.version();
|
|
206
|
+
if (manifest.agent.version !== local) {
|
|
207
|
+
throw new Error(`Codex CLI version mismatch: bundle from codex-cli ${manifest.agent.version}, this host runs codex-cli ${local}. Both ends must run the same version.`);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
snapshot(sessionId: string): CodexImportSnapshot {
|
|
212
|
+
const active = this.runtime.rolloutPath(sessionId);
|
|
213
|
+
const archived = this.runtime.archivedRolloutPath(sessionId);
|
|
214
|
+
const existing = active ?? archived;
|
|
215
|
+
if (!existing) return { wasArchived: false };
|
|
216
|
+
const saved = join(this.serverDir, "imported", `${sessionId}.rollout.bak`);
|
|
217
|
+
mkdirSync(dirname(saved), { recursive: true, mode: 0o700 });
|
|
218
|
+
copyFileSync(existing, saved);
|
|
219
|
+
return { backup: { path: existing, saved }, wasArchived: active === undefined };
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
async importSession(request: ImportRequest): Promise<void> {
|
|
223
|
+
const { sessionId, manifest } = request;
|
|
224
|
+
const rolloutFile = manifest.files.find((file) => file.role === "session");
|
|
225
|
+
const stateFile = manifest.files.find((file) => file.role === "state" && basename(file.path) === THREAD_STATE_FILE);
|
|
226
|
+
if (!rolloutFile || !stateFile) throw new Error("Bundle has no Codex rollout");
|
|
227
|
+
const state = JSON.parse(readFileSync(join(request.extractedDir, stateFile.path), "utf8")) as ThreadState;
|
|
228
|
+
const sessionsDir = this.runtime.sessionsDir;
|
|
229
|
+
const target = resolve(sessionsDir, state.rolloutRelPath);
|
|
230
|
+
if (relative(sessionsDir, target).startsWith("..")) throw new Error(`Bundle rollout path escapes the sessions directory: ${state.rolloutRelPath}`);
|
|
231
|
+
|
|
232
|
+
const client = await this.runtime.client();
|
|
233
|
+
// The provider the thread will run under here. Checked before the rollout is written: a host that cannot use it
|
|
234
|
+
// would accept the move and then fail every turn with an authentication error.
|
|
235
|
+
const provider = request.rebindProvider ?? state.modelProvider;
|
|
236
|
+
if (provider) {
|
|
237
|
+
const verdict = await checkHostProvider(client, provider);
|
|
238
|
+
if (!verdict.ok) throw new Error(verdict.detail);
|
|
239
|
+
}
|
|
240
|
+
// A copy from an earlier visit (the tombstone of a move away) is dropped first, with the app-server's index row for it:
|
|
241
|
+
// the row keeps the old cwd, and it is only rebuilt from a rollout the app-server has not seen. snapshot() kept a copy
|
|
242
|
+
// of the file, so a failed move puts it back.
|
|
243
|
+
const stale = this.runtime.rolloutPath(sessionId) ?? this.runtime.archivedRolloutPath(sessionId);
|
|
244
|
+
if (stale) {
|
|
245
|
+
await client.call("thread/delete", { threadId: sessionId }).catch(() => undefined);
|
|
246
|
+
rmSync(stale, { force: true });
|
|
247
|
+
}
|
|
248
|
+
const destination = target;
|
|
249
|
+
|
|
250
|
+
const original = readFileSync(join(request.extractedDir, rolloutFile.path), "utf8");
|
|
251
|
+
const moved = rewriteRolloutCwd(original, state.originalCwd, request.cwd).text;
|
|
252
|
+
const rewritten = request.rebindProvider ? rewriteRolloutProvider(moved, request.rebindProvider).text : moved;
|
|
253
|
+
mkdirSync(dirname(destination), { recursive: true });
|
|
254
|
+
const temp = `${destination}.${process.pid}.tmp`;
|
|
255
|
+
writeFileSync(temp, rewritten, { mode: 0o600 });
|
|
256
|
+
renameSync(temp, destination);
|
|
257
|
+
|
|
258
|
+
// The app-server indexes the rollout when it first reads it. Read, then load the thread.
|
|
259
|
+
const { thread } = await client.call<{ thread: { id: string; cwd: string; modelProvider?: string } }>("thread/read", { threadId: sessionId, includeTurns: false });
|
|
260
|
+
if (thread.id !== sessionId) throw new Error(`Imported rollout reads back as thread ${thread.id}, not ${sessionId}`);
|
|
261
|
+
if (thread.cwd !== request.cwd) throw new Error(`Imported thread points at ${thread.cwd}, expected ${request.cwd}`);
|
|
262
|
+
if (request.rebindProvider && thread.modelProvider !== request.rebindProvider) throw new Error(`Imported thread runs under provider "${thread.modelProvider}", expected "${request.rebindProvider}"`);
|
|
263
|
+
const turns = await client.call<{ data: unknown[] }>("thread/turns/list", { threadId: sessionId, limit: 1 });
|
|
264
|
+
if (!Array.isArray(turns.data)) throw new Error("Imported thread has no readable history");
|
|
265
|
+
await client.call("thread/resume", { threadId: sessionId, excludeTurns: true });
|
|
266
|
+
await client.call("thread/unsubscribe", { threadId: sessionId }).catch(() => undefined);
|
|
267
|
+
if (state.threadName) await client.call("thread/name/set", { threadId: sessionId, name: state.threadName }).catch(() => undefined);
|
|
268
|
+
// Imported: the rollback copy is no longer needed.
|
|
269
|
+
rmSync(join(this.serverDir, "imported", `${sessionId}.rollout.bak`), { force: true });
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
async restore(sessionId: string, snapshot: unknown): Promise<void> {
|
|
273
|
+
const before = (snapshot ?? { wasArchived: false }) as CodexImportSnapshot;
|
|
274
|
+
const client = await this.runtime.client().catch(() => undefined);
|
|
275
|
+
await client?.call("thread/unsubscribe", { threadId: sessionId }).catch(() => undefined);
|
|
276
|
+
const current = this.runtime.rolloutPath(sessionId);
|
|
277
|
+
if (before.backup) {
|
|
278
|
+
if (current) rmSync(current, { force: true });
|
|
279
|
+
mkdirSync(dirname(before.backup.path), { recursive: true });
|
|
280
|
+
copyFileSync(before.backup.saved, before.backup.path);
|
|
281
|
+
rmSync(before.backup.saved, { force: true });
|
|
282
|
+
} else {
|
|
283
|
+
if (current) rmSync(current, { force: true });
|
|
284
|
+
await client?.call("thread/delete", { threadId: sessionId }).catch(() => undefined);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
async preflight(context: MovePreflightContext): Promise<void> {
|
|
289
|
+
this.runtime.assertPinned();
|
|
290
|
+
this.runtime.version();
|
|
291
|
+
if (context.side === "source") {
|
|
292
|
+
if (!this.runtime.rolloutPath(context.sessionId)) throw new Error(`Unknown Codex thread: ${context.sessionId}`);
|
|
293
|
+
await this.refreshBusy(context.sessionId);
|
|
294
|
+
} else {
|
|
295
|
+
await this.runtime.ensureDaemon();
|
|
296
|
+
if (!existsSync(this.runtime.home)) throw new Error(`CODEX_HOME ${this.runtime.home} does not exist on this host`);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
}
|