@phren/cli 0.3.11 → 0.3.13
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/dist/bridge/account-usage.d.ts +124 -0
- package/dist/bridge/account-usage.js +258 -0
- package/dist/bridge/agent-hook-stores.d.ts +3 -0
- package/dist/bridge/agent-hook-stores.js +5 -0
- package/dist/bridge/agent-hooks.d.ts +162 -5
- package/dist/bridge/agent-hooks.js +682 -49
- package/dist/bridge/approval-summary.d.ts +16 -0
- package/dist/bridge/approval-summary.js +133 -0
- package/dist/bridge/authority-command.d.ts +20 -0
- package/dist/bridge/authority-command.js +120 -0
- package/dist/bridge/authority.d.ts +223 -0
- package/dist/bridge/authority.js +231 -0
- package/dist/bridge/claude-account-setup.d.ts +14 -0
- package/dist/bridge/claude-account-setup.js +69 -0
- package/dist/bridge/claude-accounts.d.ts +49 -0
- package/dist/bridge/claude-accounts.js +195 -0
- package/dist/bridge/code-routes.js +2 -2
- package/dist/bridge/codex-app-server.d.ts +144 -0
- package/dist/bridge/codex-app-server.js +319 -0
- package/dist/bridge/codex-auth-refresh.d.ts +33 -0
- package/dist/bridge/codex-auth-refresh.js +71 -0
- package/dist/bridge/codex-hook-trust.d.ts +27 -0
- package/dist/bridge/codex-hook-trust.js +237 -0
- package/dist/bridge/codex-question-reply.d.ts +16 -0
- package/dist/bridge/codex-question-reply.js +57 -0
- package/dist/bridge/codex-review-mode.d.ts +10 -0
- package/dist/bridge/codex-review-mode.js +74 -0
- package/dist/bridge/codex-servers.d.ts +217 -0
- package/dist/bridge/codex-servers.js +636 -0
- package/dist/bridge/command.js +97 -4
- package/dist/bridge/computer-identity.d.ts +75 -0
- package/dist/bridge/computer-identity.js +166 -0
- package/dist/bridge/conductor-group.d.ts +91 -8
- package/dist/bridge/conductor-group.js +105 -9
- package/dist/bridge/conductor-role.d.ts +94 -0
- package/dist/bridge/conductor-role.js +176 -0
- package/dist/bridge/conductor-sets.d.ts +20 -0
- package/dist/bridge/conductor-sets.js +59 -0
- package/dist/bridge/dispatch-command.d.ts +3 -0
- package/dist/bridge/dispatch-command.js +82 -12
- package/dist/bridge/dispatch-returns.d.ts +128 -19
- package/dist/bridge/dispatch-returns.js +371 -54
- package/dist/bridge/dispatch.d.ts +128 -3
- package/dist/bridge/dispatch.js +303 -42
- package/dist/bridge/fanouts.d.ts +7 -1
- package/dist/bridge/fanouts.js +39 -4
- package/dist/bridge/folder-trust.d.ts +56 -0
- package/dist/bridge/folder-trust.js +195 -0
- package/dist/bridge/grants.d.ts +22 -1
- package/dist/bridge/grants.js +57 -9
- package/dist/bridge/hand-off-queue.d.ts +74 -0
- package/dist/bridge/hand-off-queue.js +235 -0
- package/dist/bridge/hand-off.d.ts +30 -10
- package/dist/bridge/hand-off.js +79 -46
- package/dist/bridge/harness-status.d.ts +11 -0
- package/dist/bridge/harness-status.js +32 -0
- package/dist/bridge/harnesses.d.ts +39 -0
- package/dist/bridge/harnesses.js +65 -0
- package/dist/bridge/health.d.ts +2 -0
- package/dist/bridge/health.js +1 -1
- package/dist/bridge/herdr.d.ts +11 -2
- package/dist/bridge/herdr.js +98 -23
- package/dist/bridge/hook-fast.d.ts +4 -0
- package/dist/bridge/hook-fast.js +68 -0
- package/dist/bridge/install.d.ts +16 -1
- package/dist/bridge/install.js +102 -21
- package/dist/bridge/launch-brief.d.ts +96 -0
- package/dist/bridge/launch-brief.js +164 -0
- package/dist/bridge/model-switch.d.ts +3 -0
- package/dist/bridge/model-switch.js +17 -1
- package/dist/bridge/models.d.ts +8 -4
- package/dist/bridge/models.js +24 -8
- package/dist/bridge/mux-wire.d.ts +9 -0
- package/dist/bridge/mux-wire.js +19 -0
- package/dist/bridge/opencode-pane-server.d.ts +113 -0
- package/dist/bridge/opencode-pane-server.js +332 -0
- package/dist/bridge/opencode-panes.d.ts +111 -0
- package/dist/bridge/opencode-panes.js +295 -0
- package/dist/bridge/pane-accounts.d.ts +8 -0
- package/dist/bridge/pane-accounts.js +46 -0
- package/dist/bridge/pane-status.d.ts +12 -0
- package/dist/bridge/pane-status.js +50 -1
- package/dist/bridge/prompt-startup.d.ts +5 -0
- package/dist/bridge/prompt-startup.js +24 -0
- package/dist/bridge/protocol.d.ts +5 -0
- package/dist/bridge/protocol.js +4 -0
- package/dist/bridge/push.d.ts +11 -4
- package/dist/bridge/push.js +27 -4
- package/dist/bridge/questions.d.ts +37 -2
- package/dist/bridge/questions.js +158 -15
- package/dist/bridge/resources.d.ts +9 -3
- package/dist/bridge/resources.js +24 -8
- package/dist/bridge/schedule-format.d.ts +2 -0
- package/dist/bridge/schedule-format.js +3 -0
- package/dist/bridge/schedule-launch.d.ts +2 -1
- package/dist/bridge/schedule-launch.js +27 -53
- package/dist/bridge/schedule-watch.d.ts +24 -1
- package/dist/bridge/schedule-watch.js +89 -2
- package/dist/bridge/server-launch.d.ts +22 -5
- package/dist/bridge/server-launch.js +238 -32
- package/dist/bridge/server-overview.d.ts +10 -3
- package/dist/bridge/server-overview.js +32 -15
- package/dist/bridge/server-pane-routes.d.ts +3 -0
- package/dist/bridge/server-pane-routes.js +150 -18
- package/dist/bridge/server-routes.d.ts +11 -0
- package/dist/bridge/server-routes.js +214 -36
- package/dist/bridge/server-stream.d.ts +2 -0
- package/dist/bridge/server-stream.js +22 -8
- package/dist/bridge/server.d.ts +6 -1
- package/dist/bridge/server.js +58 -13
- package/dist/bridge/session-activity.d.ts +93 -0
- package/dist/bridge/session-activity.js +139 -0
- package/dist/bridge/session-rename.d.ts +48 -0
- package/dist/bridge/session-rename.js +190 -0
- package/dist/bridge/session-servers.js +2 -2
- package/dist/bridge/settings-switch.d.ts +60 -0
- package/dist/bridge/settings-switch.js +287 -0
- package/dist/bridge/speech-voice.d.ts +55 -0
- package/dist/bridge/speech-voice.js +132 -0
- package/dist/bridge/speech.d.ts +70 -11
- package/dist/bridge/speech.js +169 -41
- package/dist/bridge/stalls.d.ts +22 -0
- package/dist/bridge/stalls.js +57 -0
- package/dist/bridge/sudo.d.ts +209 -0
- package/dist/bridge/sudo.js +501 -0
- package/dist/bridge/terminal-herdr.js +9 -3
- package/dist/bridge/terminal-tmux.d.ts +15 -3
- package/dist/bridge/terminal-tmux.js +103 -13
- package/dist/bridge/terminal.d.ts +27 -4
- package/dist/bridge/terminal.js +8 -1
- package/dist/bridge/transcript-claude.d.ts +4 -0
- package/dist/bridge/transcript-claude.js +186 -16
- package/dist/bridge/transcript-codex.d.ts +0 -2
- package/dist/bridge/transcript-codex.js +29 -4
- package/dist/bridge/transcript-preview.d.ts +1 -0
- package/dist/bridge/transcript-preview.js +24 -4
- package/dist/bridge/transcripts.d.ts +15 -2
- package/dist/bridge/transcripts.js +47 -16
- package/dist/bridge/turn-records.d.ts +85 -0
- package/dist/bridge/turn-records.js +143 -0
- package/dist/bridge/uploads.d.ts +3 -0
- package/dist/bridge/uploads.js +14 -0
- package/dist/bridge/usage.d.ts +56 -10
- package/dist/bridge/usage.js +190 -45
- package/dist/bridge-hook.mjs +27975 -20636
- package/dist/cli/claude-unmanaged.d.ts +12 -0
- package/dist/cli/claude-unmanaged.js +105 -0
- package/dist/cli/schedules.js +2 -1
- package/dist/cli/session-start.js +10 -1
- package/dist/cli/session-stop.js +9 -1
- package/dist/cli-registry.js +31 -6
- package/dist/data/task-receipts.d.ts +19 -0
- package/dist/data/task-receipts.js +68 -0
- package/dist/data/tasks.js +4 -1
- package/dist/generated/memory-ui-graph.browser.js +63 -63
- package/dist/graph-core/model.js +24 -3
- package/dist/graph-core/types.d.ts +4 -1
- package/dist/graph-core/types.js +1 -0
- package/dist/init/init-preset.js +7 -3
- package/dist/init/init-uninstall.js +2 -11
- package/dist/init/teardown.d.ts +3 -0
- package/dist/init/teardown.js +47 -0
- package/dist/link/context.js +21 -9
- package/dist/mcp/plugin-mode.js +1 -1
- package/dist/memory-ui-graph.runtime.js +63 -63
- package/dist/modules/code-package.d.ts +1 -0
- package/dist/modules/code-package.js +36 -7
- package/dist/modules/registry.js +17 -16
- package/dist/profile-store.d.ts +6 -0
- package/dist/profile-store.js +25 -1
- package/dist/shell/graph/glyphs.js +4 -0
- package/dist/shell/graph/graph-view.js +2 -0
- package/dist/status.js +7 -1
- package/dist/sync/task-claim.js +3 -2
- package/dist/task/lifecycle.js +25 -4
- package/dist/test-global-setup.js +5 -0
- package/dist/tools/dispatch.js +52 -4
- package/dist/tools/tasks.js +10 -1
- package/package.json +1 -1
- package/plugins/opencode/phren-transcript.js +87 -4
- package/starter/global/AGENTS.md +4 -0
- package/starter/global/skills/conductor/SKILL.md +51 -4
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { type ChildProcess } from "node:child_process";
|
|
2
|
+
import { type Json } from "./protocol.js";
|
|
3
|
+
/** JSON-RPC ids are numbers for our own requests and either numbers or strings
|
|
4
|
+
* for server requests (an MCP elicitation uses the elicitation's own id). */
|
|
5
|
+
export type AppServerRequestId = number | string;
|
|
6
|
+
/** A server request this client has not answered yet. */
|
|
7
|
+
export interface PendingServerRequest {
|
|
8
|
+
requestId: AppServerRequestId;
|
|
9
|
+
method: string;
|
|
10
|
+
params: Json;
|
|
11
|
+
threadId?: string;
|
|
12
|
+
}
|
|
13
|
+
export type AppServerEvent = {
|
|
14
|
+
kind: "notification";
|
|
15
|
+
method: string;
|
|
16
|
+
params: Json;
|
|
17
|
+
} | {
|
|
18
|
+
kind: "request";
|
|
19
|
+
requestId: AppServerRequestId;
|
|
20
|
+
method: string;
|
|
21
|
+
params: Json;
|
|
22
|
+
threadId?: string;
|
|
23
|
+
} | {
|
|
24
|
+
kind: "resolved";
|
|
25
|
+
requestId: AppServerRequestId;
|
|
26
|
+
threadId?: string;
|
|
27
|
+
};
|
|
28
|
+
export type AppServerListener = (event: AppServerEvent) => void;
|
|
29
|
+
/** A JSON-RPC error reply, carrying the server's `code` beside the message. */
|
|
30
|
+
export declare class AppServerRpcError extends Error {
|
|
31
|
+
readonly code: number;
|
|
32
|
+
readonly method: string;
|
|
33
|
+
constructor(code: number, message: string, method: string);
|
|
34
|
+
}
|
|
35
|
+
/** One user input of a `turn/start`. Shape from the spike transcripts:
|
|
36
|
+
* `{"type":"text","text":"…","text_elements":[]}`. */
|
|
37
|
+
export interface AppServerTurnInput {
|
|
38
|
+
type: string;
|
|
39
|
+
text?: string;
|
|
40
|
+
[key: string]: unknown;
|
|
41
|
+
}
|
|
42
|
+
export interface TurnStartParams {
|
|
43
|
+
threadId: string;
|
|
44
|
+
input: AppServerTurnInput[];
|
|
45
|
+
model?: string;
|
|
46
|
+
effort?: string;
|
|
47
|
+
approvalPolicy?: string;
|
|
48
|
+
sandboxPolicy?: Json;
|
|
49
|
+
approvalsReviewer?: string;
|
|
50
|
+
/** EXPERIMENTAL: plan or default mode. The settings are required and win
|
|
51
|
+
* over `model` and `effort`. */
|
|
52
|
+
collaborationMode?: {
|
|
53
|
+
mode: string;
|
|
54
|
+
settings: {
|
|
55
|
+
model: string;
|
|
56
|
+
reasoning_effort: string | null;
|
|
57
|
+
developer_instructions: string | null;
|
|
58
|
+
};
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
export interface AppServerHandle {
|
|
62
|
+
child: ChildProcess;
|
|
63
|
+
socketPath: string;
|
|
64
|
+
stop(): Promise<void>;
|
|
65
|
+
}
|
|
66
|
+
export interface AppServerClient {
|
|
67
|
+
/** Server requests awaiting an answer, keyed by request id. */
|
|
68
|
+
readonly pending: ReadonlyMap<AppServerRequestId, PendingServerRequest>;
|
|
69
|
+
request(method: string, params?: unknown, timeoutMs?: number): Promise<unknown>;
|
|
70
|
+
/** `thread/start` (T3 `buildThreadStartParams`: cwd, approvalPolicy, sandbox,
|
|
71
|
+
* approvalsReviewer, model, serviceTier). */
|
|
72
|
+
threadStart(params: Json): Promise<Json>;
|
|
73
|
+
/** `thread/resume`, turning the spike's `excludeTurns: true` on by default
|
|
74
|
+
* (T3 `openCodexThread`; transcript-turn.jsonl id 3). */
|
|
75
|
+
threadResume(params: Json & {
|
|
76
|
+
threadId: string;
|
|
77
|
+
}): Promise<Json>;
|
|
78
|
+
/** `thread/loaded/list` → the thread ids (transcript-observe.jsonl id 2). */
|
|
79
|
+
threadLoadedList(): Promise<string[]>;
|
|
80
|
+
/** `turn/start` → the queued turn's id (transcript-turn.jsonl id 4). */
|
|
81
|
+
turnStart(params: TurnStartParams): Promise<{
|
|
82
|
+
turnId: string;
|
|
83
|
+
}>;
|
|
84
|
+
/** `turn/steer`: input for the running turn `expectedTurnId`, as the TUI
|
|
85
|
+
* sends a message typed mid-turn or the answer to an async question. */
|
|
86
|
+
turnSteer(params: {
|
|
87
|
+
threadId: string;
|
|
88
|
+
expectedTurnId: string;
|
|
89
|
+
input: AppServerTurnInput[];
|
|
90
|
+
}): Promise<{
|
|
91
|
+
turnId: string;
|
|
92
|
+
}>;
|
|
93
|
+
/** `turn/interrupt` (transcript-interrupt.jsonl id 5). */
|
|
94
|
+
turnInterrupt(params: {
|
|
95
|
+
threadId: string;
|
|
96
|
+
turnId: string;
|
|
97
|
+
}): Promise<unknown>;
|
|
98
|
+
/** Decline every pending server request of the thread, then interrupt, so a
|
|
99
|
+
* parked approval cannot block the turn's teardown. */
|
|
100
|
+
interruptTurn(threadId: string, turnId: string): Promise<void>;
|
|
101
|
+
respond(requestId: AppServerRequestId, result: unknown): void;
|
|
102
|
+
respondError(requestId: AppServerRequestId, code: number, message: string): void;
|
|
103
|
+
on(listener: AppServerListener): () => void;
|
|
104
|
+
/** Called once when the connection ends, from either side. */
|
|
105
|
+
onClose(listener: () => void): () => void;
|
|
106
|
+
close(): void;
|
|
107
|
+
}
|
|
108
|
+
export interface SpawnAppServerOptions {
|
|
109
|
+
codexBin?: string;
|
|
110
|
+
socketPath: string;
|
|
111
|
+
codexHome?: string;
|
|
112
|
+
env?: NodeJS.ProcessEnv;
|
|
113
|
+
/** Use `env` as the whole environment instead of layering it over the
|
|
114
|
+
* Hook's, so variables of the Hook's own terminal cannot leak in. */
|
|
115
|
+
replaceEnv?: boolean;
|
|
116
|
+
cwd: string;
|
|
117
|
+
/** Let the server outlive the Hook (a Hook update must not end a worker the
|
|
118
|
+
* owner is watching in a pane). The caller records the pid to stop it later. */
|
|
119
|
+
detached?: boolean;
|
|
120
|
+
/** Where the server's stderr goes for its whole life. A detached server
|
|
121
|
+
* outlives the Hook's end of a pipe, and a write to a closed pipe could
|
|
122
|
+
* end it, so a long-lived server logs to a file instead. */
|
|
123
|
+
logFile?: string;
|
|
124
|
+
/** Config overrides for every thread the server runs, as `-c key=value`
|
|
125
|
+
* (the value is TOML). */
|
|
126
|
+
config?: string[];
|
|
127
|
+
}
|
|
128
|
+
/** Start one `codex app-server --listen unix://<socketPath>` and wait until its
|
|
129
|
+
* socket accepts WebSocket connections. The server is the worker's; `stop()`
|
|
130
|
+
* is the only owner. Extra `env` is layered over the current process's. */
|
|
131
|
+
export declare function spawnAppServer(options: SpawnAppServerOptions): Promise<AppServerHandle>;
|
|
132
|
+
export interface ConnectAppServerOptions {
|
|
133
|
+
clientName: string;
|
|
134
|
+
clientTitle?: string;
|
|
135
|
+
clientVersion?: string;
|
|
136
|
+
timeoutMs?: number;
|
|
137
|
+
}
|
|
138
|
+
/** Connect and complete `initialize` + `initialized` (spike client.mjs,
|
|
139
|
+
* transcript-turn.jsonl ids 1 and the notification). */
|
|
140
|
+
export declare function connectAppServer(socketPath: string, options: ConnectAppServerOptions): Promise<AppServerClient>;
|
|
141
|
+
/** The shape that declines one server request so the turn can be torn down.
|
|
142
|
+
* T3 `settlePendingApprovals("cancel")` / `settlePendingUserInputs({})` and the
|
|
143
|
+
* per-method responses in its `handleServerRequest` blocks. */
|
|
144
|
+
export declare function declineResult(method: string): Json;
|
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { mkdir, open, readFile, rm, stat } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { WebSocket } from "ws";
|
|
5
|
+
import { codexExecutable } from "./codex-binary.js";
|
|
6
|
+
import { object } from "./protocol.js";
|
|
7
|
+
/** A Phren-owned `codex app-server` and its WebSocket-on-UDS client. The
|
|
8
|
+
* visible pane is a second client (`codex resume <threadId> --remote
|
|
9
|
+
* unix://<sock>`); turns and approvals from either side reach both. Protocol
|
|
10
|
+
* and transport follow `.scratch/ref/codex-daemon-spike.md`. */
|
|
11
|
+
const STARTUP_TIMEOUT_MS = 15_000;
|
|
12
|
+
const STARTUP_POLL_MS = 100;
|
|
13
|
+
const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
|
|
14
|
+
const KILL_GRACE_MS = 2_000;
|
|
15
|
+
/** A JSON-RPC error reply, carrying the server's `code` beside the message. */
|
|
16
|
+
export class AppServerRpcError extends Error {
|
|
17
|
+
code;
|
|
18
|
+
method;
|
|
19
|
+
constructor(code, message, method) {
|
|
20
|
+
super(message);
|
|
21
|
+
this.code = code;
|
|
22
|
+
this.method = method;
|
|
23
|
+
this.name = "AppServerRpcError";
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/** Start one `codex app-server --listen unix://<socketPath>` and wait until its
|
|
27
|
+
* socket accepts WebSocket connections. The server is the worker's; `stop()`
|
|
28
|
+
* is the only owner. Extra `env` is layered over the current process's. */
|
|
29
|
+
export async function spawnAppServer(options) {
|
|
30
|
+
const env = { ...(options.replaceEnv ? {} : process.env), ...(options.env ?? {}), ...(options.codexHome ? { CODEX_HOME: options.codexHome } : {}) };
|
|
31
|
+
// The merged environment's PATH, so a caller's partial `env` still finds codex.
|
|
32
|
+
const codexBin = options.codexBin ?? codexExecutable(env);
|
|
33
|
+
await mkdir(path.dirname(options.socketPath), { recursive: true, mode: 0o700 });
|
|
34
|
+
// A socket file left by a dead server would pass the stat below and block the bind.
|
|
35
|
+
await rm(options.socketPath, { force: true });
|
|
36
|
+
const log = options.logFile ? await open(options.logFile, "a", 0o600) : undefined;
|
|
37
|
+
let child;
|
|
38
|
+
try {
|
|
39
|
+
child = spawn(codexBin, ["app-server", ...(options.config ?? []).flatMap(value => ["-c", value]), "--listen", `unix://${options.socketPath}`], {
|
|
40
|
+
cwd: options.cwd,
|
|
41
|
+
env,
|
|
42
|
+
detached: options.detached === true,
|
|
43
|
+
// No stdin: the app-server is reached over its socket, never over stdio.
|
|
44
|
+
// stderr is kept (bounded) so a failed start can say why.
|
|
45
|
+
stdio: ["ignore", "ignore", log ? log.fd : "pipe"],
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
finally {
|
|
49
|
+
await log?.close();
|
|
50
|
+
}
|
|
51
|
+
// A missing binary is an `error` event, not an exit: without a listener
|
|
52
|
+
// it would take the Hook down.
|
|
53
|
+
let failure;
|
|
54
|
+
child.once("error", error => { failure = error; });
|
|
55
|
+
let stderr = "";
|
|
56
|
+
child.stderr?.on("data", (chunk) => { stderr = (stderr + chunk.toString("utf8")).slice(-2_000); });
|
|
57
|
+
const why = async () => {
|
|
58
|
+
const text = options.logFile ? (await readFile(options.logFile, "utf8").catch(() => "")).slice(-2_000) : stderr;
|
|
59
|
+
return text.trim() ? `: ${text.trim().split("\n").slice(-3).join(" | ")}` : "";
|
|
60
|
+
};
|
|
61
|
+
const deadline = Date.now() + STARTUP_TIMEOUT_MS;
|
|
62
|
+
while (true) {
|
|
63
|
+
if (failure)
|
|
64
|
+
throw new Error(`codex app-server could not start: ${failure.message}`);
|
|
65
|
+
if (child.exitCode !== null || child.signalCode !== null) {
|
|
66
|
+
throw new Error(`codex app-server exited before ${options.socketPath} was ready (${child.exitCode ?? child.signalCode})${await why()}`);
|
|
67
|
+
}
|
|
68
|
+
if (await socketAccepts(options.socketPath))
|
|
69
|
+
break;
|
|
70
|
+
if (Date.now() > deadline) {
|
|
71
|
+
child.kill("SIGKILL");
|
|
72
|
+
throw new Error(`Timed out waiting for codex app-server at ${options.socketPath}${await why()}`);
|
|
73
|
+
}
|
|
74
|
+
await delay(STARTUP_POLL_MS);
|
|
75
|
+
}
|
|
76
|
+
// Once ready, stop reading stderr so a detached server doesn't hold the Hook open.
|
|
77
|
+
child.stderr?.destroy();
|
|
78
|
+
if (options.detached)
|
|
79
|
+
child.unref();
|
|
80
|
+
return { child, socketPath: options.socketPath, stop: () => stopChild(child) };
|
|
81
|
+
}
|
|
82
|
+
function stopChild(child) {
|
|
83
|
+
return new Promise(resolve => {
|
|
84
|
+
if (child.exitCode !== null || child.signalCode !== null) {
|
|
85
|
+
resolve();
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
// A SIGKILL that leaves no exit event (the process died in the window
|
|
89
|
+
// above) still resolves, so stop() cannot hang on a dead server.
|
|
90
|
+
const kill = setTimeout(() => { if (child.exitCode === null && child.signalCode === null)
|
|
91
|
+
child.kill("SIGKILL"); resolve(); }, KILL_GRACE_MS);
|
|
92
|
+
kill.unref();
|
|
93
|
+
child.once("exit", () => { clearTimeout(kill); resolve(); });
|
|
94
|
+
child.kill("SIGTERM");
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
async function socketAccepts(socketPath) {
|
|
98
|
+
try {
|
|
99
|
+
await stat(socketPath);
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
return false;
|
|
103
|
+
}
|
|
104
|
+
return new Promise(resolve => {
|
|
105
|
+
const ws = new WebSocket(socketUrl(socketPath), { perMessageDeflate: false });
|
|
106
|
+
let settled = false;
|
|
107
|
+
const finish = (ok) => { if (settled)
|
|
108
|
+
return; settled = true; ws.close(); resolve(ok); };
|
|
109
|
+
ws.once("open", () => finish(true));
|
|
110
|
+
ws.once("error", () => finish(false));
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
/** `perMessageDeflate: false` is required: offering compression makes the
|
|
114
|
+
* server reject the handshake with "socket hang up" (spike, Transport). */
|
|
115
|
+
function socketUrl(socketPath) { return `ws+unix://${socketPath}:/`; }
|
|
116
|
+
/** Connect and complete `initialize` + `initialized` (spike client.mjs,
|
|
117
|
+
* transcript-turn.jsonl ids 1 and the notification). */
|
|
118
|
+
export async function connectAppServer(socketPath, options) {
|
|
119
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
|
120
|
+
const ws = new WebSocket(socketUrl(socketPath), { perMessageDeflate: false });
|
|
121
|
+
await opened(ws, timeoutMs);
|
|
122
|
+
const client = new AppServerConnection(ws);
|
|
123
|
+
try {
|
|
124
|
+
await client.request("initialize", {
|
|
125
|
+
clientInfo: { name: options.clientName, title: options.clientTitle ?? options.clientName, version: options.clientVersion ?? "0.0.1" },
|
|
126
|
+
capabilities: { experimentalApi: true },
|
|
127
|
+
}, timeoutMs);
|
|
128
|
+
}
|
|
129
|
+
catch (error) {
|
|
130
|
+
client.close();
|
|
131
|
+
throw error;
|
|
132
|
+
}
|
|
133
|
+
client.notify("initialized");
|
|
134
|
+
return client;
|
|
135
|
+
}
|
|
136
|
+
function opened(ws, timeoutMs) {
|
|
137
|
+
return new Promise((resolve, reject) => {
|
|
138
|
+
const timer = setTimeout(() => { cleanup(); reject(new Error("Timed out connecting to codex app-server")); }, timeoutMs);
|
|
139
|
+
const onOpen = () => { cleanup(); resolve(); };
|
|
140
|
+
const onError = (error) => { cleanup(); reject(error); };
|
|
141
|
+
const cleanup = () => { clearTimeout(timer); ws.off("open", onOpen); ws.off("error", onError); };
|
|
142
|
+
ws.once("open", onOpen);
|
|
143
|
+
ws.once("error", onError);
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }
|
|
147
|
+
class AppServerConnection {
|
|
148
|
+
ws;
|
|
149
|
+
pending = new Map();
|
|
150
|
+
nextId = 1;
|
|
151
|
+
waiters = new Map();
|
|
152
|
+
listeners = new Set();
|
|
153
|
+
closeListeners = new Set();
|
|
154
|
+
constructor(ws) {
|
|
155
|
+
this.ws = ws;
|
|
156
|
+
ws.on("message", data => this.handle(data));
|
|
157
|
+
ws.on("close", () => {
|
|
158
|
+
this.failAll(new Error("codex app-server connection closed"));
|
|
159
|
+
for (const listener of [...this.closeListeners])
|
|
160
|
+
listener();
|
|
161
|
+
this.closeListeners.clear();
|
|
162
|
+
});
|
|
163
|
+
ws.on("error", () => this.failAll(new Error("codex app-server connection error")));
|
|
164
|
+
}
|
|
165
|
+
request(method, params, timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS) {
|
|
166
|
+
const id = this.nextId++;
|
|
167
|
+
return new Promise((resolve, reject) => {
|
|
168
|
+
const timer = setTimeout(() => {
|
|
169
|
+
this.waiters.delete(id);
|
|
170
|
+
reject(new Error(`Timed out waiting for codex app-server ${method}`));
|
|
171
|
+
}, timeoutMs);
|
|
172
|
+
this.waiters.set(id, { method, resolve, reject, timer });
|
|
173
|
+
this.write({ id, method, ...(params === undefined ? {} : { params }) });
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
notify(method, params) {
|
|
177
|
+
this.write({ method, ...(params === undefined ? {} : { params }) });
|
|
178
|
+
}
|
|
179
|
+
async threadStart(params) { return object(await this.request("thread/start", params)); }
|
|
180
|
+
async threadResume(params) {
|
|
181
|
+
return object(await this.request("thread/resume", { excludeTurns: true, ...params }));
|
|
182
|
+
}
|
|
183
|
+
async threadLoadedList() {
|
|
184
|
+
const result = object(await this.request("thread/loaded/list", {}));
|
|
185
|
+
return Array.isArray(result.data) ? result.data.filter((id) => typeof id === "string") : [];
|
|
186
|
+
}
|
|
187
|
+
async turnStart(params) {
|
|
188
|
+
const result = object(await this.request("turn/start", params));
|
|
189
|
+
const turnId = object(result.turn).id;
|
|
190
|
+
if (typeof turnId !== "string")
|
|
191
|
+
throw new Error("codex app-server turn/start returned no turn id");
|
|
192
|
+
return { turnId };
|
|
193
|
+
}
|
|
194
|
+
async turnSteer(params) {
|
|
195
|
+
const turnId = object(await this.request("turn/steer", params)).turnId;
|
|
196
|
+
if (typeof turnId !== "string")
|
|
197
|
+
throw new Error("codex app-server turn/steer returned no turn id");
|
|
198
|
+
return { turnId };
|
|
199
|
+
}
|
|
200
|
+
turnInterrupt(params) {
|
|
201
|
+
return this.request("turn/interrupt", { threadId: params.threadId, turnId: params.turnId });
|
|
202
|
+
}
|
|
203
|
+
async interruptTurn(threadId, turnId) {
|
|
204
|
+
for (const request of [...this.pending.values()]) {
|
|
205
|
+
// Elicitations may carry no threadId; they still belong to this client
|
|
206
|
+
// and would keep blocking the turn, so settle them too.
|
|
207
|
+
if (request.threadId !== undefined && request.threadId !== threadId)
|
|
208
|
+
continue;
|
|
209
|
+
this.respond(request.requestId, declineResult(request.method));
|
|
210
|
+
}
|
|
211
|
+
await this.turnInterrupt({ threadId, turnId });
|
|
212
|
+
}
|
|
213
|
+
respond(requestId, result) {
|
|
214
|
+
if (!this.pending.delete(requestId))
|
|
215
|
+
return;
|
|
216
|
+
this.write({ id: requestId, result });
|
|
217
|
+
}
|
|
218
|
+
respondError(requestId, code, message) {
|
|
219
|
+
if (!this.pending.delete(requestId))
|
|
220
|
+
return;
|
|
221
|
+
this.write({ id: requestId, error: { code, message } });
|
|
222
|
+
}
|
|
223
|
+
on(listener) {
|
|
224
|
+
this.listeners.add(listener);
|
|
225
|
+
return () => { this.listeners.delete(listener); };
|
|
226
|
+
}
|
|
227
|
+
onClose(listener) {
|
|
228
|
+
this.closeListeners.add(listener);
|
|
229
|
+
return () => { this.closeListeners.delete(listener); };
|
|
230
|
+
}
|
|
231
|
+
close() {
|
|
232
|
+
this.failAll(new Error("codex app-server client closed"));
|
|
233
|
+
this.listeners.clear();
|
|
234
|
+
try {
|
|
235
|
+
this.ws.close();
|
|
236
|
+
}
|
|
237
|
+
catch { /* already closed */ }
|
|
238
|
+
}
|
|
239
|
+
write(message) {
|
|
240
|
+
if (this.ws.readyState !== WebSocket.OPEN)
|
|
241
|
+
throw new Error("codex app-server connection is not open");
|
|
242
|
+
this.ws.send(JSON.stringify(message));
|
|
243
|
+
}
|
|
244
|
+
handle(raw) {
|
|
245
|
+
let message;
|
|
246
|
+
try {
|
|
247
|
+
message = object(JSON.parse(String(raw)));
|
|
248
|
+
}
|
|
249
|
+
catch {
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
const id = message.id;
|
|
253
|
+
const method = message.method;
|
|
254
|
+
if (typeof method === "string" && id !== undefined) {
|
|
255
|
+
const params = object(message.params);
|
|
256
|
+
const request = { requestId: id, method, params,
|
|
257
|
+
...(typeof params.threadId === "string" ? { threadId: params.threadId } : {}) };
|
|
258
|
+
this.pending.set(request.requestId, request);
|
|
259
|
+
this.emit({ kind: "request", ...request });
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
if (typeof method === "string") {
|
|
263
|
+
const params = object(message.params);
|
|
264
|
+
if (method === "serverRequest/resolved") {
|
|
265
|
+
const requestId = params.requestId;
|
|
266
|
+
this.pending.delete(requestId);
|
|
267
|
+
this.emit({ kind: "resolved", requestId, ...(typeof params.threadId === "string" ? { threadId: params.threadId } : {}) });
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
this.emit({ kind: "notification", method, params });
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
if (id === undefined)
|
|
274
|
+
return;
|
|
275
|
+
const waiter = this.waiters.get(id);
|
|
276
|
+
if (!waiter)
|
|
277
|
+
return;
|
|
278
|
+
this.waiters.delete(id);
|
|
279
|
+
clearTimeout(waiter.timer);
|
|
280
|
+
const error = object(message.error);
|
|
281
|
+
if (message.error !== undefined) {
|
|
282
|
+
waiter.reject(new AppServerRpcError(Number(error.code), String(error.message ?? `codex app-server ${waiter.method} failed`), waiter.method));
|
|
283
|
+
}
|
|
284
|
+
else {
|
|
285
|
+
waiter.resolve(message.result);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
failAll(error) {
|
|
289
|
+
for (const waiter of this.waiters.values()) {
|
|
290
|
+
clearTimeout(waiter.timer);
|
|
291
|
+
waiter.reject(error);
|
|
292
|
+
}
|
|
293
|
+
this.waiters.clear();
|
|
294
|
+
this.pending.clear();
|
|
295
|
+
}
|
|
296
|
+
emit(event) {
|
|
297
|
+
for (const listener of this.listeners)
|
|
298
|
+
listener(event);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
/** The shape that declines one server request so the turn can be torn down.
|
|
302
|
+
* T3 `settlePendingApprovals("cancel")` / `settlePendingUserInputs({})` and the
|
|
303
|
+
* per-method responses in its `handleServerRequest` blocks. */
|
|
304
|
+
export function declineResult(method) {
|
|
305
|
+
switch (method) {
|
|
306
|
+
case "item/commandExecution/requestApproval":
|
|
307
|
+
case "item/fileChange/requestApproval":
|
|
308
|
+
return { decision: "cancel" };
|
|
309
|
+
case "item/permissions/requestApproval":
|
|
310
|
+
// `scope` is required (PermissionsRequestApprovalResponse, 0.155.1).
|
|
311
|
+
return { permissions: {}, scope: "turn" };
|
|
312
|
+
case "item/tool/requestUserInput":
|
|
313
|
+
return { answers: {} };
|
|
314
|
+
case "mcpServer/elicitation/request":
|
|
315
|
+
return { action: "cancel" };
|
|
316
|
+
default:
|
|
317
|
+
return {};
|
|
318
|
+
}
|
|
319
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Every Codex process on a computer shares one ChatGPT sign-in in
|
|
3
|
+
* `$CODEX_HOME/auth.json`, and each refreshes it when `last_refresh` grows
|
|
4
|
+
* old (Codex's own threshold is 8 days). The refresh token rotates on every
|
|
5
|
+
* use, so processes that reach the threshold together (a batch of workers,
|
|
6
|
+
* one app-server per pane) race: one wins, the rest spend a token that is
|
|
7
|
+
* already used and fail ("refresh token was already used"). Codex re-reads
|
|
8
|
+
* the file before refreshing and skips when another process already did.
|
|
9
|
+
* So the Hook refreshes first, once, before any process reaches the
|
|
10
|
+
* threshold, and the others take that skip path.
|
|
11
|
+
*/
|
|
12
|
+
/** Refresh when the sign-in is this old: well before Codex's 8 days. */
|
|
13
|
+
export declare const REFRESH_AFTER_MS: number;
|
|
14
|
+
/** The sign-in's last refresh, or undefined when auth.json holds no ChatGPT
|
|
15
|
+
* sign-in (an API key, no file) and there is nothing to refresh. */
|
|
16
|
+
export declare function lastCodexRefresh(file?: string): Promise<number | undefined>;
|
|
17
|
+
export declare function codexAuthRefreshEnabled(env?: NodeJS.ProcessEnv): boolean;
|
|
18
|
+
export interface CodexAuthRefresher {
|
|
19
|
+
/** One proactive refresh through Codex's own flow (`account/read` with
|
|
20
|
+
* `refreshToken`). */
|
|
21
|
+
refreshAuth(): Promise<void>;
|
|
22
|
+
}
|
|
23
|
+
/** Checks the sign-in's age and refreshes it once when it is due. One check
|
|
24
|
+
* runs at a time; a failed refresh is logged and tried again next tick. */
|
|
25
|
+
export declare class CodexAuthKeeper {
|
|
26
|
+
private readonly refresher;
|
|
27
|
+
private readonly file?;
|
|
28
|
+
private readonly now;
|
|
29
|
+
private running?;
|
|
30
|
+
constructor(refresher: CodexAuthRefresher, file?: string | undefined, now?: () => number);
|
|
31
|
+
tick(): Promise<boolean>;
|
|
32
|
+
private check;
|
|
33
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { codexHome } from "../home-paths.js";
|
|
4
|
+
import { logger } from "../logger.js";
|
|
5
|
+
import { object } from "./protocol.js";
|
|
6
|
+
/**
|
|
7
|
+
* Every Codex process on a computer shares one ChatGPT sign-in in
|
|
8
|
+
* `$CODEX_HOME/auth.json`, and each refreshes it when `last_refresh` grows
|
|
9
|
+
* old (Codex's own threshold is 8 days). The refresh token rotates on every
|
|
10
|
+
* use, so processes that reach the threshold together (a batch of workers,
|
|
11
|
+
* one app-server per pane) race: one wins, the rest spend a token that is
|
|
12
|
+
* already used and fail ("refresh token was already used"). Codex re-reads
|
|
13
|
+
* the file before refreshing and skips when another process already did.
|
|
14
|
+
* So the Hook refreshes first, once, before any process reaches the
|
|
15
|
+
* threshold, and the others take that skip path.
|
|
16
|
+
*/
|
|
17
|
+
/** Refresh when the sign-in is this old: well before Codex's 8 days. */
|
|
18
|
+
export const REFRESH_AFTER_MS = 6 * 86_400_000;
|
|
19
|
+
/** The sign-in's last refresh, or undefined when auth.json holds no ChatGPT
|
|
20
|
+
* sign-in (an API key, no file) and there is nothing to refresh. */
|
|
21
|
+
export async function lastCodexRefresh(file = path.join(codexHome(), "auth.json")) {
|
|
22
|
+
try {
|
|
23
|
+
const auth = object(JSON.parse(await readFile(file, "utf8")));
|
|
24
|
+
if (!object(auth.tokens).refresh_token)
|
|
25
|
+
return undefined;
|
|
26
|
+
const at = Date.parse(String(auth.last_refresh ?? ""));
|
|
27
|
+
return Number.isFinite(at) ? at : 0;
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
return undefined;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
export function codexAuthRefreshEnabled(env = process.env) {
|
|
34
|
+
return !/^(?:0|off|false|no)$/i.test(env.PHREN_CODEX_AUTH_REFRESH ?? "");
|
|
35
|
+
}
|
|
36
|
+
/** Checks the sign-in's age and refreshes it once when it is due. One check
|
|
37
|
+
* runs at a time; a failed refresh is logged and tried again next tick. */
|
|
38
|
+
export class CodexAuthKeeper {
|
|
39
|
+
refresher;
|
|
40
|
+
file;
|
|
41
|
+
now;
|
|
42
|
+
running;
|
|
43
|
+
constructor(refresher, file, now = () => Date.now()) {
|
|
44
|
+
this.refresher = refresher;
|
|
45
|
+
this.file = file;
|
|
46
|
+
this.now = now;
|
|
47
|
+
}
|
|
48
|
+
tick() {
|
|
49
|
+
this.running ??= this.check().finally(() => { this.running = undefined; });
|
|
50
|
+
return this.running;
|
|
51
|
+
}
|
|
52
|
+
async check() {
|
|
53
|
+
const before = await lastCodexRefresh(this.file);
|
|
54
|
+
if (before === undefined || this.now() - before < REFRESH_AFTER_MS)
|
|
55
|
+
return false;
|
|
56
|
+
try {
|
|
57
|
+
await this.refresher.refreshAuth();
|
|
58
|
+
}
|
|
59
|
+
catch (error) {
|
|
60
|
+
logger.warn("codex-auth", `Could not refresh the Codex sign-in ahead of its workers: ${error instanceof Error ? error.message : String(error)}`);
|
|
61
|
+
return false;
|
|
62
|
+
}
|
|
63
|
+
const after = await lastCodexRefresh(this.file);
|
|
64
|
+
const refreshed = after !== undefined && after > before;
|
|
65
|
+
if (refreshed)
|
|
66
|
+
logger.info("codex-auth", "Refreshed the Codex sign-in ahead of its workers.");
|
|
67
|
+
else
|
|
68
|
+
logger.warn("codex-auth", "Codex accepted the refresh request, but auth.json still shows the old sign-in.");
|
|
69
|
+
return refreshed;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/** `SessionStart` to `session_start`, the event name in Codex's trust keys. */
|
|
2
|
+
export declare function codexEventName(event: string): string;
|
|
3
|
+
/**
|
|
4
|
+
* Codex's `hook_hash` for one handler in one group (codex-rs hooks
|
|
5
|
+
* discovery + config fingerprint): sha256 of the canonical JSON of
|
|
6
|
+
* `{ event_name, matcher?, hooks: [handler] }`, where the handler always
|
|
7
|
+
* carries `timeout` (default 600, at least 1) and `async` (default false).
|
|
8
|
+
*/
|
|
9
|
+
export declare function codexHookHash(event: string, group: Record<string, unknown>, handler: Record<string, unknown>): string;
|
|
10
|
+
/**
|
|
11
|
+
* The config text with trust carried forward to Phren's handlers in
|
|
12
|
+
* `hooks` (the hooks.json text as it is now), or undefined when nothing
|
|
13
|
+
* changes. `before` is hooks.json as it stood before this install rewrote
|
|
14
|
+
* it, when there was a rewrite. `hooksPaths` are the names Codex may key
|
|
15
|
+
* this hooks.json by; the first is used for a new key.
|
|
16
|
+
*/
|
|
17
|
+
export declare function codexHookTrustText(config: string, hooks: string, program: string, hooksPaths: string[], before?: string): {
|
|
18
|
+
text: string;
|
|
19
|
+
carried: string[];
|
|
20
|
+
} | undefined;
|
|
21
|
+
/**
|
|
22
|
+
* Carries the owner's Codex trust forward to Phren's handlers in
|
|
23
|
+
* `$CODEX_HOME/hooks.json`. Runs after every install, update, rollback and
|
|
24
|
+
* module reconcile, whether or not hooks.json changed, so a computer an
|
|
25
|
+
* earlier install left untrusted is repaired too. Never throws.
|
|
26
|
+
*/
|
|
27
|
+
export declare function carryCodexHookTrust(program: string, before?: string, env?: NodeJS.ProcessEnv): Promise<string[]>;
|