Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge 431692222d Use Duration policies in SSH readiness
Co-authored-by: Julius Marminge <[email protected]>
2026-06-01 16:06:46 +00:00
8 changed files with 78 additions and 86 deletions

No files matched your search

@@ -37,7 +37,6 @@ import {
import { type OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts";
import {
buildOpenCodePermissionRules,
isOpenCodeRuntimeError,
OpenCodeRuntime,
OpenCodeRuntimeError,
openCodeQuestionId,
@@ -131,7 +130,7 @@ const toProcessError = (threadId: ThreadId, cause: unknown): ProviderAdapterProc
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId,
detail: isOpenCodeRuntimeError(cause) ? cause.detail : openCodeRuntimeErrorDetail(cause),
detail: OpenCodeRuntimeError.is(cause) ? cause.detail : openCodeRuntimeErrorDetail(cause),
cause,
});
+19 -22
View File
@@ -13,13 +13,14 @@ import {
} from "@opencode-ai/sdk/v2";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as P from "effect/Predicate";
import * as Ref from "effect/Ref";
import * as Result from "effect/Result";
import * as Scope from "effect/Scope";
@@ -34,7 +35,7 @@ const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.UnknownFromJ
const OPENCODE_EMPTY_CONFIG_CONTENT = "{}";
const OPENCODE_SERVER_READY_PREFIX = "opencode server listening";
const DEFAULT_OPENCODE_SERVER_TIMEOUT = Duration.seconds(5);
const DEFAULT_OPENCODE_SERVER_TIMEOUT_MS = 5_000;
const DEFAULT_HOSTNAME = "127.0.0.1";
export interface OpenCodeServerProcess {
readonly url: string;
@@ -47,19 +48,15 @@ export interface OpenCodeServerConnection {
readonly external: boolean;
}
export class OpenCodeRuntimeError extends Schema.TaggedErrorClass<OpenCodeRuntimeError>()(
"OpenCodeRuntimeError",
{
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message() {
return this.detail;
}
const OPENCODE_RUNTIME_ERROR_TAG = "OpenCodeRuntimeError";
export class OpenCodeRuntimeError extends Data.TaggedError(OPENCODE_RUNTIME_ERROR_TAG)<{
readonly operation: string;
readonly cause?: unknown;
readonly detail: string;
}> {
static readonly is = (u: unknown): u is OpenCodeRuntimeError =>
P.isTagged(u, OPENCODE_RUNTIME_ERROR_TAG);
}
export const isOpenCodeRuntimeError = Schema.is(OpenCodeRuntimeError);
function encodeJsonStringForDiagnostics(input: unknown): string | undefined {
const result = encodeUnknownJsonStringExit(input);
@@ -67,7 +64,7 @@ function encodeJsonStringForDiagnostics(input: unknown): string | undefined {
}
export function openCodeRuntimeErrorDetail(cause: unknown): string {
if (isOpenCodeRuntimeError(cause)) return cause.detail;
if (OpenCodeRuntimeError.is(cause)) return cause.detail;
if (cause instanceof Error && cause.message.trim().length > 0) return cause.message.trim();
if (cause && typeof cause === "object") {
// SDK v2 throws { response, request, error? } shapes — extract what's useful
@@ -120,7 +117,7 @@ export interface OpenCodeRuntimeShape {
readonly environment?: NodeJS.ProcessEnv;
readonly port?: number;
readonly hostname?: string;
readonly timeout?: Duration.Input;
readonly timeoutMs?: number;
}) => Effect.Effect<OpenCodeServerProcess, OpenCodeRuntimeError, Scope.Scope>;
/**
* Returns a handle to either an externally-managed OpenCode server (when
@@ -133,7 +130,7 @@ export interface OpenCodeRuntimeShape {
readonly environment?: NodeJS.ProcessEnv;
readonly port?: number;
readonly hostname?: string;
readonly timeout?: Duration.Input;
readonly timeoutMs?: number;
}) => Effect.Effect<OpenCodeServerConnection, OpenCodeRuntimeError, Scope.Scope>;
readonly runOpenCodeCommand: (input: {
readonly binaryPath: string;
@@ -271,7 +268,7 @@ function ensureRuntimeError(
detail: string,
cause: unknown,
): OpenCodeRuntimeError {
return isOpenCodeRuntimeError(cause)
return OpenCodeRuntimeError.is(cause)
? cause
: new OpenCodeRuntimeError({ operation, detail, cause });
}
@@ -335,7 +332,7 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
}),
),
));
const timeout = Duration.fromInputUnsafe(input.timeout ?? DEFAULT_OPENCODE_SERVER_TIMEOUT);
const timeoutMs = input.timeoutMs ?? DEFAULT_OPENCODE_SERVER_TIMEOUT_MS;
const args = ["serve", `--hostname=${hostname}`, `--port=${port}`];
const child = yield* spawner
@@ -434,7 +431,7 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
);
const readyExit = yield* Effect.exit(
Deferred.await(readyDeferred).pipe(Effect.timeoutOption(timeout)),
Deferred.await(readyDeferred).pipe(Effect.timeoutOption(timeoutMs)),
);
// Startup-time fibers are no longer needed once ready has resolved (either
@@ -458,7 +455,7 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
yield* Fiber.interrupt(exitFiber).pipe(Effect.ignore);
return yield* new OpenCodeRuntimeError({
operation: "startOpenCodeServerProcess",
detail: `Timed out waiting for OpenCode server start after ${Duration.format(timeout)}.`,
detail: `Timed out waiting for OpenCode server start after ${timeoutMs}ms.`,
});
}
@@ -487,7 +484,7 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
...(input.environment !== undefined ? { environment: input.environment } : {}),
...(input.port !== undefined ? { port: input.port } : {}),
...(input.hostname !== undefined ? { hostname: input.hostname } : {}),
...(input.timeout !== undefined ? { timeout: input.timeout } : {}),
...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
}).pipe(
Effect.map((server) => ({
url: server.url,
@@ -50,13 +50,6 @@ it.layer(NodeServices.layer)("providerStatusCache", (it) => {
const claudeProvider = makeProvider(CLAUDE_AGENT_DRIVER, {
status: "warning",
auth: { status: "unknown" },
updateState: {
status: "queued",
startedAt: null,
finishedAt: null,
message: null,
output: null,
},
});
const openCodeProvider = makeProvider(OPENCODE_DRIVER, {
status: "warning",
@@ -88,13 +81,9 @@ it.layer(NodeServices.layer)("providerStatusCache", (it) => {
provider: openCodeProvider,
});
const { updateState: _updateState, ...cacheableClaudeProvider } = claudeProvider;
assert.deepStrictEqual(yield* readProviderStatusCache(codexPath), codexProvider);
assert.deepStrictEqual(yield* readProviderStatusCache(claudePath), cacheableClaudeProvider);
assert.deepStrictEqual(yield* readProviderStatusCache(claudePath), claudeProvider);
assert.deepStrictEqual(yield* readProviderStatusCache(openCodePath), openCodeProvider);
const claudeCacheContents = yield* fs.readFileString(claudePath);
assert.strictEqual(claudeCacheContents.includes("updateState"), false);
}),
);
@@ -9,15 +9,12 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
import { writeFileStringAtomically } from "../atomicWrite.ts";
const decodeProviderStatusCache = Schema.decodeUnknownEffect(
Schema.fromJsonString(ServerProviderSchema),
);
const ProviderStatusCacheJson = fromJsonStringPretty(ServerProviderSchema);
const encodeProviderStatusCache = Schema.encodeEffect(ProviderStatusCacheJson);
const mergeProviderModels = (
fallbackModels: ReadonlyArray<ServerProvider["models"][number]>,
@@ -149,11 +146,8 @@ export const writeProviderStatusCache = (input: {
readonly provider: ServerProvider;
}) => {
const { updateState: _updateState, ...cacheableProvider } = input.provider;
return Effect.gen(function* () {
const contents = yield* encodeProviderStatusCache(cacheableProvider);
yield* writeFileStringAtomically({
filePath: input.filePath,
contents: `${contents}\n`,
});
return writeFileStringAtomically({
filePath: input.filePath,
contents: `${JSON.stringify(cacheableProvider, null, 2)}\n`,
});
};
+1 -1
View File
@@ -139,7 +139,7 @@ describe("ssh command", () => {
username: "julius",
port: 2222,
},
{ timeoutMs: 1 },
{ timeout: Duration.millis(1) },
),
),
);
+10 -6
View File
@@ -14,7 +14,7 @@ import { buildSshChildEnvironment, type SshAuthOptions } from "./auth.ts";
import { SshCommandError, SshInvalidTargetError } from "./errors.ts";
const PUBLISHABLE_T3_VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u;
const DEFAULT_SSH_COMMAND_TIMEOUT_MS = 60_000;
const DEFAULT_SSH_COMMAND_TIMEOUT = Duration.seconds(60);
const encoder = new TextEncoder();
@@ -27,7 +27,7 @@ export interface RunSshCommandOptions extends SshAuthOptions {
readonly preHostArgs?: ReadonlyArray<string>;
readonly remoteCommandArgs?: ReadonlyArray<string>;
readonly stdin?: string;
readonly timeoutMs?: number;
readonly timeout?: Duration.Input;
}
export function parseSshResolveOutput(alias: string, stdout: string): DesktopSshEnvironmentTarget {
@@ -146,6 +146,8 @@ const runSshCommandInScope = Effect.fn("ssh/command.runSshCommand.inScope")(func
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
> {
const hostSpec = yield* buildSshHostSpecEffect(target);
const timeout = Duration.fromInputUnsafe(input.timeout ?? DEFAULT_SSH_COMMAND_TIMEOUT);
const timeoutMs = Duration.toMillis(timeout);
const environment = yield* buildSshChildEnvironment({
...(input.interactiveAuth === undefined ? {} : { interactiveAuth: input.interactiveAuth }),
...(input.authSecret === undefined ? {} : { authSecret: input.authSecret }),
@@ -174,7 +176,7 @@ const runSshCommandInScope = Effect.fn("ssh/command.runSshCommand.inScope")(func
...sshTargetLogFields(target),
command: ["ssh", ...args],
hasStdin: input.stdin !== undefined,
timeoutMs: input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS,
timeoutMs,
});
const child = yield* spawner
.spawn(
@@ -258,10 +260,12 @@ export const runSshCommand = Effect.fn("ssh/command.runSshCommand")(function* (
SshCommandError | SshInvalidTargetError,
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
> {
const timeout = Duration.fromInputUnsafe(input.timeout ?? DEFAULT_SSH_COMMAND_TIMEOUT);
const timeoutMs = Duration.toMillis(timeout);
return yield* Effect.scopedWith((commandScope) =>
runSshCommandInScope(target, input, commandScope),
).pipe(
Effect.timeoutOption(Duration.millis(input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS)),
Effect.timeoutOption(timeout),
Effect.flatMap((result) =>
Option.match(result, {
onSome: Effect.succeed,
@@ -269,7 +273,7 @@ export const runSshCommand = Effect.fn("ssh/command.runSshCommand")(function* (
Effect.gen(function* () {
yield* Effect.logWarning("ssh.command.timedOut", {
...sshTargetLogFields(target),
timeoutMs: input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS,
timeoutMs,
remoteCommandArgs: input.remoteCommandArgs ?? [],
preHostArgs: input.preHostArgs ?? [],
hasStdin: input.stdin !== undefined,
@@ -278,7 +282,7 @@ export const runSshCommand = Effect.fn("ssh/command.runSshCommand")(function* (
command: ["ssh"],
exitCode: null,
stderr: "",
message: `SSH command timed out after ${input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS}ms.`,
message: `SSH command timed out after ${timeoutMs}ms.`,
});
}),
}),
+3 -3
View File
@@ -242,9 +242,9 @@ describe("ssh tunnel scripts", () => {
Effect.result(
waitForHttpReady({
baseUrl: "http://127.0.0.1:41773/",
timeoutMs: 1_000,
intervalMs: 100,
probeTimeoutMs: 250,
timeout: Duration.seconds(1),
interval: Duration.millis(100),
probeTimeout: Duration.millis(250),
}),
),
);
+40 -31
View File
@@ -50,11 +50,11 @@ import {
export const DEFAULT_REMOTE_PORT = 3773;
const REMOTE_PORT_SCAN_WINDOW = 200;
const SSH_READY_TIMEOUT_MS = 20_000;
const SSH_READY_PROBE_TIMEOUT_MS = 1_000;
const TUNNEL_SHUTDOWN_TIMEOUT_MS = 2_000;
const REMOTE_READY_TIMEOUT_MS = 15_000;
const REMOTE_REUSE_READY_TIMEOUT_MS = 2_000;
const SSH_READY_TIMEOUT = Duration.seconds(20);
const SSH_READY_PROBE_TIMEOUT = Duration.seconds(1);
const TUNNEL_SHUTDOWN_TIMEOUT = Duration.seconds(2);
const REMOTE_READY_TIMEOUT = Duration.seconds(15);
const REMOTE_REUSE_READY_TIMEOUT = Duration.seconds(2);
export interface RemoteT3RunnerOptions {
readonly packageSpec?: string;
@@ -686,9 +686,9 @@ export function buildRemoteLaunchScript(input?: RemoteT3RunnerOptions): string {
T3_WAIT_READY_SCRIPT: stripTrailingNewlines(REMOTE_WAIT_READY_SCRIPT),
T3_DEFAULT_REMOTE_PORT: String(DEFAULT_REMOTE_PORT),
T3_REMOTE_PORT_SCAN_WINDOW: String(REMOTE_PORT_SCAN_WINDOW),
T3_READY_TIMEOUT_MS: String(REMOTE_READY_TIMEOUT_MS),
T3_REUSE_READY_TIMEOUT_MS: String(REMOTE_REUSE_READY_TIMEOUT_MS),
T3_READY_PROBE_TIMEOUT_MS: String(SSH_READY_PROBE_TIMEOUT_MS),
T3_READY_TIMEOUT_MS: String(Duration.toMillis(REMOTE_READY_TIMEOUT)),
T3_REUSE_READY_TIMEOUT_MS: String(Duration.toMillis(REMOTE_REUSE_READY_TIMEOUT)),
T3_READY_PROBE_TIMEOUT_MS: String(Duration.toMillis(SSH_READY_PROBE_TIMEOUT)),
});
}
@@ -860,7 +860,7 @@ const readRemoteServerLogTail = Effect.fn("ssh/tunnel.readRemoteServerLogTail")(
const result = yield* runSshCommand(target, {
remoteCommandArgs: ["sh", "-s"],
stdin: buildRemoteLogTailScript(target),
timeoutMs: 10_000,
timeout: Duration.seconds(10),
...(input?.authSecret === undefined ? {} : { authSecret: input.authSecret }),
...(input?.batchMode === undefined ? {} : { batchMode: input.batchMode }),
...(input?.interactiveAuth === undefined ? {} : { interactiveAuth: input.interactiveAuth }),
@@ -870,20 +870,26 @@ const readRemoteServerLogTail = Effect.fn("ssh/tunnel.readRemoteServerLogTail")(
export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(function* (input: {
readonly baseUrl: string;
readonly timeoutMs?: number;
readonly intervalMs?: number;
readonly probeTimeoutMs?: number;
readonly timeout?: Duration.Input;
readonly interval?: Duration.Input;
readonly probeTimeout?: Duration.Input;
readonly path?: string;
}): Effect.fn.Return<void, SshReadinessError, HttpClient.HttpClient> {
const timeoutMs = input.timeoutMs ?? 30_000;
const intervalMs = input.intervalMs ?? 100;
const probeTimeoutMs = input.probeTimeoutMs ?? SSH_READY_PROBE_TIMEOUT_MS;
const retryPolicy = Schedule.spaced(Duration.millis(intervalMs)).pipe(
Schedule.take(Math.max(0, Math.ceil(timeoutMs / intervalMs))),
);
const timeout = Duration.fromInputUnsafe(input.timeout ?? Duration.seconds(30));
const interval = Duration.fromInputUnsafe(input.interval ?? Duration.millis(100));
const probeTimeout = Duration.fromInputUnsafe(input.probeTimeout ?? SSH_READY_PROBE_TIMEOUT);
const timeoutMs = Duration.toMillis(timeout);
const intervalMs = Duration.toMillis(interval);
const probeTimeoutMs = Duration.toMillis(probeTimeout);
const retryPolicy = Schedule.spaced(interval);
const requestUrl = new URL(input.path ?? "/", input.baseUrl).toString();
const client = yield* HttpClient.HttpClient;
const lastProbeFailure = yield* Ref.make<unknown>(null);
const lastProbeFailure = yield* Ref.make(
Option.none<{
readonly attempt: number;
readonly cause: unknown;
}>(),
);
let attempt = 0;
yield* Effect.logDebug("ssh.tunnel.httpReady.start", {
@@ -900,7 +906,7 @@ export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(functio
Effect.gen(function* () {
attempt += 1;
const responseOption = yield* effect.pipe(
Effect.timeoutOption(Duration.millis(probeTimeoutMs)),
Effect.timeoutOption(probeTimeout),
Effect.mapError(
(cause) =>
new SshReadinessError({
@@ -933,10 +939,13 @@ export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(functio
}),
),
Effect.tapError((cause) =>
Ref.set(lastProbeFailure, {
attempt,
cause: describeReadinessCause(cause),
}),
Ref.set(
lastProbeFailure,
Option.some({
attempt,
cause: describeReadinessCause(cause),
}),
),
),
),
),
@@ -953,7 +962,7 @@ export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(functio
cause,
}),
),
Effect.timeoutOption(Duration.millis(timeoutMs)),
Effect.timeoutOption(timeout),
);
return yield* Option.match(result, {
@@ -973,11 +982,11 @@ export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(functio
intervalMs,
probeTimeoutMs,
attempts: attempt,
lastFailure,
lastFailure: Option.getOrNull(lastFailure),
});
return yield* new SshReadinessError({
message: `Timed out waiting ${timeoutMs}ms for backend readiness at ${input.baseUrl}.`,
cause: lastFailure,
cause: Option.getOrUndefined(lastFailure),
});
}),
});
@@ -1236,7 +1245,7 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input:
yield* Effect.raceFirst(
waitForHttpReady({
baseUrl: input.httpBaseUrl,
timeoutMs: SSH_READY_TIMEOUT_MS,
timeout: SSH_READY_TIMEOUT,
}),
exitFailure,
).pipe(
@@ -1296,7 +1305,7 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input:
: child
.kill({
killSignal: "SIGTERM",
forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT_MS,
forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT,
})
.pipe(Effect.ignore),
),
@@ -1540,7 +1549,7 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
[
tunnelEntry.process.kill({
killSignal: "SIGTERM",
forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT_MS,
forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT,
}),
stopRemoteServer(
tunnelEntry.target,
@@ -1594,7 +1603,7 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
remotePort: entry.remotePort,
});
const readinessExit = yield* Effect.exit(
waitForHttpReady({ baseUrl: entry.httpBaseUrl, timeoutMs: 2_000 }),
waitForHttpReady({ baseUrl: entry.httpBaseUrl, timeout: Duration.seconds(2) }),
);
if (Exit.isSuccess(readinessExit)) {
yield* Effect.logDebug("ssh.environment.tunnel.reused", {