Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
04ffe3b247 | ||
|
|
df5009c70b | ||
|
|
454d97f0cf | ||
|
|
4acb6e91ca |
No files matched your search
@@ -1,17 +1,44 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { Cause } from "effect";
|
||||
import { ManagedRuntime, ServiceMap } from "effect";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { ProviderSessionId } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
CodexAppServerManager,
|
||||
classifyCodexStderrLine,
|
||||
isRecoverableThreadResumeError,
|
||||
messageFromCodexProcessCause,
|
||||
normalizeCodexModelSlug,
|
||||
} from "./codexAppServerManager";
|
||||
|
||||
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
||||
|
||||
let runtime: ManagedRuntime.ManagedRuntime<NodeServices.NodeServices, never> | null = null;
|
||||
let services: ServiceMap.ServiceMap<NodeServices.NodeServices> | null = null;
|
||||
|
||||
beforeEach(async () => {
|
||||
runtime = ManagedRuntime.make(NodeServices.layer);
|
||||
services = await runtime.services();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
services = null;
|
||||
if (runtime) {
|
||||
await runtime.dispose();
|
||||
}
|
||||
runtime = null;
|
||||
});
|
||||
|
||||
function createManager() {
|
||||
if (!services) {
|
||||
throw new Error("Test runtime services not initialized.");
|
||||
}
|
||||
return new CodexAppServerManager(services);
|
||||
}
|
||||
|
||||
function createSendTurnHarness() {
|
||||
const manager = new CodexAppServerManager();
|
||||
const manager = createManager();
|
||||
const context = {
|
||||
session: {
|
||||
sessionId: "sess_1",
|
||||
@@ -47,7 +74,7 @@ function createSendTurnHarness() {
|
||||
}
|
||||
|
||||
function createThreadControlHarness() {
|
||||
const manager = new CodexAppServerManager();
|
||||
const manager = createManager();
|
||||
const context = {
|
||||
session: {
|
||||
sessionId: "sess_1",
|
||||
@@ -146,9 +173,15 @@ describe("isRecoverableThreadResumeError", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("messageFromCodexProcessCause", () => {
|
||||
it("extracts the underlying error message from an effect cause", () => {
|
||||
expect(messageFromCodexProcessCause(Cause.fail(new Error("boom")))).toBe("boom");
|
||||
});
|
||||
});
|
||||
|
||||
describe("startSession", () => {
|
||||
it("emits session/startFailed when resolving cwd throws before process launch", async () => {
|
||||
const manager = new CodexAppServerManager();
|
||||
const manager = createManager();
|
||||
const events: Array<{ method: string; kind: string; message?: string }> = [];
|
||||
manager.on("event", (event) => {
|
||||
events.push({
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import { type ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { EventEmitter } from "node:events";
|
||||
import readline from "node:readline";
|
||||
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
@@ -18,7 +16,10 @@ import {
|
||||
type ProviderSessionStartInput,
|
||||
type ProviderTurnStartResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { killProcessTree, spawnPipedProcess } from "./processRunner";
|
||||
import type * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { Cause, Effect, Exit, ServiceMap, Scope, Stream } from "effect";
|
||||
import type { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { makeRuntimeCommand, spawnManagedCommand } from "./processRunner";
|
||||
|
||||
type PendingRequestKey = string;
|
||||
|
||||
@@ -41,8 +42,8 @@ interface PendingApprovalRequest {
|
||||
|
||||
interface CodexSessionContext {
|
||||
session: ProviderSession;
|
||||
child: ChildProcessWithoutNullStreams;
|
||||
output: readline.Interface;
|
||||
child: ChildProcessSpawner.ChildProcessHandle;
|
||||
scope: Scope.Closeable;
|
||||
pending: Map<PendingRequestKey, PendingRequest>;
|
||||
pendingApprovals: Map<ApprovalRequestId, PendingApprovalRequest>;
|
||||
nextRequestId: number;
|
||||
@@ -152,12 +153,32 @@ export function isRecoverableThreadResumeError(error: unknown): boolean {
|
||||
return RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS.some((snippet) => message.includes(snippet));
|
||||
}
|
||||
|
||||
export function messageFromCodexProcessCause(cause: Cause.Cause<unknown>): string {
|
||||
const squashed = Cause.squash(cause);
|
||||
return squashed instanceof Error ? squashed.message : "codex app-server process errored.";
|
||||
}
|
||||
|
||||
export interface CodexAppServerManagerEvents {
|
||||
event: [event: ProviderEvent];
|
||||
}
|
||||
|
||||
export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEvents> {
|
||||
private readonly sessions = new Map<ProviderSessionId, CodexSessionContext>();
|
||||
private readonly runPromise: <A, E>(
|
||||
effect: Effect.Effect<A, E, NodeServices.NodeServices>,
|
||||
options?: Effect.RunOptions | undefined,
|
||||
) => Promise<A>;
|
||||
|
||||
constructor(services?: ServiceMap.ServiceMap<NodeServices.NodeServices>) {
|
||||
super();
|
||||
this.runPromise = services
|
||||
? Effect.runPromiseWith(services)
|
||||
: ((effect, options) =>
|
||||
Effect.runPromise(
|
||||
effect as unknown as Effect.Effect<unknown, never>,
|
||||
options,
|
||||
)) as typeof this.runPromise;
|
||||
}
|
||||
|
||||
async startSession(input: ProviderSessionStartInput): Promise<ProviderSession> {
|
||||
const sessionId = ProviderSessionId.makeUnsafe(randomUUID());
|
||||
@@ -179,19 +200,23 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
|
||||
const codexBinaryPath = input.codexBinaryPath ?? "codex";
|
||||
const codexHomePath = input.codexHomePath;
|
||||
const child = spawnPipedProcess(codexBinaryPath, ["app-server"], {
|
||||
cwd: resolvedCwd,
|
||||
env: {
|
||||
...process.env,
|
||||
...(codexHomePath ? { CODEX_HOME: codexHomePath } : {}),
|
||||
},
|
||||
});
|
||||
const output = readline.createInterface({ input: child.stdout });
|
||||
const managedProcess = await this.runPromise(
|
||||
spawnManagedCommand(
|
||||
makeRuntimeCommand(codexBinaryPath, ["app-server"], {
|
||||
cwd: resolvedCwd,
|
||||
env: {
|
||||
...process.env,
|
||||
...(codexHomePath ? { CODEX_HOME: codexHomePath } : {}),
|
||||
},
|
||||
extendEnv: false,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
context = {
|
||||
session,
|
||||
child,
|
||||
output,
|
||||
child: managedProcess.handle,
|
||||
scope: managedProcess.scope,
|
||||
pending: new Map(),
|
||||
pendingApprovals: new Map(),
|
||||
nextRequestId: 1,
|
||||
@@ -199,7 +224,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
};
|
||||
|
||||
this.sessions.set(sessionId, context);
|
||||
this.attachProcessListeners(context);
|
||||
await this.attachProcessListeners(context);
|
||||
|
||||
this.emitLifecycleEvent(context, "session/connecting", "Starting codex app-server");
|
||||
|
||||
@@ -214,7 +239,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
},
|
||||
});
|
||||
|
||||
this.writeMessage(context, { method: "initialized" });
|
||||
await this.writeMessage(context, { method: "initialized" });
|
||||
|
||||
const normalizedModel = normalizeCodexModelSlug(input.model);
|
||||
const sessionOverrides = {
|
||||
@@ -430,7 +455,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
}
|
||||
|
||||
context.pendingApprovals.delete(requestId);
|
||||
this.writeMessage(context, {
|
||||
await this.writeMessage(context, {
|
||||
id: pendingRequest.jsonRpcId,
|
||||
result: {
|
||||
decision,
|
||||
@@ -471,12 +496,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
}
|
||||
context.pending.clear();
|
||||
context.pendingApprovals.clear();
|
||||
|
||||
context.output.close();
|
||||
|
||||
if (!context.child.killed) {
|
||||
killProcessTree(context.child);
|
||||
}
|
||||
void this.runPromise(Scope.close(context.scope, Exit.void)).catch(() => undefined);
|
||||
|
||||
this.updateSession(context, {
|
||||
status: "closed",
|
||||
@@ -515,47 +535,71 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
return context;
|
||||
}
|
||||
|
||||
private attachProcessListeners(context: CodexSessionContext): void {
|
||||
context.output.on("line", (line) => {
|
||||
this.handleStdoutLine(context, line);
|
||||
});
|
||||
private async attachProcessListeners(context: CodexSessionContext): Promise<void> {
|
||||
await this.runPromise(
|
||||
Effect.gen(
|
||||
function* (this: CodexAppServerManager) {
|
||||
yield* Effect.forkScoped(
|
||||
Stream.runForEach(Stream.splitLines(Stream.decodeText(context.child.stdout)), (line) =>
|
||||
Effect.sync(() => {
|
||||
this.handleStdoutLine(context, line);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
context.child.stderr.on("data", (chunk: Buffer) => {
|
||||
const raw = chunk.toString();
|
||||
const lines = raw.split(/\r?\n/g);
|
||||
for (const rawLine of lines) {
|
||||
const classified = classifyCodexStderrLine(rawLine);
|
||||
if (!classified) {
|
||||
continue;
|
||||
}
|
||||
yield* Effect.forkScoped(
|
||||
Stream.runForEach(Stream.decodeText(context.child.stderr), (raw) =>
|
||||
Effect.sync(() => {
|
||||
const lines = raw.split(/\r?\n/g);
|
||||
for (const rawLine of lines) {
|
||||
const classified = classifyCodexStderrLine(rawLine);
|
||||
if (!classified) {
|
||||
continue;
|
||||
}
|
||||
|
||||
this.emitErrorEvent(context, "process/stderr", classified.message);
|
||||
}
|
||||
});
|
||||
this.emitErrorEvent(context, "process/stderr", classified.message);
|
||||
}
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
context.child.on("error", (error) => {
|
||||
const message = error.message || "codex app-server process errored.";
|
||||
this.updateSession(context, {
|
||||
status: "error",
|
||||
lastError: message,
|
||||
});
|
||||
this.emitErrorEvent(context, "process/error", message);
|
||||
});
|
||||
yield* Effect.forkScoped(
|
||||
Effect.matchCauseEffect(context.child.exitCode, {
|
||||
onFailure: (cause) =>
|
||||
Effect.sync(() => {
|
||||
if (context.stopping) {
|
||||
return;
|
||||
}
|
||||
|
||||
context.child.on("exit", (code, signal) => {
|
||||
if (context.stopping) {
|
||||
return;
|
||||
}
|
||||
const message = messageFromCodexProcessCause(cause);
|
||||
this.updateSession(context, {
|
||||
status: "error",
|
||||
activeTurnId: undefined,
|
||||
lastError: message,
|
||||
});
|
||||
this.emitErrorEvent(context, "process/error", message);
|
||||
this.sessions.delete(context.session.sessionId);
|
||||
}),
|
||||
onSuccess: (code) =>
|
||||
Effect.sync(() => {
|
||||
if (context.stopping) {
|
||||
return;
|
||||
}
|
||||
|
||||
const message = `codex app-server exited (code=${code ?? "null"}, signal=${signal ?? "null"}).`;
|
||||
this.updateSession(context, {
|
||||
status: "closed",
|
||||
activeTurnId: undefined,
|
||||
lastError: code === 0 ? context.session.lastError : message,
|
||||
});
|
||||
this.emitLifecycleEvent(context, "session/exited", message);
|
||||
this.sessions.delete(context.session.sessionId);
|
||||
});
|
||||
const message = `codex app-server exited (code=${code}).`;
|
||||
this.updateSession(context, {
|
||||
status: "closed",
|
||||
activeTurnId: undefined,
|
||||
lastError: code === 0 ? context.session.lastError : message,
|
||||
});
|
||||
this.emitLifecycleEvent(context, "session/exited", message);
|
||||
this.sessions.delete(context.session.sessionId);
|
||||
}),
|
||||
}),
|
||||
);
|
||||
}.bind(this),
|
||||
).pipe(Scope.provide(context.scope)),
|
||||
);
|
||||
}
|
||||
|
||||
private handleStdoutLine(context: CodexSessionContext, line: string): void {
|
||||
@@ -711,19 +755,31 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
}
|
||||
|
||||
if (request.method === "item/tool/requestUserInput") {
|
||||
this.writeMessage(context, {
|
||||
void this.writeMessage(context, {
|
||||
id: request.id,
|
||||
result: { answers: {} },
|
||||
}).catch((error) => {
|
||||
this.emitErrorEvent(
|
||||
context,
|
||||
"protocol/writeError",
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
this.writeMessage(context, {
|
||||
void this.writeMessage(context, {
|
||||
id: request.id,
|
||||
error: {
|
||||
code: -32601,
|
||||
message: `Unsupported server request: ${request.method}`,
|
||||
},
|
||||
}).catch((error) => {
|
||||
this.emitErrorEvent(
|
||||
context,
|
||||
"protocol/writeError",
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -766,23 +822,30 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
resolve,
|
||||
reject,
|
||||
});
|
||||
this.writeMessage(context, {
|
||||
void this.writeMessage(context, {
|
||||
method,
|
||||
id,
|
||||
params,
|
||||
}).catch((error) => {
|
||||
clearTimeout(timeout);
|
||||
context.pending.delete(String(id));
|
||||
reject(error instanceof Error ? error : new Error(String(error)));
|
||||
});
|
||||
});
|
||||
|
||||
return result as TResponse;
|
||||
}
|
||||
|
||||
private writeMessage(context: CodexSessionContext, message: unknown): void {
|
||||
private async writeMessage(context: CodexSessionContext, message: unknown): Promise<void> {
|
||||
const encoded = JSON.stringify(message);
|
||||
if (!context.child.stdin.writable) {
|
||||
if (context.stopping) {
|
||||
throw new Error("Cannot write to codex app-server stdin.");
|
||||
}
|
||||
|
||||
context.child.stdin.write(`${encoded}\n`);
|
||||
await this.runPromise(
|
||||
Stream.run(context.child.stdin)(Stream.make(new TextEncoder().encode(`${encoded}\n`))).pipe(
|
||||
Scope.provide(context.scope),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
private emitLifecycleEvent(context: CodexSessionContext, method: string, message: string): void {
|
||||
|
||||
@@ -3,7 +3,7 @@ import { it, assert } from "@effect/vitest";
|
||||
import { Effect, Layer, Schema } from "effect";
|
||||
|
||||
import { GitCommandError } from "../Errors.ts";
|
||||
import { GitServiceLive } from "./GitService.ts";
|
||||
import { GitServiceLive, normalizeGitProcessResult } from "./GitService.ts";
|
||||
import { GitService } from "../Services/GitService.ts";
|
||||
|
||||
const layer = it.layer(Layer.provideMerge(GitServiceLive, NodeServices.layer));
|
||||
@@ -56,4 +56,31 @@ layer("GitServiceLive", (it) => {
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it("normalizeGitProcessResult fails when git exits without a code", () => {
|
||||
try {
|
||||
void normalizeGitProcessResult(
|
||||
{
|
||||
operation: "GitProcess.test.signal",
|
||||
cwd: process.cwd(),
|
||||
args: ["status"],
|
||||
},
|
||||
{},
|
||||
{
|
||||
code: null,
|
||||
signal: "SIGTERM",
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
timedOut: false,
|
||||
},
|
||||
);
|
||||
assert.fail("Expected normalizeGitProcessResult to throw.");
|
||||
} catch (error) {
|
||||
assert.equal(Schema.is(GitCommandError)(error), true);
|
||||
if (!Schema.is(GitCommandError)(error)) {
|
||||
return;
|
||||
}
|
||||
assert.equal(error.detail, "git status terminated by signal SIGTERM.");
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -39,6 +39,59 @@ function toGitCommandError(
|
||||
});
|
||||
}
|
||||
|
||||
export function normalizeGitProcessResult(
|
||||
commandInput: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
|
||||
input: Pick<ExecuteGitInput, "allowNonZeroExit">,
|
||||
result: {
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
readonly code: number | null;
|
||||
readonly signal: NodeJS.Signals | null;
|
||||
readonly timedOut: boolean;
|
||||
},
|
||||
): ExecuteGitResult {
|
||||
if (result.timedOut) {
|
||||
throw new GitCommandError({
|
||||
operation: commandInput.operation,
|
||||
command: quoteGitCommand(commandInput.args),
|
||||
cwd: commandInput.cwd,
|
||||
detail: `${quoteGitCommand(commandInput.args)} timed out.`,
|
||||
});
|
||||
}
|
||||
|
||||
if (result.code === null) {
|
||||
throw new GitCommandError({
|
||||
operation: commandInput.operation,
|
||||
command: quoteGitCommand(commandInput.args),
|
||||
cwd: commandInput.cwd,
|
||||
detail:
|
||||
result.signal !== null
|
||||
? `${quoteGitCommand(commandInput.args)} terminated by signal ${result.signal}.`
|
||||
: `${quoteGitCommand(commandInput.args)} terminated before reporting an exit code.`,
|
||||
});
|
||||
}
|
||||
|
||||
const exitCode = result.code;
|
||||
if (!input.allowNonZeroExit && exitCode !== 0) {
|
||||
const trimmedStderr = result.stderr.trim();
|
||||
throw new GitCommandError({
|
||||
operation: commandInput.operation,
|
||||
command: quoteGitCommand(commandInput.args),
|
||||
cwd: commandInput.cwd,
|
||||
detail:
|
||||
trimmedStderr.length > 0
|
||||
? `${quoteGitCommand(commandInput.args)} failed: ${trimmedStderr}`
|
||||
: `${quoteGitCommand(commandInput.args)} failed with code ${exitCode}.`,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
code: exitCode,
|
||||
stdout: result.stdout,
|
||||
stderr: result.stderr,
|
||||
} satisfies ExecuteGitResult;
|
||||
}
|
||||
|
||||
const makeGitService = Effect.sync(() => {
|
||||
const execute: GitServiceShape["execute"] = Effect.fnUntraced(function* (input) {
|
||||
const commandInput = {
|
||||
@@ -59,34 +112,7 @@ const makeGitService = Effect.sync(() => {
|
||||
outputMode: "error",
|
||||
});
|
||||
|
||||
if (result.timedOut) {
|
||||
throw new GitCommandError({
|
||||
operation: commandInput.operation,
|
||||
command: quoteGitCommand(commandInput.args),
|
||||
cwd: commandInput.cwd,
|
||||
detail: `${quoteGitCommand(commandInput.args)} timed out.`,
|
||||
});
|
||||
}
|
||||
|
||||
const exitCode = result.code ?? 0;
|
||||
if (!input.allowNonZeroExit && exitCode !== 0) {
|
||||
const trimmedStderr = result.stderr.trim();
|
||||
throw new GitCommandError({
|
||||
operation: commandInput.operation,
|
||||
command: quoteGitCommand(commandInput.args),
|
||||
cwd: commandInput.cwd,
|
||||
detail:
|
||||
trimmedStderr.length > 0
|
||||
? `${quoteGitCommand(commandInput.args)} failed: ${trimmedStderr}`
|
||||
: `${quoteGitCommand(commandInput.args)} failed with code ${exitCode}.`,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
code: exitCode,
|
||||
stdout: result.stdout,
|
||||
stderr: result.stderr,
|
||||
} satisfies ExecuteGitResult;
|
||||
return normalizeGitProcessResult(commandInput, input, result);
|
||||
},
|
||||
catch: toGitCommandError(commandInput, "failed to run."),
|
||||
});
|
||||
|
||||
@@ -7,6 +7,8 @@ import {
|
||||
} from "node:child_process";
|
||||
|
||||
import type { ServerRuntimeEnvironment } from "@t3tools/contracts";
|
||||
import { Effect, Exit, Scope } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { detectServerRuntimeEnvironment } from "./runtimeEnvironment";
|
||||
|
||||
@@ -17,12 +19,21 @@ interface ProcessSpawnBaseOptions {
|
||||
shell?: boolean | undefined;
|
||||
}
|
||||
|
||||
export interface ProcessSpawnOptions extends ProcessSpawnBaseOptions {
|
||||
interface RuntimeShellOptions {
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment | undefined;
|
||||
shell?: boolean | string | undefined;
|
||||
}
|
||||
|
||||
interface ProcessSpawnOptions extends ProcessSpawnBaseOptions {
|
||||
stdio?: StdioOptions | undefined;
|
||||
detached?: boolean | undefined;
|
||||
}
|
||||
|
||||
export interface ProcessSpawnSyncOptions extends ProcessSpawnBaseOptions {
|
||||
interface RuntimeCommandOptions extends ChildProcess.CommandOptions {
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment | undefined;
|
||||
}
|
||||
|
||||
interface ProcessSpawnSyncOptions extends ProcessSpawnBaseOptions {
|
||||
stdio?: StdioOptions | undefined;
|
||||
detached?: boolean | undefined;
|
||||
encoding?: BufferEncoding | undefined;
|
||||
@@ -61,7 +72,7 @@ function resolveRuntimeEnvironment(
|
||||
return runtimeEnvironment ?? detectServerRuntimeEnvironment();
|
||||
}
|
||||
|
||||
function shouldUseShell(options: ProcessSpawnBaseOptions): boolean {
|
||||
function shouldUseShell(options: RuntimeShellOptions): boolean | string {
|
||||
if (options.shell !== undefined) {
|
||||
return options.shell;
|
||||
}
|
||||
@@ -79,7 +90,45 @@ function toSpawnOptions(options: ProcessSpawnOptions) {
|
||||
};
|
||||
}
|
||||
|
||||
export function spawnProcess(
|
||||
function toRuntimeCommandOptions(
|
||||
options: RuntimeCommandOptions = {},
|
||||
): ChildProcess.CommandOptions {
|
||||
const { runtimeEnvironment: _, ...rest } = options;
|
||||
return {
|
||||
...rest,
|
||||
shell: options.shell ?? shouldUseShell(options),
|
||||
};
|
||||
}
|
||||
|
||||
export function makeRuntimeCommand(
|
||||
command: string,
|
||||
args: ReadonlyArray<string>,
|
||||
options: RuntimeCommandOptions = {},
|
||||
): ChildProcess.StandardCommand {
|
||||
return ChildProcess.make(command, [...args], toRuntimeCommandOptions(options));
|
||||
}
|
||||
|
||||
interface ManagedChildProcess {
|
||||
readonly scope: Scope.Closeable;
|
||||
readonly handle: ChildProcessSpawner.ChildProcessHandle;
|
||||
}
|
||||
|
||||
export const spawnManagedCommand = (command: ChildProcess.Command) =>
|
||||
Effect.gen(function* () {
|
||||
const scope = yield* Scope.make("sequential");
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const handle = yield* spawner.spawn(command).pipe(
|
||||
Scope.provide(scope),
|
||||
Effect.tapError(() => Scope.close(scope, Exit.void)),
|
||||
);
|
||||
|
||||
return {
|
||||
scope,
|
||||
handle,
|
||||
} satisfies ManagedChildProcess;
|
||||
});
|
||||
|
||||
function spawnProcess(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
options: ProcessSpawnOptions = {},
|
||||
@@ -87,7 +136,7 @@ export function spawnProcess(
|
||||
return spawn(command, args, toSpawnOptions(options));
|
||||
}
|
||||
|
||||
export function spawnPipedProcess(
|
||||
function spawnPipedProcess(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
options: Omit<ProcessSpawnOptions, "stdio" | "detached"> = {},
|
||||
@@ -204,7 +253,7 @@ const DEFAULT_MAX_BUFFER_BYTES = 8 * 1024 * 1024;
|
||||
* wrapper, leaving the actual command running. Use `taskkill /T` to kill the
|
||||
* entire process tree instead.
|
||||
*/
|
||||
export function killProcessTree(
|
||||
function killProcessTree(
|
||||
child: ChildProcessHandle,
|
||||
options: {
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment | undefined;
|
||||
|
||||
@@ -33,6 +33,7 @@ import { CodexAppServerManager } from "../../codexAppServerManager.ts";
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
|
||||
const PROVIDER = "codex" as const;
|
||||
|
||||
@@ -433,6 +434,7 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const serverConfig = yield* Effect.service(ServerConfig);
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const services = yield* Effect.services<NodeServices.NodeServices>();
|
||||
const nativeEventLogger =
|
||||
options?.nativeEventLogger ??
|
||||
(options?.nativeEventLogPath !== undefined
|
||||
@@ -449,7 +451,7 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
|
||||
if (options?.makeManager) {
|
||||
return options.makeManager();
|
||||
}
|
||||
return new CodexAppServerManager();
|
||||
return new CodexAppServerManager(services);
|
||||
}),
|
||||
(manager) =>
|
||||
Effect.sync(() => {
|
||||
@@ -587,24 +589,25 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
|
||||
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
|
||||
yield* Effect.acquireRelease(
|
||||
Effect.gen(function* () {
|
||||
Effect.sync(() => {
|
||||
const writeNativeEvent = (event: ProviderEvent) =>
|
||||
Effect.gen(function* () {
|
||||
if (!nativeEventLogger) {
|
||||
return;
|
||||
}
|
||||
const orchestrationThreadId = yield* Effect.catch(
|
||||
directory.getThreadId(event.sessionId).pipe(
|
||||
Effect.map((threadIdOption) =>
|
||||
Option.isSome(threadIdOption) ? threadIdOption.value : null,
|
||||
directory
|
||||
.getThreadId(event.sessionId)
|
||||
.pipe(
|
||||
Effect.map((threadIdOption) =>
|
||||
Option.isSome(threadIdOption) ? threadIdOption.value : null,
|
||||
),
|
||||
),
|
||||
),
|
||||
() => Effect.succeed(null),
|
||||
);
|
||||
yield* nativeEventLogger.write(event, orchestrationThreadId);
|
||||
});
|
||||
|
||||
const services = yield* Effect.services<never>();
|
||||
const listener = (event: ProviderEvent) =>
|
||||
Effect.gen(function* () {
|
||||
yield* writeNativeEvent(event);
|
||||
|
||||
@@ -7,7 +7,12 @@ import { checkCodexProviderStatus, parseAuthStatusFromOutput } from "./ProviderH
|
||||
// ── Test helpers ────────────────────────────────────────────────────
|
||||
|
||||
function mockRunner(
|
||||
handler: (args: ReadonlyArray<string>) => { stdout: string; stderr: string; code: number },
|
||||
handler: (args: ReadonlyArray<string>) => {
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
code: number | null;
|
||||
timedOut?: boolean;
|
||||
},
|
||||
) {
|
||||
return (args: ReadonlyArray<string>) => Promise.resolve(handler(args));
|
||||
}
|
||||
@@ -116,6 +121,32 @@ it.effect("returns warning when login status command is unsupported", () =>
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns unavailable when codex version probe times out", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkCodexProviderStatus(
|
||||
mockRunner((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") {
|
||||
return { stdout: "", stderr: "", code: null, timedOut: true };
|
||||
}
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
);
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.available, false);
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(status.message, "Codex CLI is installed but failed to run. Timed out while running command.");
|
||||
}),
|
||||
);
|
||||
|
||||
it("parseAuthStatusFromOutput: timed out auth check is warning", () => {
|
||||
const parsed = parseAuthStatusFromOutput({ stdout: "", stderr: "", code: null, timedOut: true });
|
||||
assert.strictEqual(parsed.status, "warning");
|
||||
assert.strictEqual(parsed.authStatus, "unknown");
|
||||
assert.strictEqual(parsed.message, "Timed out while checking Codex authentication status.");
|
||||
});
|
||||
|
||||
// ── Pure function tests ─────────────────────────────────────────────
|
||||
|
||||
it("parseAuthStatusFromOutput: exit code 0 with no auth markers is ready", () => {
|
||||
|
||||
@@ -31,7 +31,7 @@ class ProviderHealthCommandError extends Data.TaggedError("ProviderHealthCommand
|
||||
export interface CommandResult {
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
readonly code: number;
|
||||
readonly code: number | null;
|
||||
readonly timedOut?: boolean;
|
||||
}
|
||||
|
||||
@@ -76,6 +76,9 @@ function detailFromResult(
|
||||
if (stderr) return stderr;
|
||||
const stdout = nonEmptyTrimmed(result.stdout);
|
||||
if (stdout) return stdout;
|
||||
if (result.code === null) {
|
||||
return "Command was terminated before reporting an exit code.";
|
||||
}
|
||||
if (result.code !== 0) {
|
||||
return `Command exited with code ${result.code}.`;
|
||||
}
|
||||
@@ -109,6 +112,14 @@ export function parseAuthStatusFromOutput(result: CommandResult): {
|
||||
readonly authStatus: ServerProviderAuthStatus;
|
||||
readonly message?: string;
|
||||
} {
|
||||
if (result.timedOut) {
|
||||
return {
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message: "Timed out while checking Codex authentication status.",
|
||||
};
|
||||
}
|
||||
|
||||
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
|
||||
|
||||
if (
|
||||
@@ -199,7 +210,7 @@ const defaultRunCodexCommand: RunProviderHealthCommand = async (args) => {
|
||||
return {
|
||||
stdout: result.stdout,
|
||||
stderr: result.stderr,
|
||||
code: result.code ?? 0,
|
||||
code: result.code,
|
||||
timedOut: result.timedOut,
|
||||
} satisfies CommandResult;
|
||||
};
|
||||
@@ -237,7 +248,7 @@ export const checkCodexProviderStatus = (
|
||||
}
|
||||
|
||||
const version = versionProbe.success;
|
||||
if (version.code !== 0) {
|
||||
if (version.timedOut || version.code !== 0) {
|
||||
const detail = detailFromResult(version);
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
|
||||
@@ -38,7 +38,7 @@ import { NodePtyAdapterLive } from "./terminal/Layers/NodePTY";
|
||||
export function makeServerProviderLayer(): Layer.Layer<
|
||||
ProviderService,
|
||||
ProviderUnsupportedError,
|
||||
SqlClient.SqlClient | ServerConfig | FileSystem.FileSystem
|
||||
SqlClient.SqlClient | ServerConfig | FileSystem.FileSystem | NodeServices.NodeServices
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
const { stateDir } = yield* ServerConfig;
|
||||
|
||||
Reference in new issue
Block a user