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,112 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* JSON-RPC client for the Codex app-server, over its control socket (WebSocket on
|
|
3
|
+
* a unix socket). The socket is only ever a local path: either the daemon's own, or
|
|
4
|
+
* one that ssh forwarded from another machine. Nothing here opens a network port.
|
|
5
|
+
*/
|
|
6
|
+
import { connectUnixWebSocket, type UnixWebSocket } from "./ws-unix.ts";
|
|
7
|
+
|
|
8
|
+
export type JsonRpcNotification = { method: string; params?: any };
|
|
9
|
+
|
|
10
|
+
export class AppServerError extends Error {
|
|
11
|
+
readonly code: number | undefined;
|
|
12
|
+
constructor(method: string, message: string, code?: number) {
|
|
13
|
+
super(`codex app-server ${method}: ${message}`);
|
|
14
|
+
this.name = "AppServerError";
|
|
15
|
+
this.code = code;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export class CodexAppServerClient {
|
|
20
|
+
private readonly ws: UnixWebSocket;
|
|
21
|
+
private readonly pending = new Map<number, { method: string; resolve: (value: any) => void; reject: (error: Error) => void }>();
|
|
22
|
+
private readonly listeners = new Set<(notification: JsonRpcNotification) => void>();
|
|
23
|
+
private nextId = 1;
|
|
24
|
+
private closed = false;
|
|
25
|
+
/** Result of `initialize`: includes `codexHome`. */
|
|
26
|
+
info: { codexHome?: string; userAgent?: string } = {};
|
|
27
|
+
|
|
28
|
+
private constructor(ws: UnixWebSocket) {
|
|
29
|
+
this.ws = ws;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
static async connect(socketPath: string, clientName = "pi-better-server"): Promise<CodexAppServerClient> {
|
|
33
|
+
let client: CodexAppServerClient | undefined;
|
|
34
|
+
const ws = await connectUnixWebSocket(socketPath, {
|
|
35
|
+
onMessage: (text) => client?.onMessage(text),
|
|
36
|
+
onClose: () => client?.onClosed(),
|
|
37
|
+
});
|
|
38
|
+
client = new CodexAppServerClient(ws);
|
|
39
|
+
try {
|
|
40
|
+
client.info = await client.call("initialize", { clientInfo: { name: clientName, version: "0" }, capabilities: null });
|
|
41
|
+
ws.send(JSON.stringify({ method: "initialized" }));
|
|
42
|
+
} catch (error) {
|
|
43
|
+
client.close();
|
|
44
|
+
throw error;
|
|
45
|
+
}
|
|
46
|
+
return client;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
call<T = any>(method: string, params: Record<string, unknown> = {}, timeoutMs = 30_000): Promise<T> {
|
|
50
|
+
if (this.closed) return Promise.reject(new AppServerError(method, "connection closed"));
|
|
51
|
+
const id = this.nextId++;
|
|
52
|
+
return new Promise<T>((resolve, reject) => {
|
|
53
|
+
const timer = setTimeout(() => {
|
|
54
|
+
this.pending.delete(id);
|
|
55
|
+
reject(new AppServerError(method, `no reply in ${timeoutMs}ms`));
|
|
56
|
+
}, timeoutMs);
|
|
57
|
+
this.pending.set(id, {
|
|
58
|
+
method,
|
|
59
|
+
resolve: (value) => {
|
|
60
|
+
clearTimeout(timer);
|
|
61
|
+
resolve(value);
|
|
62
|
+
},
|
|
63
|
+
reject: (error) => {
|
|
64
|
+
clearTimeout(timer);
|
|
65
|
+
reject(error);
|
|
66
|
+
},
|
|
67
|
+
});
|
|
68
|
+
this.ws.send(JSON.stringify({ id, method, params }));
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
onNotification(listener: (notification: JsonRpcNotification) => void): () => void {
|
|
73
|
+
this.listeners.add(listener);
|
|
74
|
+
return () => void this.listeners.delete(listener);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
get isClosed(): boolean {
|
|
78
|
+
return this.closed;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
close(): void {
|
|
82
|
+
if (this.closed) return;
|
|
83
|
+
this.closed = true;
|
|
84
|
+
this.ws.close();
|
|
85
|
+
this.onClosed();
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
private onMessage(text: string): void {
|
|
89
|
+
let message: any;
|
|
90
|
+
try {
|
|
91
|
+
message = JSON.parse(text);
|
|
92
|
+
} catch {
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
if (typeof message.id === "number" && this.pending.has(message.id) && (message.result !== undefined || message.error !== undefined)) {
|
|
96
|
+
const entry = this.pending.get(message.id)!;
|
|
97
|
+
this.pending.delete(message.id);
|
|
98
|
+
if (message.error) entry.reject(new AppServerError(entry.method, String(message.error.message ?? "request failed"), message.error.code));
|
|
99
|
+
else entry.resolve(message.result);
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
if (typeof message.method === "string" && message.id === undefined) for (const listener of this.listeners) listener(message);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
private onClosed(): void {
|
|
106
|
+
this.closed = true;
|
|
107
|
+
for (const [id, entry] of this.pending) {
|
|
108
|
+
this.pending.delete(id);
|
|
109
|
+
entry.reject(new AppServerError(entry.method, "connection closed"));
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Daemon for Codex hosts: the same unix-socket protocol as the Pi daemon, limited to
|
|
3
|
+
* what a Codex host needs: hello, list_sessions (Codex threads), get_state / steer / prompt
|
|
4
|
+
* (so `pi-remote steer` works on a thread), the move commands, and `codex_endpoint`
|
|
5
|
+
* (where the Codex app-server's control socket is, for attach).
|
|
6
|
+
* The daemon never listens on TCP, and the app-server it fronts is reached only
|
|
7
|
+
* through its own unix socket.
|
|
8
|
+
*/
|
|
9
|
+
import { chmodSync, existsSync, statSync, unlinkSync } from "node:fs";
|
|
10
|
+
import { connect, createServer, type Server, type Socket } from "node:net";
|
|
11
|
+
import { readGitBranch } from "../git.ts";
|
|
12
|
+
import { checkHello } from "../handshake.ts";
|
|
13
|
+
import { MoveHost } from "../core/move-host.ts";
|
|
14
|
+
import { defaultServerDir, ensureServerDir, movesDirFor, socketPathFor } from "../paths.ts";
|
|
15
|
+
import { encodeLine, failure, LineDecoder, MOVE_COMMANDS, type MoveCommand, type ServerMessage, type SessionSummary } from "../protocol.ts";
|
|
16
|
+
import { CodexMoveAdapter } from "./adapter.ts";
|
|
17
|
+
import { deliverToThread, isThreadRunning } from "./deliver.ts";
|
|
18
|
+
import { readRolloutMeta, readThreadName } from "./rollout.ts";
|
|
19
|
+
import { CodexRuntime, type CodexRuntimeOptions } from "./runtime.ts";
|
|
20
|
+
|
|
21
|
+
export interface CodexDaemonOptions {
|
|
22
|
+
serverDir?: string;
|
|
23
|
+
codex?: CodexRuntimeOptions;
|
|
24
|
+
log?: (message: string) => void;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface CodexDaemon {
|
|
28
|
+
readonly serverDir: string;
|
|
29
|
+
readonly socketPath: string;
|
|
30
|
+
readonly runtime: CodexRuntime;
|
|
31
|
+
stop(): Promise<void>;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface CodexEndpoint {
|
|
35
|
+
/** Unix socket of the Codex app-server on the daemon's host. */
|
|
36
|
+
socketPath: string;
|
|
37
|
+
codexVersion: string;
|
|
38
|
+
appServerVersion?: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function socketIsLive(path: string): Promise<boolean> {
|
|
42
|
+
return new Promise((resolve) => {
|
|
43
|
+
const probe = connect(path);
|
|
44
|
+
probe.once("connect", () => {
|
|
45
|
+
probe.destroy();
|
|
46
|
+
resolve(true);
|
|
47
|
+
});
|
|
48
|
+
probe.once("error", () => resolve(false));
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** What the thread's most recent turn failed with, if it did. */
|
|
53
|
+
async function lastTurnError(runtime: CodexRuntime, threadId: string): Promise<string | undefined> {
|
|
54
|
+
try {
|
|
55
|
+
const client = await runtime.client();
|
|
56
|
+
const page = await client.call<{ data: Array<{ status: string; error?: { message?: string; additionalDetails?: string | null } | null }> }>("thread/turns/list", { threadId, limit: 1 });
|
|
57
|
+
const turn = page.data[0];
|
|
58
|
+
if (turn?.status !== "failed" || !turn.error?.message) return undefined;
|
|
59
|
+
return turn.error.additionalDetails && !turn.error.message.includes(turn.error.additionalDetails) ? `${turn.error.message} (${turn.error.additionalDetails})` : turn.error.message;
|
|
60
|
+
} catch {
|
|
61
|
+
return undefined;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async function listThreads(runtime: CodexRuntime, adapter: CodexMoveAdapter): Promise<SessionSummary[]> {
|
|
66
|
+
const client = await runtime.client();
|
|
67
|
+
const sessions: SessionSummary[] = [];
|
|
68
|
+
// thread/list shows only the host's default provider unless told otherwise; a thread rebound to another configured provider must stay listed.
|
|
69
|
+
const { config } = await client.call<{ config: { model_provider?: string | null; model_providers?: Record<string, unknown> | null } }>("config/read", {});
|
|
70
|
+
const modelProviders = [...new Set([config.model_provider ?? "openai", "openai", ...Object.keys(config.model_providers ?? {})])];
|
|
71
|
+
let cursor: string | null = null;
|
|
72
|
+
do {
|
|
73
|
+
const page: { data: any[]; nextCursor: string | null } = await client.call("thread/list", { limit: 100, cursor, modelProviders, sourceKinds: ["cli", "vscode", "exec", "appServer"] });
|
|
74
|
+
for (const thread of page.data) {
|
|
75
|
+
const ownership = adapter.ownership.get(thread.id).state;
|
|
76
|
+
const branch = typeof thread.cwd === "string" ? readGitBranch(thread.cwd) : undefined;
|
|
77
|
+
const iso = (seconds: unknown): string => new Date(Number(seconds) * 1000).toISOString();
|
|
78
|
+
sessions.push({
|
|
79
|
+
sessionId: thread.id,
|
|
80
|
+
cwd: thread.cwd,
|
|
81
|
+
sessionFile: thread.path ?? "",
|
|
82
|
+
status: "running",
|
|
83
|
+
...(thread.name ? { name: thread.name } : thread.preview ? { name: String(thread.preview).slice(0, 80) } : {}),
|
|
84
|
+
...(thread.model ? { model: thread.model } : {}),
|
|
85
|
+
...(branch ? { branch } : {}),
|
|
86
|
+
isStreaming: thread.status?.type === "active",
|
|
87
|
+
...(thread.status?.type === "systemError" ? { lastError: (await lastTurnError(runtime, thread.id)) ?? "the last turn failed" } : {}),
|
|
88
|
+
...(ownership !== "owned" ? { ownership } : {}),
|
|
89
|
+
live: thread.status?.type !== "notLoaded",
|
|
90
|
+
lastSeq: 0,
|
|
91
|
+
hasController: false,
|
|
92
|
+
needsInput: [],
|
|
93
|
+
createdAt: iso(thread.createdAt),
|
|
94
|
+
updatedAt: iso(thread.updatedAt),
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
cursor = page.nextCursor;
|
|
98
|
+
} while (cursor);
|
|
99
|
+
// A fenced or moved thread is archived on this app-server (thread/list omits it), but it must stay
|
|
100
|
+
// addressable: `move --abort`, `--retire` and `ls` resolve it here. Build its row from the rollout.
|
|
101
|
+
const listed = new Set(sessions.map((session) => session.sessionId));
|
|
102
|
+
for (const record of adapter.ownership.list()) {
|
|
103
|
+
if (record.state === "owned" || listed.has(record.sessionId)) continue;
|
|
104
|
+
const file = runtime.rolloutPath(record.sessionId) ?? runtime.archivedRolloutPath(record.sessionId);
|
|
105
|
+
if (!file) continue;
|
|
106
|
+
try {
|
|
107
|
+
const meta = readRolloutMeta(file);
|
|
108
|
+
const name = readThreadName(runtime.home, record.sessionId);
|
|
109
|
+
sessions.push({
|
|
110
|
+
sessionId: record.sessionId,
|
|
111
|
+
cwd: meta.cwd,
|
|
112
|
+
sessionFile: file,
|
|
113
|
+
status: "closed",
|
|
114
|
+
...(name ? { name } : {}),
|
|
115
|
+
isStreaming: false,
|
|
116
|
+
ownership: record.state,
|
|
117
|
+
live: false,
|
|
118
|
+
lastSeq: 0,
|
|
119
|
+
hasController: false,
|
|
120
|
+
needsInput: [],
|
|
121
|
+
createdAt: meta.createdAt ?? record.updatedAt,
|
|
122
|
+
updatedAt: statSync(file).mtime.toISOString(),
|
|
123
|
+
});
|
|
124
|
+
} catch {
|
|
125
|
+
/* an unreadable rollout cannot be summarized; the move commands still accept the full id */
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return sessions;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export async function startCodexDaemon(options: CodexDaemonOptions = {}): Promise<CodexDaemon> {
|
|
132
|
+
const serverDir = options.serverDir ?? defaultServerDir();
|
|
133
|
+
const socketPath = socketPathFor(serverDir);
|
|
134
|
+
const log = options.log ?? (() => undefined);
|
|
135
|
+
ensureServerDir(serverDir);
|
|
136
|
+
if (existsSync(socketPath)) {
|
|
137
|
+
if (await socketIsLive(socketPath)) throw new Error(`A pi-better-server is already listening on ${socketPath}`);
|
|
138
|
+
unlinkSync(socketPath);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const runtime = new CodexRuntime(options.codex);
|
|
142
|
+
runtime.assertPinned();
|
|
143
|
+
const adapter = new CodexMoveAdapter(runtime, serverDir);
|
|
144
|
+
const moves = new MoveHost(adapter, serverDir, movesDirFor(serverDir));
|
|
145
|
+
|
|
146
|
+
const sockets = new Set<Socket>();
|
|
147
|
+
const server: Server = createServer((socket) => {
|
|
148
|
+
sockets.add(socket);
|
|
149
|
+
const send = (message: unknown): void => {
|
|
150
|
+
if (!socket.destroyed) socket.write(encodeLine(message));
|
|
151
|
+
};
|
|
152
|
+
const dispatch = async (line: string): Promise<void> => {
|
|
153
|
+
let command: Record<string, unknown>;
|
|
154
|
+
try {
|
|
155
|
+
const parsed: unknown = JSON.parse(line);
|
|
156
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error("not an object");
|
|
157
|
+
command = parsed as Record<string, unknown>;
|
|
158
|
+
} catch {
|
|
159
|
+
send(failure(undefined, "parse", "Invalid JSON line"));
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
const id = typeof command.id === "string" ? command.id : undefined;
|
|
163
|
+
const type = typeof command.type === "string" ? command.type : "";
|
|
164
|
+
const reply = (message: Record<string, unknown>): void => send({ ...(id !== undefined ? { id } : {}), type: "response", command: type, success: true, ...message } as ServerMessage);
|
|
165
|
+
try {
|
|
166
|
+
if (type === "hello") {
|
|
167
|
+
const verdict = checkHello(command);
|
|
168
|
+
if (verdict.ok) return reply({ data: { ...verdict.data, extensionVersions: { ...verdict.data.extensionVersions, "codex-cli": runtime.version() } } });
|
|
169
|
+
send(failure(id, type, verdict.error));
|
|
170
|
+
socket.end();
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
if (MOVE_COMMANDS.has(type)) return reply(await moves.handle(command as MoveCommand));
|
|
174
|
+
if (type === "list_sessions") return reply({ data: { sessions: await listThreads(runtime, adapter) } });
|
|
175
|
+
if (type === "get_state" || type === "steer" || type === "prompt") {
|
|
176
|
+
const sessionId = typeof command.sessionId === "string" ? command.sessionId : "";
|
|
177
|
+
if (!sessionId) throw new Error(`${type} needs a sessionId`);
|
|
178
|
+
if (type === "get_state") return reply({ sessionId, data: { sessionId, isStreaming: await isThreadRunning(adapter, runtime, sessionId) } });
|
|
179
|
+
const message = typeof command.message === "string" ? command.message.trim() : "";
|
|
180
|
+
if (!message) throw new Error(`${type} needs a message`);
|
|
181
|
+
return reply({ sessionId, data: await deliverToThread(adapter, runtime, sessionId, message) });
|
|
182
|
+
}
|
|
183
|
+
if (type === "codex_endpoint") {
|
|
184
|
+
const status = await runtime.daemonStatus();
|
|
185
|
+
const endpoint: CodexEndpoint = { socketPath: status.socketPath, codexVersion: runtime.version(), ...(status.appServerVersion ? { appServerVersion: status.appServerVersion } : {}) };
|
|
186
|
+
return reply({ data: endpoint });
|
|
187
|
+
}
|
|
188
|
+
send(failure(id, type || "unknown", `Codex hosts do not serve "${type}". Use the Codex TUI (pi-remote attach) to drive a thread.`));
|
|
189
|
+
} catch (error) {
|
|
190
|
+
send(failure(id, type || "unknown", error instanceof Error ? error.message : String(error)));
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
socket.setEncoding("utf8");
|
|
194
|
+
const decoder = new LineDecoder(
|
|
195
|
+
(line) => void dispatch(line),
|
|
196
|
+
() => {
|
|
197
|
+
send(failure(undefined, "parse", "Line too long"));
|
|
198
|
+
socket.destroy();
|
|
199
|
+
},
|
|
200
|
+
);
|
|
201
|
+
socket.on("data", (chunk: string) => decoder.push(chunk));
|
|
202
|
+
socket.on("error", () => undefined);
|
|
203
|
+
socket.on("close", () => sockets.delete(socket));
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
await new Promise<void>((resolve, reject) => {
|
|
207
|
+
server.once("error", reject);
|
|
208
|
+
server.listen(socketPath, () => {
|
|
209
|
+
server.off("error", reject);
|
|
210
|
+
resolve();
|
|
211
|
+
});
|
|
212
|
+
});
|
|
213
|
+
chmodSync(socketPath, 0o600);
|
|
214
|
+
log(`codex host listening on ${socketPath} (codex-cli ${runtime.version()}, CODEX_HOME ${runtime.home})`);
|
|
215
|
+
|
|
216
|
+
let stopped: Promise<void> | undefined;
|
|
217
|
+
return {
|
|
218
|
+
serverDir,
|
|
219
|
+
socketPath,
|
|
220
|
+
runtime,
|
|
221
|
+
stop() {
|
|
222
|
+
stopped ??= (async () => {
|
|
223
|
+
const closed = new Promise<void>((resolve) => server.close(() => resolve()));
|
|
224
|
+
for (const socket of sockets) socket.destroy();
|
|
225
|
+
await closed;
|
|
226
|
+
runtime.close();
|
|
227
|
+
if (existsSync(socketPath)) unlinkSync(socketPath);
|
|
228
|
+
})();
|
|
229
|
+
return stopped;
|
|
230
|
+
},
|
|
231
|
+
};
|
|
232
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Getting a message into a Codex thread through the app-server: `turn/steer` while a turn
|
|
3
|
+
* runs (the text joins the turn at its next model call), `turn/start` when the thread is
|
|
4
|
+
* idle. The same thing `codex queue --thread` does, without a second process.
|
|
5
|
+
*/
|
|
6
|
+
import type { CodexAppServerClient } from "./app-server.ts";
|
|
7
|
+
import type { CodexMoveAdapter } from "./adapter.ts";
|
|
8
|
+
import type { CodexRuntime } from "./runtime.ts";
|
|
9
|
+
|
|
10
|
+
export type Delivery = "steer" | "prompt";
|
|
11
|
+
|
|
12
|
+
export interface DeliveryResult {
|
|
13
|
+
delivered: Delivery;
|
|
14
|
+
/** The new turn failed (or its model request did) within the watch window; the text is what Codex reported. */
|
|
15
|
+
failure?: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** How long a freshly started turn is watched for an immediate failure (a rejected key fails within a second). */
|
|
19
|
+
const TURN_WATCH_MS = Number(process.env.PI_CODEX_TURN_WATCH_MS ?? 3000);
|
|
20
|
+
|
|
21
|
+
const NO_ACTIVE_TURN = /no active turn/i;
|
|
22
|
+
|
|
23
|
+
function userInput(text: string): unknown[] {
|
|
24
|
+
return [{ type: "text", text, text_elements: [] }];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** A thread this daemon may drive: present here and not fenced or handed to another host. */
|
|
28
|
+
export function assertDrivable(adapter: CodexMoveAdapter, runtime: CodexRuntime, threadId: string): void {
|
|
29
|
+
const ownership = adapter.ownership.get(threadId).state;
|
|
30
|
+
if (ownership !== "owned") throw new Error(`Thread ${threadId} is ${ownership} on this host and cannot take messages here; drive it where it now lives`);
|
|
31
|
+
if (!runtime.rolloutPath(threadId)) throw new Error(`Unknown Codex thread: ${threadId}`);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async function threadStatus(runtime: CodexRuntime, threadId: string): Promise<string> {
|
|
35
|
+
const client = await runtime.client();
|
|
36
|
+
const { thread } = await client.call<{ thread: { status?: { type?: string } } }>("thread/read", { threadId, includeTurns: false });
|
|
37
|
+
return thread.status?.type ?? "notLoaded";
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export async function isThreadRunning(adapter: CodexMoveAdapter, runtime: CodexRuntime, threadId: string): Promise<boolean> {
|
|
41
|
+
assertDrivable(adapter, runtime, threadId);
|
|
42
|
+
return (await threadStatus(runtime, threadId)) === "active";
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async function activeTurnId(runtime: CodexRuntime, threadId: string): Promise<string | undefined> {
|
|
46
|
+
const client = await runtime.client();
|
|
47
|
+
const page = await client.call<{ data: Array<{ id: string; status: string }> }>("thread/turns/list", { threadId, limit: 5 });
|
|
48
|
+
return page.data.find((turn) => turn.status === "inProgress")?.id;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function describeFailure(error: { message?: string; additionalDetails?: string | null } | null | undefined): string {
|
|
52
|
+
const detail = error?.additionalDetails && !error.message?.includes(error.additionalDetails) ? ` (${error.additionalDetails})` : "";
|
|
53
|
+
return `${error?.message ?? "the turn failed"}${detail}`;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Watch the turn just started. Resolves with the error it failed with, or undefined when it completes, when its status cannot be read, or when
|
|
58
|
+
* `TURN_WATCH_MS` passes while it is still going (a running turn is not a failure; `ls` shows a later failure).
|
|
59
|
+
*/
|
|
60
|
+
async function failureOfTurn(client: CodexAppServerClient, threadId: string, turnId: string | undefined): Promise<string | undefined> {
|
|
61
|
+
const deadline = Date.now() + TURN_WATCH_MS;
|
|
62
|
+
for (;;) {
|
|
63
|
+
type TurnRow = { id: string; status: string; error?: { message?: string; additionalDetails?: string | null } | null };
|
|
64
|
+
// The turn already started; failing to read its status afterwards is "no failure seen", not a failed delivery.
|
|
65
|
+
const page = await client.call<{ data: TurnRow[] }>("thread/turns/list", { threadId, limit: 3 }).catch(() => undefined);
|
|
66
|
+
if (!page) return undefined;
|
|
67
|
+
const turn = turnId ? page.data.find((candidate) => candidate.id === turnId) : page.data[0];
|
|
68
|
+
if (turn?.status === "failed") return describeFailure(turn.error);
|
|
69
|
+
// Right after turn/start the history can still read the new turn as "interrupted" (nothing is recorded for it yet); only a final status counts.
|
|
70
|
+
if (turn?.status === "completed") return undefined;
|
|
71
|
+
if (Date.now() >= deadline) return undefined;
|
|
72
|
+
await new Promise((resolve) => setTimeout(resolve, 150));
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Deliver `text`. Mid-turn it steers the running turn; idle it starts a turn. A turn
|
|
78
|
+
* that ends (or starts) between the status read and the call is delivered the other way: the running
|
|
79
|
+
* turn is looked up right before `turn/start`, and a steer that finds its turn gone is retried as a start.
|
|
80
|
+
*/
|
|
81
|
+
export async function deliverToThread(adapter: CodexMoveAdapter, runtime: CodexRuntime, threadId: string, text: string): Promise<DeliveryResult> {
|
|
82
|
+
assertDrivable(adapter, runtime, threadId);
|
|
83
|
+
const client = await runtime.client();
|
|
84
|
+
const status = await threadStatus(runtime, threadId);
|
|
85
|
+
if (status === "notLoaded") await client.call("thread/resume", { threadId, excludeTurns: true });
|
|
86
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
87
|
+
// Look for a running turn even when the status read said idle: another client may have started one since.
|
|
88
|
+
const turnId = await activeTurnId(runtime, threadId);
|
|
89
|
+
if (turnId) {
|
|
90
|
+
try {
|
|
91
|
+
await client.call("turn/steer", { threadId, expectedTurnId: turnId, input: userInput(text) });
|
|
92
|
+
return { delivered: "steer" };
|
|
93
|
+
} catch (error) {
|
|
94
|
+
if (!(error instanceof Error && NO_ACTIVE_TURN.test(error.message))) throw error;
|
|
95
|
+
continue; // the turn ended just now; start one
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
const started = await client.call<{ turn?: { id?: string } }>("turn/start", { threadId, input: userInput(text) });
|
|
99
|
+
const failure = await failureOfTurn(client, threadId, started.turn?.id);
|
|
100
|
+
return { delivered: "prompt", ...(failure ? { failure } : {}) };
|
|
101
|
+
}
|
|
102
|
+
throw new Error(`Could not deliver to ${threadId}: its turn state kept changing`);
|
|
103
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Before a Codex thread is fenced: ask the source which model provider the thread has, then ask the target
|
|
3
|
+
* whether its Codex can use that provider (or the one `--codex-provider` rebinds the thread to). Nothing is
|
|
4
|
+
* fenced, written or sent when the target says no.
|
|
5
|
+
*/
|
|
6
|
+
import type { MoveEndpoint } from "../move/orchestrate.ts";
|
|
7
|
+
import { assertChecks, type CheckResult } from "../move/preflight.ts";
|
|
8
|
+
|
|
9
|
+
export async function preflightCodexProvider(source: MoveEndpoint, target: MoveEndpoint, sessionId: string, rebindProvider: string | undefined): Promise<void> {
|
|
10
|
+
const described = await source.call({ type: "move_preflight", sessionId });
|
|
11
|
+
const modelProvider = (described.data as { session?: { modelProvider?: string } }).session?.modelProvider;
|
|
12
|
+
if (!modelProvider && !rebindProvider) return;
|
|
13
|
+
const answer = await target.call({ type: "move_preflight", ...(modelProvider ? { modelProvider } : {}), ...(rebindProvider ? { rebindProvider } : {}) });
|
|
14
|
+
assertChecks((answer.data as { checks: CheckResult[] }).checks);
|
|
15
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Can this host's Codex run a thread under a given model provider? A thread keeps the provider it was
|
|
3
|
+
* recorded under (`session_meta.model_provider`), and the host's sign-in belongs to the providers that host
|
|
4
|
+
* set up, so a thread moved to a host whose login is for another provider fails every turn with a 401.
|
|
5
|
+
* The answer comes from the host's own app-server (`config/read`, `account/read`); no credential is read here.
|
|
6
|
+
*/
|
|
7
|
+
import type { CodexAppServerClient } from "./app-server.ts";
|
|
8
|
+
|
|
9
|
+
export interface ProviderCheck {
|
|
10
|
+
ok: boolean;
|
|
11
|
+
detail: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
interface ProviderConfig {
|
|
15
|
+
env_key?: string | null;
|
|
16
|
+
experimental_bearer_token?: string | null;
|
|
17
|
+
auth?: unknown;
|
|
18
|
+
aws?: unknown;
|
|
19
|
+
requires_openai_auth?: boolean;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
interface AccountView {
|
|
23
|
+
account: { type?: string } | null;
|
|
24
|
+
requiresOpenaiAuth?: boolean;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Providers Codex ships with; they are not listed under `[model_providers]` in config.toml. */
|
|
28
|
+
const BUILT_IN_NO_AUTH = new Set(["ollama", "lmstudio"]);
|
|
29
|
+
|
|
30
|
+
export async function checkHostProvider(client: CodexAppServerClient, provider: string, env: NodeJS.ProcessEnv = process.env): Promise<ProviderCheck> {
|
|
31
|
+
const { config } = await client.call<{ config: { model_provider?: string | null; model_providers?: Record<string, ProviderConfig> | null } }>("config/read", {});
|
|
32
|
+
const account = await client.call<AccountView>("account/read", {});
|
|
33
|
+
const configured = config.model_providers ?? {};
|
|
34
|
+
const fallback = config.model_provider ?? "openai";
|
|
35
|
+
const known = [...new Set([fallback, ...Object.keys(configured)])].map((id) => `"${id}"`).join(", ");
|
|
36
|
+
const login = account.account?.type;
|
|
37
|
+
const not = (why: string): ProviderCheck => ({ ok: false, detail: `model provider "${provider}" cannot be used there: ${why}. This host's default provider is "${fallback}" (configured: ${known}); pass --codex-provider <id> to rebind the thread to one of them` });
|
|
38
|
+
|
|
39
|
+
// Own keys only: `constructor`, `toString` and `__proto__` are not configured providers.
|
|
40
|
+
const own = Object.hasOwn(configured, provider) ? configured[provider] : undefined;
|
|
41
|
+
if (own) {
|
|
42
|
+
if (own.env_key) return env[own.env_key] ? { ok: true, detail: `provider "${provider}" is configured there (key from $${own.env_key})` } : not(`it needs $${own.env_key}, which is not set there`);
|
|
43
|
+
if (own.experimental_bearer_token || own.auth || own.aws) return { ok: true, detail: `provider "${provider}" is configured there` };
|
|
44
|
+
if (own.requires_openai_auth) return login ? { ok: true, detail: `provider "${provider}" is configured there and Codex is signed in (${login})` } : not("it needs a Codex sign-in and this host is not signed in (`codex login`)");
|
|
45
|
+
return { ok: true, detail: `provider "${provider}" is configured there and needs no sign-in` };
|
|
46
|
+
}
|
|
47
|
+
if (provider === "openai") {
|
|
48
|
+
if (login === "chatgpt") return { ok: true, detail: 'provider "openai" is usable there (ChatGPT sign-in)' };
|
|
49
|
+
if (login === "apiKey" && fallback === "openai") return { ok: true, detail: 'provider "openai" is usable there (API key)' };
|
|
50
|
+
if (login === "apiKey") return not(`its only sign-in is an API key, which belongs to the provider "${fallback}" configured there`);
|
|
51
|
+
return not("this host is not signed in (`codex login`)");
|
|
52
|
+
}
|
|
53
|
+
if (BUILT_IN_NO_AUTH.has(provider)) return { ok: true, detail: `provider "${provider}" is built in and needs no sign-in` };
|
|
54
|
+
return not("it is not configured there");
|
|
55
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `pi-remote return` for a Codex thread: the move in the other direction. The host that
|
|
3
|
+
* has the thread is the source, this machine's Codex daemon is the target, and the same
|
|
4
|
+
* `moveSession` runs it, so the guarantees are the same ones a move away has: the host
|
|
5
|
+
* keeps the thread fenced until this machine acknowledges it (no half-moved state), and
|
|
6
|
+
* once it has, the host's copy is archived (one live writer).
|
|
7
|
+
*/
|
|
8
|
+
import { existsSync, readdirSync } from "node:fs";
|
|
9
|
+
import { resolve } from "node:path";
|
|
10
|
+
import { DaemonClient } from "../client.ts";
|
|
11
|
+
import { moveSession, type MoveResult } from "../move/orchestrate.ts";
|
|
12
|
+
import { defaultServerDir, socketPathFor } from "../paths.ts";
|
|
13
|
+
import { resolveSession } from "../remote/sessions.ts";
|
|
14
|
+
import { preflightCodexProvider } from "./preflight.ts";
|
|
15
|
+
import { readRolloutMeta } from "./rollout.ts";
|
|
16
|
+
import { startCodexDaemon, type CodexDaemon } from "./daemon.ts";
|
|
17
|
+
import { CodexRuntime, type CodexRuntimeOptions } from "./runtime.ts";
|
|
18
|
+
|
|
19
|
+
export interface ReturnCodexOptions {
|
|
20
|
+
/** Thread id, unique id prefix or name on the host. */
|
|
21
|
+
ref: string;
|
|
22
|
+
/** Connected client for the host's Codex daemon. */
|
|
23
|
+
host: DaemonClient;
|
|
24
|
+
/** This machine's daemon dir (default: the usual one). */
|
|
25
|
+
serverDir?: string;
|
|
26
|
+
codex?: CodexRuntimeOptions;
|
|
27
|
+
/** Where to rebuild the workspace. Default: where the thread lived before it moved away. */
|
|
28
|
+
toCwd?: string;
|
|
29
|
+
/** Bind the returned thread to this model provider on this machine (the host's provider may not exist here). */
|
|
30
|
+
rebindProvider?: string;
|
|
31
|
+
waitMs?: number;
|
|
32
|
+
onProgress?: (message: string) => void;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface ReturnCodexResult extends MoveResult {
|
|
36
|
+
resumeCommand: string;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function isCodexHost(client: DaemonClient): boolean {
|
|
40
|
+
return client.server?.extensionVersions?.["codex-cli"] !== undefined;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** The local Codex daemon: the one already running in `serverDir`, else one that lives for this command. */
|
|
44
|
+
async function localDaemon(serverDir: string, codex: CodexRuntimeOptions | undefined): Promise<{ client: DaemonClient; runtime: CodexRuntime; /** True when a daemon was already running and keeps the thread loaded after this command. */ managed: boolean; stop(): Promise<void> }> {
|
|
45
|
+
let started: CodexDaemon | undefined;
|
|
46
|
+
let client: DaemonClient;
|
|
47
|
+
try {
|
|
48
|
+
client = await DaemonClient.connect(socketPathFor(serverDir));
|
|
49
|
+
} catch (error) {
|
|
50
|
+
if ((error as NodeJS.ErrnoException).code && !["ENOENT", "ECONNREFUSED"].includes((error as NodeJS.ErrnoException).code!)) throw error;
|
|
51
|
+
started = await startCodexDaemon({ serverDir, ...(codex ? { codex } : {}) });
|
|
52
|
+
client = await DaemonClient.connect(started.socketPath);
|
|
53
|
+
}
|
|
54
|
+
if (client.server?.extensionVersions?.["codex-cli"] === undefined) {
|
|
55
|
+
client.close();
|
|
56
|
+
await started?.stop();
|
|
57
|
+
throw new Error(`The daemon in ${serverDir} hosts Pi sessions, not Codex threads. Stop it, or point PI_SERVER_DIR at a Codex daemon dir.`);
|
|
58
|
+
}
|
|
59
|
+
return {
|
|
60
|
+
client,
|
|
61
|
+
runtime: started?.runtime ?? new CodexRuntime(codex),
|
|
62
|
+
managed: started === undefined,
|
|
63
|
+
async stop() {
|
|
64
|
+
client.close();
|
|
65
|
+
await started?.stop();
|
|
66
|
+
},
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* How to continue a returned thread. While this machine's daemon is running, its app-server is the thread's one
|
|
72
|
+
* writer, so a standalone `codex resume` / `codex exec resume` is refused ("already has an active writer"):
|
|
73
|
+
* go through the daemon instead. When the daemon only lived for the return, nothing holds the thread and
|
|
74
|
+
* plain `codex resume` works.
|
|
75
|
+
*/
|
|
76
|
+
export function resumeHint(cwd: string, sessionId: string, managed: boolean, serverDir: string): string {
|
|
77
|
+
if (!managed) return `cd ${cwd} && codex resume ${sessionId}`;
|
|
78
|
+
const env = serverDir === defaultServerDir() ? "" : `PI_SERVER_DIR=${serverDir} `;
|
|
79
|
+
return `${env}pi-remote attach ${sessionId} --agent codex (or: ${env}pi-remote steer ${sessionId} --agent codex "<message>")`;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export async function returnCodexThread(options: ReturnCodexOptions): Promise<ReturnCodexResult> {
|
|
83
|
+
const summary = await resolveSession(options.host, options.ref);
|
|
84
|
+
const serverDir = options.serverDir ?? defaultServerDir();
|
|
85
|
+
const local = await localDaemon(serverDir, options.codex);
|
|
86
|
+
try {
|
|
87
|
+
// Default destination: the original workspace path, read from the tombstone left when the thread moved away.
|
|
88
|
+
let dest = options.toCwd ? resolve(options.toCwd) : undefined;
|
|
89
|
+
if (!dest) {
|
|
90
|
+
const tombstone = local.runtime.archivedRolloutPath(summary.sessionId) ?? local.runtime.rolloutPath(summary.sessionId);
|
|
91
|
+
if (tombstone) dest = readRolloutMeta(tombstone).cwd;
|
|
92
|
+
}
|
|
93
|
+
// Checked before anything is fenced: a busy destination must not cost the host its session.
|
|
94
|
+
if (dest && existsSync(dest) && readdirSync(dest).length > 0) {
|
|
95
|
+
throw new Error(`${dest} already exists and is not empty; pass --to-cwd <empty dir>`);
|
|
96
|
+
}
|
|
97
|
+
await preflightCodexProvider(options.host, local.client, summary.sessionId, options.rebindProvider);
|
|
98
|
+
options.onProgress?.("preflight passed");
|
|
99
|
+
const result = await moveSession(options.host, local.client, {
|
|
100
|
+
sessionId: summary.sessionId,
|
|
101
|
+
...(options.rebindProvider ? { rebindProvider: options.rebindProvider } : {}),
|
|
102
|
+
...(dest ? { toCwd: dest } : {}),
|
|
103
|
+
...(options.waitMs !== undefined ? { waitMs: options.waitMs } : {}),
|
|
104
|
+
...(options.onProgress ? { onProgress: options.onProgress } : {}),
|
|
105
|
+
});
|
|
106
|
+
return { ...result, resumeCommand: resumeHint(result.cwd, result.sessionId, local.managed, serverDir) };
|
|
107
|
+
} finally {
|
|
108
|
+
await local.stop();
|
|
109
|
+
}
|
|
110
|
+
}
|