Merge origin/main into orchestrator v2

Port current mainline fixes onto the orchestrator v2 architecture.

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex authored and Julius Marminge committed 2026-07-20 16:07:59 +02:00
commit 309fcabe1f
880 files changed
+82635 -12286

No files matched your search

+3 -1
View File
@@ -1,5 +1,6 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { ThreadId } from "@t3tools/contracts";
import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -228,6 +229,7 @@ describe("AssetAccess", () => {
const fallbackResult = yield* issueAssetUrl({
resource: { _tag: "project-favicon", cwd: root },
});
expect(fallbackResult.relativeUrl.endsWith(`/${PROJECT_FAVICON_FALLBACK_MARKER}`)).toBe(true);
const fallbackSuffix = fallbackResult.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
const fallbackSeparatorIndex = fallbackSuffix.indexOf("/");
expect(
@@ -235,7 +237,7 @@ describe("AssetAccess", () => {
fallbackSuffix.slice(0, fallbackSeparatorIndex),
fallbackSuffix.slice(fallbackSeparatorIndex + 1),
),
).toEqual({ kind: "project-favicon-fallback" });
).toBeNull();
}).pipe(Effect.provide(testLayer)),
);
+4 -8
View File
@@ -19,6 +19,7 @@ import {
WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
} from "@t3tools/shared/filePreview";
import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";
import * as Clock from "effect/Clock";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -40,7 +41,6 @@ import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
export const ASSET_ROUTE_PREFIX = "/api/assets";
export const FALLBACK_PROJECT_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#6b728080" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" data-fallback="project-favicon"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2Z"/></svg>`;
const SIGNING_SECRET_NAME = "asset-access-signing-key";
const ASSET_TOKEN_TTL_MS = 60 * 60 * 1000;
@@ -91,9 +91,7 @@ const AssetClaimsJson = Schema.fromJsonString(AssetClaimsSchema);
const decodeAssetClaims = Schema.decodeUnknownOption(AssetClaimsJson);
const encodeAssetClaims = Schema.encodeSync(AssetClaimsJson);
export type ResolvedAsset =
| { readonly kind: "file"; readonly path: string }
| { readonly kind: "project-favicon-fallback" };
export type ResolvedAsset = { readonly kind: "file"; readonly path: string };
function decodeClaims(encodedPayload: string): AssetClaims | null {
try {
@@ -326,7 +324,7 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
relativePath,
expiresAt,
};
fileName = relativePath ? path.basename(relativePath) : "favicon.svg";
fileName = relativePath ? path.basename(relativePath) : PROJECT_FAVICON_FALLBACK_MARKER;
break;
}
}
@@ -391,9 +389,7 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
}
if (claims.kind === "project-favicon") {
if (claims.relativePath === null) {
return { kind: "project-favicon-fallback" } satisfies ResolvedAsset;
}
if (claims.relativePath === null) return null;
const faviconPath = yield* resolveCanonicalWorkspaceFileForRequest({
workspaceRoot: claims.workspaceRoot,
relativePath: claims.relativePath,
+10
View File
@@ -16,6 +16,8 @@ import {
EnvironmentOperationForbiddenError,
EnvironmentRequestInvalidError,
type EnvironmentRequestInvalidReason,
EnvironmentResourceNotFoundError,
type EnvironmentResourceNotFoundReason,
EnvironmentScopeRequiredError,
EnvironmentAuthenticatedAuth,
EnvironmentAuthenticatedPrincipal,
@@ -137,6 +139,14 @@ function failEnvironmentOperationForbidden(reason: "current_session_revoke_not_a
);
}
export function failEnvironmentNotFound(reason: EnvironmentResourceNotFoundReason) {
return currentEnvironmentTraceId.pipe(
Effect.flatMap((traceId) =>
Effect.fail(new EnvironmentResourceNotFoundError({ code: "not_found", reason, traceId })),
),
);
}
export function failEnvironmentInternal(reason: EnvironmentInternalErrorReason, error?: unknown) {
return Effect.gen(function* () {
const traceId = yield* currentEnvironmentTraceId;
+23 -6
View File
@@ -18,6 +18,9 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import { deriveServerPaths } from "../config.ts";
import { resolveServerConfig } from "./config.ts";
const deriveExplicitServerPaths = (baseDir: string, devUrl: URL | undefined) =>
deriveServerPaths(baseDir, devUrl, { baseDirIsExplicit: true });
const encodeDesktopBootstrap = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
const makeDesktopBootstrap = (
@@ -60,7 +63,10 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
Effect.gen(function* () {
const { join } = yield* Path.Path;
const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-env-base");
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:5173"));
const derivedPaths = yield* deriveExplicitServerPaths(
baseDir,
new URL("http://127.0.0.1:5173"),
);
const resolved = yield* resolveServerConfig(
{
mode: Option.none(),
@@ -119,6 +125,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
tailscaleServeEnabled: false,
tailscaleServePort: 443,
});
assert.equal(resolved.stateDir, join(baseDir, "userdata"));
}),
);
@@ -126,7 +133,10 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
Effect.gen(function* () {
const { join } = yield* Path.Path;
const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-flags-base");
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
const derivedPaths = yield* deriveExplicitServerPaths(
baseDir,
new URL("http://127.0.0.1:4173"),
);
const resolved = yield* resolveServerConfig(
{
mode: Option.some("web"),
@@ -185,6 +195,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
tailscaleServeEnabled: true,
tailscaleServePort: 8443,
});
assert.equal(resolved.dbPath, join(baseDir, "userdata", "state.sqlite"));
}),
);
@@ -199,7 +210,10 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
tailscaleServePort: 443,
}),
);
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
const derivedPaths = yield* deriveExplicitServerPaths(
baseDir,
new URL("http://127.0.0.1:4173"),
);
const resolved = yield* resolveServerConfig(
{
@@ -396,7 +410,10 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
tailscaleServePort: 443,
}),
);
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
const derivedPaths = yield* deriveExplicitServerPaths(
baseDir,
new URL("http://127.0.0.1:4173"),
);
const resolved = yield* resolveServerConfig(
{
@@ -461,7 +478,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-settings-" });
const derivedPaths = yield* deriveServerPaths(baseDir, undefined);
const derivedPaths = yield* deriveExplicitServerPaths(baseDir, undefined);
yield* fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true });
yield* fs.writeFileString(
derivedPaths.settingsPath,
@@ -529,7 +546,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
Effect.gen(function* () {
const { join } = yield* Path.Path;
const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-headless-base");
const derivedPaths = yield* deriveServerPaths(baseDir, undefined);
const derivedPaths = yield* deriveExplicitServerPaths(baseDir, undefined);
const resolved = yield* resolveServerConfig(
{
+11 -7
View File
@@ -31,7 +31,9 @@ export const hostFlag = Flag.string("host").pipe(
Flag.optional,
);
export const baseDirFlag = Flag.string("base-dir").pipe(
Flag.withDescription("Base directory path (equivalent to T3CODE_HOME)."),
Flag.withDescription(
"Explicit T3 Code data directory; runtime state is stored under userdata (equivalent to T3CODE_HOME).",
),
Flag.optional,
);
export const devUrlFlag = Flag.string("dev-url").pipe(
@@ -259,19 +261,21 @@ export const resolveServerConfig = (
resolveOptionPrecedence(normalizedFlags.devUrl, Option.fromUndefinedOr(env.devUrl)),
() => undefined,
);
const explicitBaseDir = resolveOptionPrecedence(
normalizedFlags.baseDir,
Option.fromUndefinedOr(env.t3Home),
).pipe(Option.filter((value) => value.trim().length > 0));
const baseDir = yield* resolveBaseDir(
Option.getOrUndefined(
resolveOptionPrecedence(
normalizedFlags.baseDir,
Option.fromUndefinedOr(env.t3Home),
Option.fromUndefinedOr(bootstrap?.t3Home),
),
resolveOptionPrecedence(explicitBaseDir, Option.fromUndefinedOr(bootstrap?.t3Home)),
),
);
const rawCwd = Option.getOrElse(normalizedFlags.cwd, () => process.cwd());
const cwd = path.resolve(yield* expandHomePath(rawCwd.trim()));
yield* fs.makeDirectory(cwd, { recursive: true });
const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, devUrl);
const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, devUrl, {
baseDirIsExplicit: Option.isSome(explicitBaseDir),
});
yield* ServerConfig.ensureServerDirectories(derivedPaths);
const persistedObservabilitySettings = yield* loadPersistedObservabilitySettings(
derivedPaths.settingsPath,
+54 -1
View File
@@ -1,14 +1,44 @@
import * as RelayClient from "@t3tools/shared/relayClient";
import { assert, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Console from "effect/Console";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Logger from "effect/Logger";
import * as Option from "effect/Option";
import * as References from "effect/References";
import * as Terminal from "effect/Terminal";
import { acquireRelayClientForLink, reportCloudDisconnectResults } from "./connect.ts";
import {
acquireRelayClientForLink,
formatHeadlessAuthorizationPrompt,
formatRelayClientReady,
headlessSessionConfig,
isPublishAgentActivityEnabledValue,
recoverBootServiceOffer,
reportCloudDisconnectResults,
} from "./connect.ts";
it("explains how to complete headless authorization", () => {
assert.equal(
formatHeadlessAuthorizationPrompt("https://example.test/connect"),
[
"Headless authorization",
"Open this URL on a device with a browser:",
" https://example.test/connect",
"",
"After signing in, return here and enter the code shown in your browser.",
].join("\n"),
);
});
it("formats relay readiness without printing its installation path", () => {
assert.equal(formatRelayClientReady("2026.5.2"), "✓ Relay client ready · cloudflared 2026.5.2");
});
const readHeadlessSessionConfig = (env: Record<string, string>) =>
headlessSessionConfig.pipe(Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env }))));
const managedExecutable = {
status: "available",
@@ -17,6 +47,22 @@ const managedExecutable = {
version: RelayClient.CLOUDFLARED_VERSION,
} as const;
it.effect("detects headless operation from individual SSH config values", () =>
Effect.gen(function* () {
assert.isFalse(yield* readHeadlessSessionConfig({}));
assert.isFalse(yield* readHeadlessSessionConfig({ CI: "true" }));
assert.isTrue(yield* readHeadlessSessionConfig({ SSH_CONNECTION: "client server" }));
assert.isTrue(yield* readHeadlessSessionConfig({ SSH_TTY: "/dev/pts/1" }));
}),
);
it.effect("treats cancelling optional background setup as a successful skip", () =>
Effect.gen(function* () {
const result = yield* recoverBootServiceOffer(Effect.fail(new Terminal.QuitError({})));
assert.isFalse(result);
}),
);
it.effect("does not install the relay client when the user declines the managed download", () =>
Effect.gen(function* () {
let installCalls = 0;
@@ -153,3 +199,10 @@ it.effect("keeps disconnect causes in structured logs and out of console warning
),
);
});
it("treats only the literal 'true' as publish-enabled", () => {
assert.equal(isPublishAgentActivityEnabledValue("true"), true);
assert.equal(isPublishAgentActivityEnabledValue("false"), false);
assert.equal(isPublishAgentActivityEnabledValue(null), false);
assert.equal(isPublishAgentActivityEnabledValue("TRUE"), false);
});
+354 -54
View File
@@ -6,9 +6,12 @@ import {
} from "@t3tools/contracts";
import { RelayOkResponse } from "@t3tools/contracts/relay";
import * as RelayClient from "@t3tools/shared/relayClient";
import * as Terminal from "effect/Terminal";
import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
import * as Cause from "effect/Cause";
import * as Config from "effect/Config";
import * as Console from "effect/Console";
import * as Crypto from "effect/Crypto";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
@@ -16,6 +19,7 @@ import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as References from "effect/References";
import * as Schema from "effect/Schema";
import { Command, Flag, GlobalFlag, Prompt } from "effect/unstable/cli";
import {
FetchHttpClient,
@@ -25,15 +29,23 @@ import {
} from "effect/unstable/http";
import * as HttpApiClient from "effect/unstable/httpapi/HttpApiClient";
import packageJson from "../../package.json" with { type: "json" };
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import * as BootService from "../cloud/bootService.ts";
import * as CliState from "../cloud/CliState.ts";
import * as CliTokenManager from "../cloud/CliTokenManager.ts";
import { CLOUD_LINKED_USER_ID, RELAY_URL_SECRET } from "../cloud/config.ts";
import {
CLOUD_LINKED_USER_ID,
PUBLISH_AGENT_ACTIVITY_SECRET,
RELAY_URL_SECRET,
} from "../cloud/config.ts";
import { relayUrlConfig } from "../cloud/publicConfig.ts";
import { headlessRelayClientTracingLayer } from "../cloud/relayTracing.ts";
import * as ServerConfig from "../config.ts";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import * as ExternalLauncher from "../process/externalLauncher.ts";
import * as ProcessRunner from "../processRunner.ts";
import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
@@ -42,16 +54,100 @@ const jsonFlag = Flag.boolean("json").pipe(
Flag.withDefault(false),
);
const isCloudCliTokenManagerError = Schema.is(CliTokenManager.CloudCliTokenManagerError);
const headlessFlag = Flag.boolean("headless").pipe(
Flag.withDescription("Authorize without a local browser using out-of-band OAuth."),
Flag.withDefault(false),
);
/**
* Inside an SSH session there is no local browser to complete the loopback
* OAuth callback, so out-of-band OAuth is the only flow that can work.
*/
export const headlessSessionConfig = Config.all({
sshConnection: Config.string("SSH_CONNECTION").pipe(Config.option),
sshTty: Config.string("SSH_TTY").pipe(Config.option),
}).pipe(
Config.map(({ sshConnection, sshTty }) => Option.isSome(sshConnection) || Option.isSome(sshTty)),
);
const promptForOutOfBandOAuthCode = Effect.fn("cloud.cli.prompt_for_out_of_band_oauth_code")(
function* ({ authorizeUrl, validate }: CliTokenManager.OutOfBandOAuthPromptInput) {
yield* Console.log(formatHeadlessAuthorizationPrompt(authorizeUrl));
return yield* Prompt.run(Prompt.text({ message: "Authorization code", validate }));
},
);
export function formatHeadlessAuthorizationPrompt(authorizeUrl: string): string {
return [
"Headless authorization",
"Open this URL on a device with a browser:",
` ${authorizeUrl}`,
"",
"After signing in, return here and enter the code shown in your browser.",
].join("\n");
}
/** Returns the connected account identity, if the flow could determine one. */
const authorizeCli = Effect.fn("cloud.cli.authorize")(function* (options: {
readonly headless: boolean;
}) {
const tokens = yield* CliTokenManager.CloudCliTokenManager;
const useOutOfBandOAuth = options.headless || (yield* headlessSessionConfig);
if (!useOutOfBandOAuth) {
const authorization = yield* tokens.get;
if (authorization._tag === "Authorized") {
return authorization.token.identity ?? null;
}
yield* Console.log("\nHeadless mode enabled. A new authorization link is ready below.");
}
// A stored credential whose refresh fails (revoked, expired grant) must
// fall through to a fresh out-of-band authorization, not dead-end the command.
const existing = yield* tokens.getExisting.pipe(
Effect.catchTag("CloudCliCredentialRefreshError", () =>
Console.log(
"The stored T3 Connect credential could not be refreshed; signing in again.",
).pipe(Effect.as(Option.none())),
),
);
if (Option.isSome(existing)) {
return existing.value.identity ?? null;
}
const { token, identity } = yield* CliTokenManager.outOfBandOAuthLogin(
promptForOutOfBandOAuthCode,
).pipe(
Effect.mapError((cause) =>
// Ctrl-C / EOF at the prompt is a QuitError; let it propagate so the CLI
// cancels quietly instead of dumping an authorization error.
Terminal.isQuitError(cause) || isCloudCliTokenManagerError(cause)
? cause
: new CliTokenManager.CloudCliAuthorizationError({ cause }),
),
);
yield* tokens.store(token);
return identity;
});
function bytesToString(value: Uint8Array): string {
return new TextDecoder().decode(value);
}
function stringToBytes(value: string): Uint8Array {
return new TextEncoder().encode(value);
}
export function isPublishAgentActivityEnabledValue(value: string | null): boolean {
return value === "true";
}
interface CloudCliStatus {
readonly desired: boolean;
readonly authenticated: boolean;
readonly linked: boolean;
readonly cloudUserId: string | null;
readonly relayUrl: string | null;
readonly publishAgentActivity: boolean;
readonly relayClient: RelayClient.RelayClientStatus;
}
@@ -104,6 +200,7 @@ function formatCloudStatus(status: CloudCliStatus, options?: { readonly json?: b
` Authorization: ${status.authenticated ? "stored credential" : "missing"}`,
` Environment link: ${provisioned}`,
` Relay: ${status.relayUrl ?? "not provisioned"}`,
` Publish agent activity: ${status.publishAgentActivity ? "enabled" : "disabled"}`,
...formatRelayClientStatus(status.relayClient),
...(nextStep ? ["", `Next: ${nextStep}`] : []),
].join("\n");
@@ -299,6 +396,21 @@ const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: {
if (options.clearAuthorization) {
const tokens = yield* CliTokenManager.CloudCliTokenManager;
yield* tokens.clear;
// uninstall itself no-ops when nothing is installed (and on non-Linux),
// so no status pre-check that could mask a real removal failure.
const bootService = yield* BootService.BootService;
yield* bootService.uninstall.pipe(
Effect.tap((removed) =>
removed ? Console.log("Removed the T3 Code background service.") : Effect.void,
),
Effect.catchTag("BootServiceUnsupportedError", () => Effect.succeed(false)),
Effect.catch((error) =>
Console.warn(`Could not remove the background service: ${error.message}`).pipe(
Effect.as(false),
),
),
);
}
yield* reportCloudDisconnectResults({
@@ -312,7 +424,7 @@ const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: {
}
});
const runCloudCommand = <A, E>(
const runCloudCommand = Effect.fn("cloud.cli.run_cloud_command")(function* <A, E>(
flags: { readonly baseDir: Option.Option<string> },
run: Effect.Effect<
A,
@@ -321,6 +433,8 @@ const runCloudCommand = <A, E>(
| CliTokenManager.CloudCliTokenManager
| RelayClient.RelayClient
| EnvironmentAuth.EnvironmentAuth
| BootService.BootService
| Crypto.Crypto
| FileSystem.FileSystem
| HttpClient.HttpClient
| Prompt.Environment
@@ -330,37 +444,79 @@ const runCloudCommand = <A, E>(
options?: {
readonly quietLogs?: boolean;
},
) =>
Effect.gen(function* () {
const logLevel = yield* GlobalFlag.LogLevel;
const config = yield* resolveCliAuthConfig(flags, logLevel);
const minimumLogLevel = options?.quietLogs ? "Error" : config.logLevel;
const runtimeLayer = Layer.mergeAll(
ServerSecretStore.layer,
CliTokenManager.layer.pipe(Layer.provide(ServerSecretStore.layer)),
RelayClient.layerCloudflared({ baseDir: config.baseDir }),
EnvironmentAuth.runtimeLayer,
ServerEnvironment.layer,
headlessRelayClientTracingLayer,
).pipe(
Layer.provideMerge(FetchHttpClient.layer),
Layer.provideMerge(ServerConfig.layer(config)),
Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
) {
const logLevel = yield* GlobalFlag.LogLevel;
const config = yield* resolveCliAuthConfig(flags, logLevel);
const minimumLogLevel = options?.quietLogs ? "Error" : config.logLevel;
const runtimeLayer = Layer.mergeAll(
ServerSecretStore.layer,
CliTokenManager.layer.pipe(
Layer.provide(ServerSecretStore.layer),
Layer.provide(ExternalLauncher.layer),
),
RelayClient.layerCloudflared({ baseDir: config.baseDir }),
EnvironmentAuth.runtimeLayer,
ServerEnvironment.layer,
BootService.layer({
baseDir: config.baseDir,
logsDir: config.logsDir,
cliVersion: packageJson.version,
}).pipe(Layer.provide(ProcessRunner.layer)),
headlessRelayClientTracingLayer,
).pipe(
Layer.provideMerge(FetchHttpClient.layer),
Layer.provideMerge(ServerConfig.layer(config)),
Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
);
return yield* run.pipe(Effect.provide(runtimeLayer));
});
const connectedAs = (identity: string | null): string => (identity ? ` as ${identity}` : "");
export function formatRelayClientReady(version: string): string {
return `✓ Relay client ready · cloudflared ${version}`;
}
const linkEnvironmentForConnect = Effect.fn("cloud.cli.link_environment")(function* (options: {
readonly headless: boolean;
readonly publishOnly?: boolean;
}) {
const publishOnly = options.publishOnly ?? false;
if (!publishOnly) {
const relayClient = yield* RelayClient.RelayClient;
const installed = yield* acquireRelayClientForLink(
relayClient,
confirmRelayClientInstall,
reportRelayClientInstallProgress,
);
return yield* run.pipe(Effect.provide(runtimeLayer));
});
if (Option.isNone(installed)) {
yield* Console.log("T3 Connect setup cancelled. The relay client was not installed.");
return null;
}
yield* Console.log(formatRelayClientReady(installed.value.version));
}
const identity = yield* authorizeCli(options);
yield* CliState.setCliDesiredCloudLink(true, publishOnly ? "publish_only" : "managed");
if (publishOnly) {
const secrets = yield* ServerSecretStore.ServerSecretStore;
yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, stringToBytes("true"));
}
return { identity } as const;
});
const connectLoginCommand = Command.make("login", {
...projectLocationFlags,
headless: headlessFlag,
}).pipe(
Command.withDescription("Authorize the T3 Connect CLI without enabling remote access."),
Command.withHandler((flags) =>
runCloudCommand(
flags,
Effect.gen(function* () {
const tokens = yield* CliTokenManager.CloudCliTokenManager;
yield* tokens.get;
yield* Console.log("Signed in to T3 Connect.");
yield* Console.log("T3 Connect\n");
const identity = yield* authorizeCli(flags);
yield* Console.log(`✓ Signed in${connectedAs(identity)}`);
}),
),
),
@@ -368,32 +524,28 @@ const connectLoginCommand = Command.make("login", {
const connectLinkCommand = Command.make("link", {
...projectLocationFlags,
headless: headlessFlag,
publishOnly: Flag.boolean("publish-only").pipe(
Flag.withDescription(
"Link to publish agent activity only — no managed tunnel. Reach this environment out of band (e.g. Tailscale).",
),
Flag.withDefault(false),
),
}).pipe(
Command.withDescription("Authorize this environment for T3 Connect on next start."),
Command.withHandler((flags) =>
runCloudCommand(
flags,
Effect.gen(function* () {
const relayClient = yield* RelayClient.RelayClient;
const installed = yield* acquireRelayClientForLink(
relayClient,
confirmRelayClientInstall,
reportRelayClientInstallProgress,
);
if (Option.isNone(installed)) {
yield* Console.log("T3 Connect setup cancelled. The relay client was not installed.");
return;
yield* Console.log("T3 Connect\n");
const linked = yield* linkEnvironmentForConnect(flags);
if (linked) {
yield* Console.log(
flags.publishOnly
? `✓ Authorized${connectedAs(linked.identity)}\n\nNext\n Start T3 to publish agent activity (no managed tunnel).`
: `✓ Authorized${connectedAs(linked.identity)}\n\nNext\n Start the server with \`t3 serve\` to make this machine reachable.`,
);
}
yield* Console.log(
`Using relay client ${installed.value.version} from ${installed.value.executablePath}.`,
);
const tokens = yield* CliTokenManager.CloudCliTokenManager;
yield* tokens.get;
yield* CliState.setCliDesiredCloudLink(true);
yield* Console.log(
"This T3 environment will be available through T3 Connect the next time T3 starts.",
);
}),
),
),
@@ -411,22 +563,27 @@ const connectStatusCommand = Command.make("status", {
const secrets = yield* ServerSecretStore.ServerSecretStore;
const relayClient = yield* RelayClient.RelayClient;
const tokens = yield* CliTokenManager.CloudCliTokenManager;
const [desired, authenticated, cloudUserId, relayUrl, executable] = yield* Effect.all(
[
CliState.readCliDesiredCloudLink,
tokens.hasCredential,
secrets.get(CLOUD_LINKED_USER_ID),
secrets.get(RELAY_URL_SECRET),
relayClient.resolve,
],
{ concurrency: "unbounded" },
);
const [desired, authenticated, cloudUserId, relayUrl, publishAgentActivity, executable] =
yield* Effect.all(
[
CliState.readCliDesiredCloudLink,
tokens.hasCredential,
secrets.get(CLOUD_LINKED_USER_ID),
secrets.get(RELAY_URL_SECRET),
secrets.get(PUBLISH_AGENT_ACTIVITY_SECRET),
relayClient.resolve,
],
{ concurrency: "unbounded" },
);
const status: CloudCliStatus = {
desired,
authenticated,
linked: Option.isSome(cloudUserId),
cloudUserId: Option.isSome(cloudUserId) ? bytesToString(cloudUserId.value) : null,
relayUrl: Option.isSome(relayUrl) ? bytesToString(relayUrl.value) : null,
publishAgentActivity: isPublishAgentActivityEnabledValue(
Option.isSome(publishAgentActivity) ? bytesToString(publishAgentActivity.value) : null,
),
relayClient: executable,
};
yield* Console.log(formatCloudStatus(status, { json: flags.json }));
@@ -438,6 +595,76 @@ const connectStatusCommand = Command.make("status", {
),
);
const connectPublishCommand = Command.make("publish", {
...projectLocationFlags,
disable: Flag.boolean("disable").pipe(
Flag.withDescription("Stop publishing agent activity to your mobile clients."),
Flag.withDefault(false),
),
}).pipe(
Command.withDescription(
"Toggle publishing agent activity (push notifications and Live Activities) to your mobile clients.",
),
Command.withHandler((flags) =>
runCloudCommand(
flags,
Effect.gen(function* () {
const secrets = yield* ServerSecretStore.ServerSecretStore;
const tokens = yield* CliTokenManager.CloudCliTokenManager;
const enabled = !flags.disable;
yield* secrets.set(
PUBLISH_AGENT_ACTIVITY_SECRET,
stringToBytes(enabled ? "true" : "false"),
);
if (!enabled) {
// If enabling scheduled a publish-only link that hasn't been
// provisioned yet, disabling must cancel it too — otherwise the next
// start still links an environment whose only purpose was publishing.
// A pending managed link is left alone; it exists for the tunnel.
const linkedNow = Option.isSome(yield* secrets.get(CLOUD_LINKED_USER_ID));
if (!linkedNow && (yield* CliState.readCliDesiredLinkMode) === "publish_only") {
yield* CliState.setCliDesiredCloudLink(false);
yield* Console.log("Cancelled the pending publish-only T3 Connect link.");
}
yield* Console.log("Publishing agent activity disabled.");
return;
}
yield* Console.log("Publishing agent activity enabled.");
const linked = Option.isSome(yield* secrets.get(CLOUD_LINKED_USER_ID));
if (linked) {
return;
}
// Publishing needs the relay to know this environment belongs to you.
// Establish a tunnel-free publish-only link automatically so signing in
// is all it takes — the mobile client can still reach the environment
// out of band without T3 Connect.
if (!(yield* tokens.hasCredential)) {
yield* Console.log(
"Run `t3 connect login` first so this environment can be authorized to publish.",
);
return;
}
// A link may already be desired (e.g. `t3 connect link` before the
// server's first start). Never downgrade it: a desired managed link
// also covers publishing, so only request a publish-only link when no
// link is pending at all.
if (yield* CliState.readCliDesiredCloudLink) {
yield* Console.log(
"A T3 Connect link is already pending. Start T3 to finish provisioning it; publishing starts once it links.",
);
return;
}
yield* CliState.setCliDesiredCloudLink(true, "publish_only");
yield* Console.log(
"Restart T3 to finish authorizing this environment to publish (no managed tunnel is created).",
);
}),
),
),
);
const connectUnlinkCommand = Command.make("unlink", {
...projectLocationFlags,
}).pipe(
@@ -456,11 +683,84 @@ const connectLogoutCommand = Command.make("logout", {
),
);
export const connectCommand = Command.make("connect").pipe(
Command.withDescription("Manage headless T3 Connect access."),
const offerBootService = Effect.gen(function* () {
const bootService = yield* BootService.BootService;
const { supported, installed, current } = yield* bootService.status;
if (!supported) {
// Don't prompt for something that can only fail; background setup is
// Linux/systemd-only for now.
return false;
}
if (installed && current) {
yield* Console.log("T3 Code is already set up to run in the background on this machine.");
return true;
}
const wanted = yield* Prompt.run(
Prompt.confirm({
message: installed
? "The installed T3 Code background service is from an older setup. Update it now?"
: "Run T3 Code in the background whenever this machine boots? " +
"It stays reachable through T3 Connect even after you log out.",
initial: true,
}),
);
if (!wanted) {
return false;
}
const plan = yield* bootService.install;
yield* Console.log(`Background service installed. Logs: ${plan.logPath}`);
return true;
});
export const recoverBootServiceOffer = <R>(
offer: Effect.Effect<boolean, BootService.BootServiceError | Terminal.QuitError, R>,
) =>
offer.pipe(
Effect.catchTags({
QuitError: () => Effect.succeed(false),
BootServiceUnsupportedError: (error) =>
Console.log(`Skipping background setup: ${error.message}`).pipe(Effect.as(false)),
BootServiceCommandError: (error) =>
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
BootServiceInstallError: (error) =>
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
}),
);
export const connectCommand = Command.make("connect", {
...projectLocationFlags,
headless: headlessFlag,
}).pipe(
Command.withDescription("Set up T3 Connect for this machine."),
Command.withHandler((flags) =>
runCloudCommand(
flags,
Effect.gen(function* () {
yield* Console.log("T3 Connect\n");
const linked = yield* linkEnvironmentForConnect(flags);
if (!linked) {
return;
}
// Show which account was linked so an unexpected identity (an
// authorization code for a different account) is visible before the
// machine is brought online.
yield* Console.log(`✓ Connected${connectedAs(linked.identity)}`);
// Connect itself already succeeded; a boot-service failure must not
// fail the command, just tell the user what happened and move on.
const background = yield* recoverBootServiceOffer(offerBootService);
yield* Console.log(
background
? "\n✓ Background service ready\n\nT3 Code will stay reachable after you log out."
: "\nNext\n Start the server with `t3 serve` to make this machine reachable.",
);
}),
),
),
Command.withSubcommands([
connectLoginCommand,
connectLinkCommand,
connectPublishCommand,
connectStatusCommand,
connectUnlinkCommand,
connectLogoutCommand,
+5
View File
@@ -520,6 +520,10 @@ const projectRemoveCommand = Command.make("remove", {
project: Argument.string("project").pipe(
Argument.withDescription("Project id or workspace root to remove."),
),
force: Flag.boolean("force").pipe(
Flag.withDescription("Delete the project and all of its threads."),
Flag.withDefault(false),
),
}).pipe(
Command.withDescription("Remove a project."),
Command.withHandler((flags) =>
@@ -542,6 +546,7 @@ const projectRemoveCommand = Command.make("remove", {
type: "project.delete",
commandId: CommandId.make(yield* projectCommandUuid),
projectId: project.id,
force: flags.force,
});
return `Removed project ${project.id} (${project.title}).`;
}),
+23
View File
@@ -56,4 +56,27 @@ it.layer(NodeServices.layer)("CliState", (it) => {
}
}).pipe(Effect.provide(makeTestLayer())),
);
it.effect("round-trips the desired link mode and defaults legacy links to managed", () =>
Effect.gen(function* () {
const secrets = yield* ServerSecretStore.ServerSecretStore;
assert.equal(yield* CliState.readCliDesiredLinkMode, "managed");
yield* CliState.setCliDesiredCloudLink(true, "publish_only");
assert.isTrue(yield* CliState.readCliDesiredCloudLink);
assert.equal(yield* CliState.readCliDesiredLinkMode, "publish_only");
yield* CliState.setCliDesiredCloudLink(true, "managed");
assert.equal(yield* CliState.readCliDesiredLinkMode, "managed");
// A pre-existing link persisted the literal "true"; treat it as managed.
yield* secrets.set(CliState.CLOUD_CLI_DESIRED_LINK_SECRET, new TextEncoder().encode("true"));
assert.isTrue(yield* CliState.readCliDesiredCloudLink);
assert.equal(yield* CliState.readCliDesiredLinkMode, "managed");
yield* CliState.setCliDesiredCloudLink(false);
assert.equal(yield* CliState.readCliDesiredLinkMode, "managed");
}).pipe(Effect.provide(makeTestLayer())),
);
});
+26 -2
View File
@@ -14,19 +14,43 @@ import {
export const CLOUD_CLI_DESIRED_LINK_SECRET = "cloud-cli-desired-link";
const TRUE_BYTES = new TextEncoder().encode("true");
// "managed" provisions a Cloudflare tunnel (default, legacy value "true").
// "publish_only" links the environment to the relay purely to publish agent
// activity — no tunnel, no relay-advertised endpoint — so activity can flow to
// mobile clients even when they reach the environment out of band (Tailscale,
// direct pairing) without T3 Connect.
export type CliDesiredLinkMode = "managed" | "publish_only";
const MANAGED_BYTES = new TextEncoder().encode("managed");
const PUBLISH_ONLY_BYTES = new TextEncoder().encode("publish_only");
export const readCliDesiredCloudLink = Effect.gen(function* () {
const secrets = yield* ServerSecretStore.ServerSecretStore;
return Option.isSome(yield* secrets.get(CLOUD_CLI_DESIRED_LINK_SECRET));
});
export const readCliDesiredLinkMode = Effect.gen(function* () {
const secrets = yield* ServerSecretStore.ServerSecretStore;
const value = yield* secrets.get(CLOUD_CLI_DESIRED_LINK_SECRET);
if (Option.isNone(value)) {
return "managed" as CliDesiredLinkMode;
}
// Legacy links stored the literal "true" and are always managed.
return new TextDecoder().decode(value.value) === "publish_only"
? ("publish_only" as CliDesiredLinkMode)
: ("managed" as CliDesiredLinkMode);
});
export const setCliDesiredCloudLink = Effect.fn("cloud.cli_state.set_desired")(function* (
desired: boolean,
mode: CliDesiredLinkMode = "managed",
) {
const secrets = yield* ServerSecretStore.ServerSecretStore;
if (desired) {
yield* secrets.set(CLOUD_CLI_DESIRED_LINK_SECRET, TRUE_BYTES);
yield* secrets.set(
CLOUD_CLI_DESIRED_LINK_SECRET,
mode === "publish_only" ? PUBLISH_ONLY_BYTES : MANAGED_BYTES,
);
} else {
yield* secrets.remove(CLOUD_CLI_DESIRED_LINK_SECRET);
}
@@ -0,0 +1,264 @@
import { readConnectAuthorizeRequest } from "@t3tools/shared/connectAuth";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Crypto from "effect/Crypto";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Schema from "effect/Schema";
import * as Terminal from "effect/Terminal";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
import * as CliTokenManager from "./CliTokenManager.ts";
import type { OutOfBandOAuthPromptInput } from "./CliTokenManager.ts";
// pk_test_<base64 of "clerk.example.test$">
const TEST_ENV = {
T3CODE_CLERK_PUBLISHABLE_KEY: "pk_test_Y2xlcmsuZXhhbXBsZS50ZXN0JA==",
T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: "oauth_client_test",
T3CODE_HOSTED_APP_URL: "https://hosted.example.test",
};
interface RecordedTokenRequest {
readonly url: string;
readonly params: URLSearchParams;
}
// A JWT whose payload claims { email: "[email protected]" } (signature is not
// verified — the CLI only reads the claim to display the connected account).
const TestIdTokenHeaderJson = Schema.fromJsonString(Schema.Struct({ alg: Schema.Literal("none") }));
const TestIdTokenPayloadJson = Schema.fromJsonString(Schema.Struct({ email: Schema.String }));
const encodeTestIdTokenHeader = Schema.encodeSync(TestIdTokenHeaderJson);
const encodeTestIdTokenPayload = Schema.encodeSync(TestIdTokenPayloadJson);
const idTokenWithEmail = (() => {
const header = Encoding.encodeBase64Url(encodeTestIdTokenHeader({ alg: "none" }));
const payload = Encoding.encodeBase64Url(
encodeTestIdTokenPayload({ email: "[email protected]" }),
);
return `${header}.${payload}.`;
})();
const TestTokenResponseJson = Schema.fromJsonString(
Schema.Struct({
access_token: Schema.String,
refresh_token: Schema.String,
id_token: Schema.String,
expires_in: Schema.Number,
token_type: Schema.String,
}),
);
const encodeTestTokenResponse = Schema.encodeSync(TestTokenResponseJson);
const makeTokenEndpointLayer = (
requests: Array<RecordedTokenRequest>,
options?: { readonly idToken?: string },
) =>
Layer.succeed(
HttpClient.HttpClient,
HttpClient.make((request) =>
Effect.sync(() => {
const body =
request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "";
requests.push({ url: request.url, params: new URLSearchParams(body) });
return HttpClientResponse.fromWeb(
request,
new Response(
encodeTestTokenResponse({
access_token: "access-token-1",
refresh_token: "refresh-token-1",
id_token: options?.idToken ?? idTokenWithEmail,
expires_in: 3600,
token_type: "bearer",
}),
{ status: 200, headers: { "content-type": "application/json" } },
),
);
}),
),
);
const provideTestEnv = Effect.provide(
ConfigProvider.layer(ConfigProvider.fromEnv({ env: TEST_ENV })),
);
const isAuthorizationError = Schema.is(CliTokenManager.CloudCliAuthorizationError);
class PromptRejectedError extends Schema.TaggedErrorClass<PromptRejectedError>()(
"PromptRejectedError",
{ message: Schema.String },
) {}
it("formats loopback authorization with a headless-host fallback", () => {
assert.equal(
CliTokenManager.formatLoopbackAuthorizationPrompt("https://clerk.example.test/authorize"),
[
"Open this URL to authorize T3 Connect:",
" https://clerk.example.test/authorize",
"",
"Press \u001b[1mEnter\u001b[22m to open it in your browser.",
"No browser on this device? Press \u001b[1mH\u001b[22m to switch to headless mode.",
].join("\n"),
);
});
const makeTestTerminal = (queue: Queue.Queue<Terminal.UserInput>) =>
Terminal.make({
columns: Effect.succeed(80),
rows: Effect.succeed(24),
readInput: Effect.succeed(Queue.asDequeue(queue)),
readLine: Effect.never,
display: () => Effect.void,
});
const userInput = (name: string): Terminal.UserInput => ({
input: Option.some(name),
key: { name, ctrl: false, meta: false, shift: name !== name.toLowerCase() },
});
it.effect("opens the browser on Enter and switches the active flow on H", () =>
Effect.gen(function* () {
const queue = yield* Queue.make<Terminal.UserInput>();
yield* Queue.offerAll(queue, [userInput("enter"), userInput("H")]);
const opened: Array<string> = [];
const result = yield* CliTokenManager.waitForLoopbackAuthorization({
authorizationUrl: "https://clerk.example.test/authorize",
callback: Effect.never,
terminal: makeTestTerminal(queue),
launchBrowser: (url) =>
Effect.sync(() => {
opened.push(url);
}),
});
assert.deepEqual(opened, ["https://clerk.example.test/authorize"]);
assert.deepEqual(result, { _tag: "HeadlessRequested" });
}),
);
it.effect("finishes normally when the browser callback wins", () =>
Effect.gen(function* () {
const queue = yield* Queue.make<Terminal.UserInput>();
const callback = yield* Deferred.make<string>();
yield* Deferred.succeed(callback, "clerk-code-123");
const result = yield* CliTokenManager.waitForLoopbackAuthorization({
authorizationUrl: "https://clerk.example.test/authorize",
callback: Deferred.await(callback),
terminal: makeTestTerminal(queue),
launchBrowser: () => Effect.die("browser launch should not run"),
});
assert.deepEqual(result, { _tag: "AuthorizationCode", code: "clerk-code-123" });
}),
);
it.layer(NodeServices.layer)("CliTokenManager.outOfBandOAuthLogin", (it) => {
it.effect("prints a hosted authorize URL and exchanges the out-of-band code with PKCE", () =>
Effect.gen(function* () {
const requests: Array<RecordedTokenRequest> = [];
let seenAuthorizeUrl = "";
const { token, identity } = yield* CliTokenManager.outOfBandOAuthLogin(
({ authorizeUrl, validate }: OutOfBandOAuthPromptInput) =>
Effect.gen(function* () {
seenAuthorizeUrl = authorizeUrl;
const request = readConnectAuthorizeRequest(new URL(authorizeUrl));
assert.isNotNull(request);
return yield* validate(`clerk-code-123.${request!.state}`).pipe(
Effect.mapError((message) => new PromptRejectedError({ message })),
);
}),
).pipe(Effect.provide(makeTokenEndpointLayer(requests)), provideTestEnv);
const authorizeUrl = new URL(seenAuthorizeUrl);
assert.equal(authorizeUrl.origin, "https://hosted.example.test");
assert.equal(authorizeUrl.pathname, "/connect");
const request = readConnectAuthorizeRequest(authorizeUrl);
assert.isNotNull(request);
assert.match(request!.state, /^[A-Za-z0-9_-]{22}$/);
assert.equal(token.accessToken, "access-token-1");
assert.equal(token.refreshToken, "refresh-token-1");
assert.equal(token.identity, "[email protected]");
// The id_token's email claim is surfaced so connect can show the account.
assert.equal(identity, "[email protected]");
assert.lengthOf(requests, 1);
const exchange = requests[0]!;
assert.equal(exchange.url, "https://clerk.example.test/oauth/token");
assert.equal(exchange.params.get("grant_type"), "authorization_code");
assert.equal(exchange.params.get("code"), "clerk-code-123");
assert.equal(
exchange.params.get("redirect_uri"),
"https://hosted.example.test/connect/callback",
);
assert.equal(exchange.params.get("client_id"), "oauth_client_test");
// The verifier must hash to the challenge advertised in the authorize URL.
const verifier = exchange.params.get("code_verifier");
assert.isNotNull(verifier);
const crypto = yield* Crypto.Crypto;
const digest = yield* crypto.digest("SHA-256", new TextEncoder().encode(verifier!));
assert.equal(Encoding.encodeBase64Url(digest), request!.challenge);
}),
);
it.effect("rejects out-of-band codes whose state does not match the request", () =>
Effect.gen(function* () {
const requests: Array<RecordedTokenRequest> = [];
const validationErrors: Array<string> = [];
const result = yield* CliTokenManager.outOfBandOAuthLogin(
({ validate }: OutOfBandOAuthPromptInput) =>
validate("clerk-code-123.wrong-state").pipe(
Effect.tapError((message) => Effect.sync(() => validationErrors.push(message))),
Effect.mapError((message) => new PromptRejectedError({ message })),
),
).pipe(Effect.provide(makeTokenEndpointLayer(requests)), provideTestEnv, Effect.flip);
assert.lengthOf(requests, 0);
assert.lengthOf(validationErrors, 1);
assert.include(validationErrors[0], "different connect request");
assert.instanceOf(result, PromptRejectedError);
}),
);
it.effect("ignores an id_token whose claims are not valid JSON", () =>
Effect.gen(function* () {
const requests: Array<RecordedTokenRequest> = [];
const malformedIdToken = `header.${Encoding.encodeBase64Url("not-json")}.signature`;
const { identity } = yield* CliTokenManager.outOfBandOAuthLogin(
({ authorizeUrl }: OutOfBandOAuthPromptInput) => {
const request = readConnectAuthorizeRequest(new URL(authorizeUrl));
assert.isNotNull(request);
return Effect.succeed(`clerk-code-123.${request!.state}`);
},
).pipe(
Effect.provide(makeTokenEndpointLayer(requests, { idToken: malformedIdToken })),
provideTestEnv,
);
assert.isNull(identity);
assert.lengthOf(requests, 1);
}),
);
it.effect("fails without touching the token endpoint when the prompt returns garbage", () =>
Effect.gen(function* () {
const requests: Array<RecordedTokenRequest> = [];
const result = yield* CliTokenManager.outOfBandOAuthLogin(() =>
Effect.succeed("not-a-connect-code"),
).pipe(Effect.provide(makeTokenEndpointLayer(requests)), provideTestEnv, Effect.flip);
assert.lengthOf(requests, 0);
assert.isTrue(isAuthorizationError(result));
}),
);
});
+284 -69
View File
@@ -3,6 +3,7 @@ import * as NodeHttp from "node:http";
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
import * as Clock from "effect/Clock";
import * as Cause from "effect/Cause";
import * as Console from "effect/Console";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
@@ -12,8 +13,10 @@ import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as Terminal from "effect/Terminal";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
@@ -21,19 +24,105 @@ import * as HttpRouter from "effect/unstable/http/HttpRouter";
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
import {
buildConnectAuthorizeRequestUrl,
buildConnectClerkAuthorizeUrl,
checkConnectAuthCode,
connectCallbackUrl,
} from "@t3tools/shared/connectAuth";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import { cloudCliOAuthConfig, type CloudCliOAuthConfig } from "./publicConfig.ts";
import * as ExternalLauncher from "../process/externalLauncher.ts";
import {
cloudCliOAuthConfig,
hostedAppUrlConfig,
type CloudCliOAuthConfig,
} from "./publicConfig.ts";
import { renderLoopbackAuthorizationCompleteHtml } from "./cliAuthHtml.ts";
const CLOUD_CLI_OAUTH_TOKEN_SECRET = "cloud-cli-oauth-token";
const CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT = Duration.minutes(10);
const CLOUD_CLI_OAUTH_REFRESH_EARLY_MS = Duration.toMillis(Duration.minutes(5));
const boldTerminalText = (value: string): string => `\u001b[1m${value}\u001b[22m`;
export function formatLoopbackAuthorizationPrompt(authorizationUrl: string): string {
return [
"Open this URL to authorize T3 Connect:",
` ${authorizationUrl}`,
"",
`Press ${boldTerminalText("Enter")} to open it in your browser.`,
`No browser on this device? Press ${boldTerminalText("H")} to switch to headless mode.`,
].join("\n");
}
export type LoopbackAuthorizationResult =
| { readonly _tag: "AuthorizationCode"; readonly code: string }
| { readonly _tag: "HeadlessRequested" };
const readLoopbackAuthorizationAction = Effect.fn(
"cloud.cli_token.read_loopback_authorization_action",
)(function* (input: Queue.Dequeue<Terminal.UserInput, Cause.Done>) {
while (true) {
const event = yield* Queue.take(input).pipe(Effect.mapError(() => new Terminal.QuitError({})));
const keyName = event.key.name.toLowerCase();
if (!event.key.ctrl && !event.key.meta && keyName === "h") {
return "headless" as const;
}
if (keyName === "enter" || keyName === "return") {
return "open-browser" as const;
}
}
});
export const waitForLoopbackAuthorization = Effect.fn(
"cloud.cli_token.wait_for_loopback_authorization",
)(function* <E, R>(input: {
readonly authorizationUrl: string;
readonly callback: Effect.Effect<string, E, R>;
readonly terminal: Terminal.Terminal;
readonly launchBrowser: (
url: string,
) => Effect.Effect<void, ExternalLauncher.ExternalLauncherError>;
}) {
return yield* Effect.scoped(
Effect.gen(function* () {
const terminalInput = yield* input.terminal.readInput;
while (true) {
const result = yield* Effect.raceFirst(
input.callback.pipe(
Effect.map(
(code): LoopbackAuthorizationResult => ({ _tag: "AuthorizationCode", code }),
),
),
readLoopbackAuthorizationAction(terminalInput),
);
if (typeof result !== "string") {
return result;
}
if (result === "headless") {
return { _tag: "HeadlessRequested" } as const;
}
yield* input
.launchBrowser(input.authorizationUrl)
.pipe(
Effect.catch(() =>
Console.warn(
`Could not open a browser on this device. Open the URL above manually, or press ${boldTerminalText("H")} to switch to headless mode.`,
),
),
);
}
}),
);
});
const PersistedToken = Schema.Struct({
accessToken: Schema.String,
refreshToken: Schema.String,
expiresAtEpochMs: Schema.Number,
identity: Schema.optional(Schema.String),
});
type PersistedToken = typeof PersistedToken.Type;
export type PersistedToken = typeof PersistedToken.Type;
const PersistedTokenJson = Schema.fromJsonString(PersistedToken);
const decodePersistedToken = Schema.decodeUnknownEffect(PersistedTokenJson);
@@ -42,10 +131,39 @@ const encodePersistedToken = Schema.encodeEffect(PersistedTokenJson);
const OAuthTokenResponse = Schema.Struct({
access_token: Schema.String,
refresh_token: Schema.optional(Schema.String),
id_token: Schema.optional(Schema.String),
expires_in: Schema.Number,
token_type: Schema.String,
});
const OidcIdentityClaimsJson = Schema.fromJsonString(
Schema.Struct({
email: Schema.optional(Schema.String),
preferred_username: Schema.optional(Schema.String),
sub: Schema.optional(Schema.String),
}),
);
const decodeOidcIdentityClaimsJson = Schema.decodeUnknownOption(OidcIdentityClaimsJson);
/**
* Best-effort read of the `email` (or fallback) claim from an OIDC id_token.
* Only used to show the operator which account they linked, so a malformed
* token degrades to "no identity" rather than an error.
*/
function idTokenIdentity(idToken: string | undefined): string | null {
if (!idToken) return null;
const payload = idToken.split(".")[1];
if (!payload) return null;
const decoded = Encoding.decodeBase64UrlString(payload);
if (decoded._tag !== "Success") return null;
const claims = decodeOidcIdentityClaimsJson(decoded.success);
if (Option.isNone(claims)) return null;
for (const value of [claims.value.email, claims.value.preferred_username, claims.value.sub]) {
if (typeof value === "string" && value.length > 0) return value;
}
return null;
}
export class CloudCliCredentialRemovalError extends Schema.TaggedErrorClass<CloudCliCredentialRemovalError>()(
"CloudCliCredentialRemovalError",
{ cause: Schema.Defect() },
@@ -103,18 +221,18 @@ export type CloudCliTokenManagerError = typeof CloudCliTokenManagerError.Type;
export class CloudCliTokenManager extends Context.Service<
CloudCliTokenManager,
{
readonly get: Effect.Effect<PersistedToken, CloudCliTokenManagerError>;
readonly get: Effect.Effect<
| { readonly _tag: "Authorized"; readonly token: PersistedToken }
| { readonly _tag: "HeadlessRequested" },
CloudCliTokenManagerError | Terminal.QuitError
>;
readonly getExisting: Effect.Effect<Option.Option<PersistedToken>, CloudCliTokenManagerError>;
readonly hasCredential: Effect.Effect<boolean, CloudCliTokenManagerError>;
readonly store: (token: PersistedToken) => Effect.Effect<void, CloudCliTokenManagerError>;
readonly clear: Effect.Effect<void, CloudCliTokenManagerError>;
}
>()("t3/cloud/CliTokenManager/CloudCliTokenManager") {}
const wrapError =
<WrappedError extends CloudCliTokenManagerError>(makeError: (cause: unknown) => WrappedError) =>
<A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, WrappedError, R> =>
effect.pipe(Effect.mapError(makeError));
function stringToBytes(value: string): Uint8Array {
return new TextEncoder().encode(value);
}
@@ -123,10 +241,101 @@ function bytesToString(value: Uint8Array): string {
return new TextDecoder().decode(value);
}
export const make = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const exchangeToken = Effect.fn("cloud.cli_token.exchange")(function* (
metadata: Pick<CloudCliOAuthConfig, "tokenEndpoint">,
params: Record<string, string>,
) {
const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk);
const response = yield* HttpClientRequest.post(metadata.tokenEndpoint).pipe(
HttpClientRequest.bodyUrlParams(params),
httpClient.execute,
Effect.flatMap(HttpClientResponse.schemaBodyJson(OAuthTokenResponse)),
);
const now = yield* Clock.currentTimeMillis;
const identity = idTokenIdentity(response.id_token);
return {
token: {
accessToken: response.access_token,
refreshToken: response.refresh_token ?? params.refresh_token ?? "",
expiresAtEpochMs: now + response.expires_in * 1_000,
...(identity === null ? {} : { identity }),
} satisfies PersistedToken,
identity,
};
});
const makePkceRequest = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const verifier = Encoding.encodeBase64Url(yield* crypto.randomBytes(32));
const challenge = Encoding.encodeBase64Url(
yield* crypto.digest("SHA-256", new TextEncoder().encode(verifier)),
);
const state = Encoding.encodeBase64Url(yield* crypto.randomBytes(16));
return { verifier, challenge, state };
});
export interface OutOfBandOAuthPromptInput {
readonly authorizeUrl: string;
readonly validate: (value: string) => Effect.Effect<string, string>;
}
/**
* Out-of-band OAuth for machines without a local browser (SSH). The user
* opens the hosted /connect URL elsewhere, signs in, and enters the displayed
* code in this terminal. The PKCE verifier never leaves this process, so the
* authorization code is useless to an observer, and the state bundled into
* the blob preserves the loopback flow's CSRF check.
*/
export const outOfBandOAuthLogin = Effect.fn("cloud.cli_token.out_of_band_oauth_login")(function* <
E,
R,
>(promptForCode: (input: OutOfBandOAuthPromptInput) => Effect.Effect<string, E, R>) {
const metadata = yield* cloudCliOAuthConfig;
const hostedAppUrl = yield* hostedAppUrlConfig;
const { verifier, challenge, state } = yield* makePkceRequest;
const authorizationCode = yield* promptForCode({
authorizeUrl: buildConnectAuthorizeRequestUrl({ hostedAppUrl, state, challenge }),
validate: (value) => {
const checked = checkConnectAuthCode(value, state);
return typeof checked === "string" ? Effect.fail(checked) : Effect.succeed(value);
},
}).pipe(
// Clerk authorization codes expire on this horizon anyway; matching the
// loopback flow's timeout turns an abandoned prompt into a clear error.
Effect.timeout(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT),
Effect.catchTag("TimeoutError", (cause) =>
Effect.fail(new CloudCliAuthorizationTimeoutError({ cause })),
),
);
// promptForCode is caller-supplied, so re-check the returned value rather
// than trusting that the prompt ran validate.
const authCode = checkConnectAuthCode(authorizationCode, state);
if (typeof authCode === "string") {
return yield* new CloudCliAuthorizationError({ cause: authCode });
}
return yield* exchangeToken(metadata, {
grant_type: "authorization_code",
code: authCode.code,
redirect_uri: connectCallbackUrl(hostedAppUrl),
client_id: metadata.clientId,
code_verifier: verifier,
});
});
export const make = Effect.gen(function* () {
// Capture exactly the services the login/refresh flows need at build time
// (matching the behavior before the out-of-band flow captured the instances), not
// the whole ambient context.
const crypto = yield* Crypto.Crypto;
const httpClient = yield* HttpClient.HttpClient;
const services = Context.make(Crypto.Crypto, crypto).pipe(
Context.add(HttpClient.HttpClient, httpClient),
);
const secrets = yield* ServerSecretStore.ServerSecretStore;
const terminal = yield* Terminal.Terminal;
const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
const semaphore = yield* Semaphore.make(1);
const persist = Effect.fn("cloud.cli_token.persist")(function* (token: PersistedToken) {
const encoded = yield* encodePersistedToken(token);
@@ -136,7 +345,7 @@ export const make = Effect.gen(function* () {
const clear = secrets
.remove(CLOUD_CLI_OAUTH_TOKEN_SECRET)
.pipe(wrapError((cause) => new CloudCliCredentialRemovalError({ cause })));
.pipe(Effect.mapError((cause) => new CloudCliCredentialRemovalError({ cause })));
const read = Effect.fn("cloud.cli_token.read")(function* () {
const encoded = yield* secrets.get(CLOUD_CLI_OAUTH_TOKEN_SECRET);
@@ -144,39 +353,21 @@ export const make = Effect.gen(function* () {
return Option.some(yield* decodePersistedToken(bytesToString(encoded.value)));
});
const exchangeToken = Effect.fn("cloud.cli_token.exchange")(function* (
metadata: CloudCliOAuthConfig,
params: Record<string, string>,
) {
const response = yield* HttpClientRequest.post(metadata.tokenEndpoint).pipe(
HttpClientRequest.bodyUrlParams(params),
httpClient.execute,
Effect.flatMap(HttpClientResponse.schemaBodyJson(OAuthTokenResponse)),
);
const now = yield* Clock.currentTimeMillis;
return {
accessToken: response.access_token,
refreshToken: response.refresh_token ?? params.refresh_token ?? "",
expiresAtEpochMs: now + response.expires_in * 1_000,
} satisfies PersistedToken;
});
const refresh = Effect.fn("cloud.cli_token.refresh")(function* (token: PersistedToken) {
const metadata = yield* cloudCliOAuthConfig;
return yield* exchangeToken(metadata, {
const { token: refreshed } = yield* exchangeToken(metadata, {
grant_type: "refresh_token",
refresh_token: token.refreshToken,
client_id: metadata.clientId,
});
return refreshed.identity === undefined && token.identity !== undefined
? { ...refreshed, identity: token.identity }
: refreshed;
});
const login = Effect.fn("cloud.cli_token.login")(function* () {
const metadata = yield* cloudCliOAuthConfig;
const verifier = Encoding.encodeBase64Url(yield* crypto.randomBytes(32));
const challenge = Encoding.encodeBase64Url(
yield* crypto.digest("SHA-256", new TextEncoder().encode(verifier)),
);
const state = yield* crypto.randomUUIDv4;
const { verifier, challenge, state } = yield* makePkceRequest;
const callback = yield* Deferred.make<string>();
const callbackRoute = HttpRouter.add(
"GET",
@@ -191,14 +382,7 @@ export const make = Effect.gen(function* () {
});
}
yield* Deferred.succeed(callback, code);
return yield* HttpServerResponse.html`
<html>
<body style="font-family: sans-serif; text-align: center; margin-top: 50px;">
<h1>T3 Connect authorization complete</h1>
<p>You can close this window and return to your terminal.</p>
</body>
</html>
`;
return HttpServerResponse.html(renderLoopbackAuthorizationCompleteHtml());
}),
);
yield* HttpRouter.serve(callbackRoute, {
@@ -214,32 +398,37 @@ export const make = Effect.gen(function* () {
),
Layer.build,
);
const authorizationUrl = new URL(metadata.authorizationEndpoint);
authorizationUrl.searchParams.set("client_id", metadata.clientId);
authorizationUrl.searchParams.set("redirect_uri", metadata.redirectUri);
authorizationUrl.searchParams.set("response_type", "code");
authorizationUrl.searchParams.set("scope", metadata.scopes.join(" "));
authorizationUrl.searchParams.set("state", state);
authorizationUrl.searchParams.set("code_challenge", challenge);
authorizationUrl.searchParams.set("code_challenge_method", "S256");
yield* Console.log(`Open this URL to authorize T3 Connect:\n${authorizationUrl.toString()}\n`);
const code = yield* Deferred.await(callback).pipe(
Effect.timeout(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT),
Effect.catchTag("TimeoutError", (cause) =>
Effect.fail(
new CloudCliAuthorizationTimeoutError({
cause,
}),
const authorizationUrl = buildConnectClerkAuthorizeUrl({
authorizationEndpoint: metadata.authorizationEndpoint,
clientId: metadata.clientId,
redirectUri: metadata.redirectUri,
scopes: metadata.scopes,
state,
challenge,
});
yield* Console.log(formatLoopbackAuthorizationPrompt(authorizationUrl));
const authorization = yield* waitForLoopbackAuthorization({
authorizationUrl,
callback: Deferred.await(callback).pipe(
Effect.timeout(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT),
Effect.catchTag("TimeoutError", (cause) =>
Effect.fail(new CloudCliAuthorizationTimeoutError({ cause })),
),
),
);
return yield* exchangeToken(metadata, {
terminal,
launchBrowser: externalLauncher.launchBrowser,
});
if (authorization._tag === "HeadlessRequested") {
return authorization;
}
const { token } = yield* exchangeToken(metadata, {
grant_type: "authorization_code",
code,
code: authorization.code,
redirect_uri: metadata.redirectUri,
client_id: metadata.clientId,
code_verifier: verifier,
});
return { _tag: "Authorized", token } as const;
});
const getExistingNoLock = Effect.fn("cloud.cli_token.get_existing_no_lock")(function* () {
@@ -253,24 +442,50 @@ export const make = Effect.gen(function* () {
});
const getExisting = semaphore.withPermits(1)(
getExistingNoLock().pipe(wrapError((cause) => new CloudCliCredentialRefreshError({ cause }))),
getExistingNoLock().pipe(
Effect.mapError((cause) => new CloudCliCredentialRefreshError({ cause })),
Effect.provide(services),
),
);
const hasCredential = semaphore.withPermits(1)(
read().pipe(
Effect.map(Option.isSome),
wrapError((cause) => new CloudCliCredentialReadError({ cause })),
Effect.mapError((cause) => new CloudCliCredentialReadError({ cause })),
),
);
const get = semaphore.withPermits(1)(
Effect.gen(function* () {
const token = yield* getExistingNoLock();
return Option.isSome(token)
? token.value
: yield* Effect.scoped(login()).pipe(Effect.flatMap(persist));
}).pipe(wrapError((cause) => new CloudCliAuthorizationError({ cause }))),
// A stored credential that can't be read or refreshed (corrupt, revoked,
// expired grant) must fall through to a fresh login rather than dead-end
// the command — authorizeCli applies the same fallback to out-of-band
// authorization.
const token = yield* getExistingNoLock().pipe(
Effect.orElseSucceed(() => Option.none<PersistedToken>()),
);
if (Option.isSome(token)) {
return { _tag: "Authorized", token: token.value } as const;
}
const authorization = yield* Effect.scoped(login());
return authorization._tag === "Authorized"
? ({ _tag: "Authorized", token: yield* persist(authorization.token) } as const)
: authorization;
}).pipe(
Effect.mapError((cause) =>
Terminal.isQuitError(cause) ? cause : new CloudCliAuthorizationError({ cause }),
),
Effect.provide(services),
),
);
const store = Effect.fn("cloud.cli_token.store")(function* (token: PersistedToken) {
yield* semaphore.withPermits(1)(
persist(token).pipe(
Effect.asVoid,
Effect.mapError((cause) => new CloudCliAuthorizationError({ cause })),
),
);
});
return CloudCliTokenManager.of({ get, getExisting, hasCredential, clear });
return CloudCliTokenManager.of({ get, getExisting, hasCredential, store, clear });
});
export const layer = Layer.effect(CloudCliTokenManager, make);
+529
View File
@@ -0,0 +1,529 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import {
HostProcessArguments,
HostProcessExecutablePath,
HostProcessPlatform,
} from "@t3tools/shared/hostProcess";
import * as ProcessRunner from "../processRunner.ts";
import * as BootService from "./bootService.ts";
const isUnsupportedError = Schema.is(BootService.BootServiceUnsupportedError);
const isCommandError = Schema.is(BootService.BootServiceCommandError);
interface RecordedCommand {
readonly command: string;
readonly args: ReadonlyArray<string>;
}
const makeRecordingRunnerLayer = (
commands: Array<RecordedCommand>,
options?: {
readonly failCommand?: string;
readonly failWhen?: (command: string, args: ReadonlyArray<string>) => boolean;
},
) =>
Layer.succeed(
ProcessRunner.ProcessRunner,
ProcessRunner.ProcessRunner.of({
run: (input) =>
Effect.sync(() => {
assert.isUndefined(input.env);
commands.push({ command: input.command, args: input.args });
const failed =
input.command === options?.failCommand ||
options?.failWhen?.(input.command, input.args) === true;
return {
stdout: "",
stderr: failed ? `${input.command} exploded` : "",
code: ChildProcessSpawner.ExitCode(failed ? 1 : 0),
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
};
}),
}),
);
const makeHost = (entry: string): BootService.BootServiceHost => ({
execPath: "/usr/local/bin/node",
cliEntryPath: entry,
});
const provideHostRefs = (home: string, platform: NodeJS.Platform = "linux") =>
Effect.provide(
Layer.mergeAll(
Layer.succeed(HostProcessPlatform, platform),
ConfigProvider.layer(ConfigProvider.fromEnv({ env: { HOME: home } })),
),
);
const makeTestContext = Effect.fn("test.makeTestContext")(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-boot-service-test-" });
// A real file for the stable-entry cases so status can confirm the entry
// point exists.
const stableEntry = path.join(root, "bin.mjs");
yield* fs.writeFileString(stableEntry, "#!/usr/bin/env node\n");
return {
fs,
path,
dirs: {
home: root,
baseDir: path.join(root, ".t3"),
logsDir: path.join(root, ".t3", "userdata", "logs"),
stableEntry,
},
};
});
it("renders a systemd unit with absolute paths and append-mode logging", () => {
const unit = BootService.renderBootServiceUnit({
nodePath: "/usr/local/bin/node",
t3EntryPath: "/home/theo/.t3/runtime/versions/0.0.27/node_modules/t3/dist/bin.mjs",
baseDir: "/home/theo/.t3",
logPath: "/home/theo/.t3/userdata/logs/boot-service.log",
unitPath: "/home/theo/.config/systemd/user/t3code.service",
});
assert.equal(
unit,
[
"[Unit]",
"Description=T3 Code server (T3 Connect)",
"StartLimitIntervalSec=300",
"StartLimitBurst=5",
"",
"[Service]",
"Type=simple",
"WorkingDirectory=%h",
"Environment=T3CODE_HOME=/home/theo/.t3",
"ExecStart=/usr/local/bin/node /home/theo/.t3/runtime/versions/0.0.27/node_modules/t3/dist/bin.mjs serve",
"Restart=always",
"RestartSec=5",
"StandardOutput=append:/home/theo/.t3/userdata/logs/boot-service.log",
"StandardError=append:/home/theo/.t3/userdata/logs/boot-service.log",
"",
"[Install]",
"WantedBy=default.target",
"",
].join("\n"),
);
});
it("quotes systemd values containing spaces and escapes percent specifiers", () => {
assert.equal(BootService.quoteSystemdValue("/plain/path"), "/plain/path");
assert.equal(BootService.quoteSystemdValue("/home/me/T3 Data"), '"/home/me/T3 Data"');
assert.equal(BootService.quoteSystemdValue("/opt/100%cpu"), "/opt/100%%cpu");
const unit = BootService.renderBootServiceUnit({
nodePath: "/home/me/my tools/node",
t3EntryPath: "/home/me/T3 Data/bin.mjs",
baseDir: "/home/me/T3 Data",
logPath: "/home/me/100%logs/boot.log",
unitPath: "/home/me/.config/systemd/user/t3code.service",
});
assert.include(unit, 'ExecStart="/home/me/my tools/node" "/home/me/T3 Data/bin.mjs" serve');
assert.include(unit, 'Environment=T3CODE_HOME="/home/me/T3 Data"');
// append: paths take the rest of the line literally (spaces are fine,
// quoting is not), but % still goes through specifier expansion.
assert.include(unit, "StandardOutput=append:/home/me/100%%logs/boot.log");
assert.include(unit, "StandardError=append:/home/me/100%%logs/boot.log");
});
it("flags package-manager cache entry points as ephemeral", () => {
assert.isTrue(
BootService.isEphemeralCacheEntry("/home/theo/.npm/_npx/abc123/node_modules/t3/dist/bin.mjs"),
);
assert.isTrue(
BootService.isEphemeralCacheEntry("C:\\Users\\theo\\AppData\\npm-cache\\_npx\\abc\\bin.mjs"),
);
assert.isTrue(
BootService.isEphemeralCacheEntry(
"/home/theo/.cache/pnpm/dlx/abc/node_modules/t3/dist/bin.mjs",
),
);
assert.isTrue(
BootService.isEphemeralCacheEntry("/home/theo/.bun/install/cache/[email protected]/dist/bin.mjs"),
);
assert.isFalse(BootService.isEphemeralCacheEntry("/usr/local/lib/node_modules/t3/dist/bin.mjs"));
assert.isFalse(
BootService.isEphemeralCacheEntry(
"/home/theo/dev/pnpm/dlx-tools/t3/node_modules/t3/dist/bin.mjs",
),
);
assert.isFalse(
BootService.isEphemeralCacheEntry(
"/home/theo/.t3/runtime/versions/0.0.27/node_modules/t3/dist/bin.mjs",
),
);
});
it.layer(NodeServices.layer)("BootService", (it) => {
it.effect("installs the unit, enables the service, and enables linger", () =>
Effect.gen(function* () {
const { dirs, fs, path } = yield* makeTestContext();
const commands: Array<RecordedCommand> = [];
const service = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost(dirs.stableEntry),
}).pipe(Effect.provide(makeRecordingRunnerLayer(commands)), provideHostRefs(dirs.home));
const plan = yield* service.install;
// A stable entry point is reused directly — no npm install.
assert.equal(plan.t3EntryPath, dirs.stableEntry);
assert.deepEqual(
commands.map((entry) => [entry.command, ...entry.args].join(" ")),
[
"systemctl --user daemon-reload",
"systemctl --user enable t3code.service",
// restart (not enable --now) so repairing a stale unit replaces a
// running process instead of leaving the old one until reboot.
"systemctl --user restart t3code.service",
"loginctl enable-linger",
],
);
const unitPath = path.join(dirs.home, ".config", "systemd", "user", "t3code.service");
const unit = yield* fs.readFileString(unitPath);
assert.include(unit, `ExecStart=/usr/local/bin/node ${dirs.stableEntry} serve`);
assert.include(unit, `Environment=T3CODE_HOME=${dirs.baseDir}`);
const status = yield* service.status;
assert.isTrue(status.supported);
assert.isTrue(status.installed);
assert.isTrue(status.current);
const removed = yield* service.uninstall;
assert.isTrue(removed);
assert.isFalse(yield* fs.exists(unitPath));
const statusAfter = yield* service.status;
assert.isFalse(statusAfter.installed);
const removedAgain = yield* service.uninstall;
assert.isFalse(removedAgain);
}),
);
it.effect("pins a runtime via npm install when running from the npx cache", () =>
Effect.gen(function* () {
const { dirs, fs, path } = yield* makeTestContext();
const commands: Array<RecordedCommand> = [];
const service = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost("/home/theo/.npm/_npx/abc/node_modules/t3/dist/bin.mjs"),
}).pipe(Effect.provide(makeRecordingRunnerLayer(commands)), provideHostRefs(dirs.home));
const plan = yield* service.install;
const runtimeDir = path.join(dirs.baseDir, "runtime", "versions", "0.0.27");
assert.equal(
plan.t3EntryPath,
path.join(runtimeDir, "node_modules", "t3", "dist", "bin.mjs"),
);
assert.deepEqual(commands[0], {
command: "npm",
args: ["install", "--prefix", runtimeDir, "--no-fund", "--no-audit", "[email protected]"],
});
// Success is recorded via a sentinel so interrupted installs re-run.
assert.isTrue(yield* fs.exists(path.join(runtimeDir, ".install-complete")));
}),
);
it.effect("reinstalls a pinned runtime when its entry point is missing", () =>
Effect.gen(function* () {
const { dirs, fs, path } = yield* makeTestContext();
const commands: Array<RecordedCommand> = [];
const service = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost("/home/theo/.npm/_npx/abc/node_modules/t3/dist/bin.mjs"),
}).pipe(Effect.provide(makeRecordingRunnerLayer(commands)), provideHostRefs(dirs.home));
const plan = yield* service.install;
yield* fs.makeDirectory(path.dirname(plan.t3EntryPath), { recursive: true });
yield* fs.writeFileString(plan.t3EntryPath, "#!/usr/bin/env node\n");
yield* fs.remove(plan.t3EntryPath);
commands.length = 0;
yield* service.install;
assert.isTrue(commands.some(({ command }) => command === "npm"));
}),
);
it.effect("reads executable metadata from host process references", () =>
Effect.gen(function* () {
const { dirs } = yield* makeTestContext();
const commands: Array<RecordedCommand> = [];
const service = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
}).pipe(
Effect.provide(makeRecordingRunnerLayer(commands)),
provideHostRefs(dirs.home),
Effect.provideService(HostProcessExecutablePath, "/opt/node/bin/node"),
Effect.provideService(HostProcessArguments, ["/opt/node/bin/node", dirs.stableEntry]),
);
const plan = yield* service.install;
assert.equal(plan.nodePath, "/opt/node/bin/node");
assert.equal(plan.t3EntryPath, dirs.stableEntry);
}),
);
it.effect("cleans up and fails when the pinned runtime install fails", () =>
Effect.gen(function* () {
const { dirs, fs, path } = yield* makeTestContext();
const commands: Array<RecordedCommand> = [];
const service = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost("/home/theo/.npm/_npx/abc/node_modules/t3/dist/bin.mjs"),
}).pipe(
Effect.provide(makeRecordingRunnerLayer(commands, { failCommand: "npm" })),
provideHostRefs(dirs.home),
);
const error = yield* service.install.pipe(Effect.flip);
assert.isTrue(isCommandError(error));
const runtimeDir = path.join(dirs.baseDir, "runtime", "versions", "0.0.27");
// The half-installed tree must not be reused by the next attempt.
assert.isFalse(yield* fs.exists(runtimeDir));
assert.isFalse(yield* fs.exists(path.join(runtimeDir, ".install-complete")));
}),
);
it.effect("reports an installed-but-stale unit so connect can offer a repair", () =>
Effect.gen(function* () {
const { dirs, fs, path } = yield* makeTestContext();
const commands: Array<RecordedCommand> = [];
const service = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost(dirs.stableEntry),
}).pipe(Effect.provide(makeRecordingRunnerLayer(commands)), provideHostRefs(dirs.home));
const unitDir = path.join(dirs.home, ".config", "systemd", "user");
yield* fs.makeDirectory(unitDir, { recursive: true });
yield* fs.writeFileString(
path.join(unitDir, "t3code.service"),
"[Service]\nExecStart=/old/node /old/t3 serve\n",
);
const status = yield* service.status;
assert.isTrue(status.supported);
assert.isTrue(status.installed);
assert.isFalse(status.current);
}),
);
it.effect("reports a current unit as stale when its entry point is gone", () =>
Effect.gen(function* () {
const { dirs, fs } = yield* makeTestContext();
const commands: Array<RecordedCommand> = [];
const service = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost(dirs.stableEntry),
}).pipe(Effect.provide(makeRecordingRunnerLayer(commands)), provideHostRefs(dirs.home));
yield* service.install;
assert.isTrue((yield* service.status).current);
// The pinned runtime (or global bin) was deleted to reclaim space; the
// unit still matches byte-for-byte but would crashloop at boot.
yield* fs.remove(dirs.stableEntry);
const status = yield* service.status;
assert.isTrue(status.installed);
assert.isFalse(status.current);
}),
);
it.effect("fails on non-Linux platforms without touching the filesystem", () =>
Effect.gen(function* () {
const { dirs, fs, path } = yield* makeTestContext();
const commands: Array<RecordedCommand> = [];
const service = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost("/usr/local/lib/node_modules/t3/dist/bin.mjs"),
}).pipe(
Effect.provide(makeRecordingRunnerLayer(commands)),
provideHostRefs(dirs.home, "darwin"),
);
const error = yield* service.install.pipe(Effect.flip);
assert.isTrue(isUnsupportedError(error));
assert.lengthOf(commands, 0);
assert.isFalse(
yield* fs.exists(path.join(dirs.home, ".config", "systemd", "user", "t3code.service")),
);
const status = yield* service.status;
assert.isFalse(status.supported);
assert.isFalse(status.installed);
}),
);
it.effect("removes the unit file when an activation step fails", () =>
Effect.gen(function* () {
const { dirs, fs, path } = yield* makeTestContext();
const commands: Array<RecordedCommand> = [];
const service = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost("/usr/local/lib/node_modules/t3/dist/bin.mjs"),
}).pipe(
Effect.provide(makeRecordingRunnerLayer(commands, { failCommand: "loginctl" })),
provideHostRefs(dirs.home),
);
const error = yield* service.install.pipe(Effect.flip);
assert.isTrue(isCommandError(error));
// A leftover unit would make the next connect report "already set up"
// even though linger never happened.
assert.isFalse(
yield* fs.exists(path.join(dirs.home, ".config", "systemd", "user", "t3code.service")),
);
const status = yield* service.status;
assert.isFalse(status.installed);
assert.isTrue(
commands.some(
({ command, args }) =>
command === "systemctl" && args.join(" ") === "--user disable --now t3code.service",
),
);
}),
);
it.effect("restores the previous unit when a repair cannot activate", () =>
Effect.gen(function* () {
const { dirs, fs, path } = yield* makeTestContext();
const initialCommands: Array<RecordedCommand> = [];
const initialService = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost(dirs.stableEntry),
}).pipe(
Effect.provide(makeRecordingRunnerLayer(initialCommands)),
provideHostRefs(dirs.home),
);
yield* initialService.install;
const unitPath = path.join(dirs.home, ".config", "systemd", "user", "t3code.service");
const previousUnit = yield* fs.readFileString(unitPath);
const replacementEntry = path.join(dirs.home, "replacement-bin.mjs");
yield* fs.writeFileString(replacementEntry, "#!/usr/bin/env node\n");
const repairCommands: Array<RecordedCommand> = [];
const repairService = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.28",
host: makeHost(replacementEntry),
}).pipe(
Effect.provide(makeRecordingRunnerLayer(repairCommands, { failCommand: "loginctl" })),
provideHostRefs(dirs.home),
);
const error = yield* repairService.install.pipe(Effect.flip);
assert.isTrue(isCommandError(error));
assert.equal(yield* fs.readFileString(unitPath), previousUnit);
assert.isTrue(
repairCommands.some(
({ command, args }) =>
command === "systemctl" && args.join(" ") === "--user restart t3code.service",
),
);
}),
);
it.effect("keeps the unit when stopping it during uninstall fails", () =>
Effect.gen(function* () {
const { dirs, fs, path } = yield* makeTestContext();
const installCommands: Array<RecordedCommand> = [];
const installedService = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost(dirs.stableEntry),
}).pipe(
Effect.provide(makeRecordingRunnerLayer(installCommands)),
provideHostRefs(dirs.home),
);
yield* installedService.install;
const uninstallCommands: Array<RecordedCommand> = [];
const failingService = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost(dirs.stableEntry),
}).pipe(
Effect.provide(
makeRecordingRunnerLayer(uninstallCommands, {
failWhen: (command, args) =>
command === "systemctl" && args.includes("disable") && args.includes("--now"),
}),
),
provideHostRefs(dirs.home),
);
const error = yield* failingService.uninstall.pipe(Effect.flip);
assert.isTrue(isCommandError(error));
assert.isTrue(
yield* fs.exists(path.join(dirs.home, ".config", "systemd", "user", "t3code.service")),
);
}),
);
it.effect("appends failed steps to the boot-service log", () =>
Effect.gen(function* () {
const { dirs, fs, path } = yield* makeTestContext();
const commands: Array<RecordedCommand> = [];
const service = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost("/usr/local/lib/node_modules/t3/dist/bin.mjs"),
}).pipe(
Effect.provide(makeRecordingRunnerLayer(commands, { failCommand: "systemctl" })),
provideHostRefs(dirs.home),
);
const error = yield* service.install.pipe(Effect.flip);
assert.isTrue(isCommandError(error));
if (!isCommandError(error)) return;
assert.equal(error.exitCode, 1);
assert.equal(error.stderrLength, "systemctl exploded".length);
const logPath = path.join(dirs.logsDir, "boot-service.log");
assert.isTrue(yield* fs.exists(logPath));
assert.include(yield* fs.readFileString(logPath), "exit code 1");
}),
);
});
+452
View File
@@ -0,0 +1,452 @@
import * as Context from "effect/Context";
import * as Config from "effect/Config";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import {
HostProcessArguments,
HostProcessExecutablePath,
HostProcessPlatform,
} from "@t3tools/shared/hostProcess";
import * as ProcessRunner from "../processRunner.ts";
/**
* Installs T3 Code as a per-user boot service so a connected machine stays
* reachable through T3 Connect after the SSH session ends. Linux-only for
* now: systemd user unit + loginctl enable-linger. The service runs a pinned
* runtime installed under <baseDir>/runtime — never `npx t3`, whose cache is
* ephemeral and whose registry fetch at boot would make startup depend on
* the network.
*/
const BOOT_SERVICE_NAME = "t3code";
const BOOT_RUNTIME_DIR = "runtime";
const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;
const PINNED_RUNTIME_INSTALL_TIMEOUT = Duration.minutes(10);
const EPHEMERAL_CACHE_SEGMENTS = [
"/_npx/", // npx
"\\_npx\\",
"/pnpm/dlx/", // pnpm dlx (~/.cache/pnpm/dlx and $PNPM_HOME/.pnpm/dlx)
"/.pnpm/dlx/",
"/.bun/install/cache/", // bunx
];
/**
* `npx t3` (and pnpm dlx / bunx) run out of ephemeral package-manager
* caches that can be evicted at any time — a boot service must never point
* there. Global installs, repo checkouts, and the pinned runtime below are
* all stable.
*/
export function isEphemeralCacheEntry(entryPath: string): boolean {
return EPHEMERAL_CACHE_SEGMENTS.some((segment) => entryPath.includes(segment));
}
/**
* systemd expands `%` specifiers in most directive values, including the
* `append:` file paths, which take the rest of the line literally and must
* NOT be quoted.
*/
export function escapeSystemdSpecifiers(value: string): string {
return value.replaceAll("%", "%%");
}
/**
* systemd word-splits ExecStart and Environment values and expands `%`
* specifiers, so paths with spaces or percents must be quoted and escaped.
*/
export function quoteSystemdValue(value: string): string {
const escaped = escapeSystemdSpecifiers(value);
return /[\s"'\\]/.test(escaped)
? `"${escaped.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`
: escaped;
}
export interface BootServicePlan {
/** Absolute path of the node binary running this CLI. */
readonly nodePath: string;
/** Absolute path of the pinned t3 entry point the unit will run. */
readonly t3EntryPath: string;
readonly baseDir: string;
readonly logPath: string;
readonly unitPath: string;
}
/**
* Pure so it is testable byte-for-byte. systemd user units run with a
* minimal environment: every path must be absolute, and the service must
* not rely on PATH, nvm shims, or shell profiles. Failures land in
* `logPath` because `systemctl --user` failures are otherwise invisible.
*/
export function renderBootServiceUnit(plan: BootServicePlan): string {
// No After=network-online.target: it does not exist in the systemd *user*
// manager, so ordering on it is silently ignored. The server retries its
// relay connection, and Restart=always covers early-boot failures.
return [
"[Unit]",
"Description=T3 Code server (T3 Connect)",
// Give up after 5 crashes in 5 minutes so a persistently broken install
// (deleted runtime, broken workspace) stops instead of restarting every
// 5s forever and growing the unrotated append log without bound.
"StartLimitIntervalSec=300",
"StartLimitBurst=5",
"",
"[Service]",
"Type=simple",
"WorkingDirectory=%h",
`Environment=T3CODE_HOME=${quoteSystemdValue(plan.baseDir)}`,
`ExecStart=${quoteSystemdValue(plan.nodePath)} ${quoteSystemdValue(plan.t3EntryPath)} serve`,
"Restart=always",
"RestartSec=5",
`StandardOutput=append:${escapeSystemdSpecifiers(plan.logPath)}`,
`StandardError=append:${escapeSystemdSpecifiers(plan.logPath)}`,
"",
"[Install]",
"WantedBy=default.target",
"",
].join("\n");
}
export class BootServiceUnsupportedError extends Schema.TaggedErrorClass<BootServiceUnsupportedError>()(
"BootServiceUnsupportedError",
{ platform: Schema.String },
) {
override get message(): string {
return `Background setup currently supports Linux with systemd; this machine reports '${this.platform}'.`;
}
}
export class BootServiceCommandError extends Schema.TaggedErrorClass<BootServiceCommandError>()(
"BootServiceCommandError",
{
step: Schema.String,
exitCode: Schema.optional(Schema.Number),
stdoutLength: Schema.optional(Schema.Number),
stderrLength: Schema.optional(Schema.Number),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return this.exitCode === undefined
? `Background setup failed while ${this.step}.`
: `Background setup failed while ${this.step} (exit code ${this.exitCode}).`;
}
}
export class BootServiceInstallError extends Schema.TaggedErrorClass<BootServiceInstallError>()(
"BootServiceInstallError",
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Could not set up the T3 Code background service.";
}
}
export type BootServiceError =
| BootServiceUnsupportedError
| BootServiceCommandError
| BootServiceInstallError;
export interface BootServiceStatus {
readonly supported: boolean;
readonly installed: boolean;
/** False when the installed unit no longer matches what install would write. */
readonly current: boolean;
readonly unitPath: string;
readonly logPath: string;
}
export class BootService extends Context.Service<
BootService,
{
/** Installs the pinned runtime + unit, enables linger, starts the service. */
readonly install: Effect.Effect<BootServicePlan, BootServiceError>;
/**
* Stops and removes the unit; leaves the pinned runtime for reuse.
* Returns whether a unit was actually removed.
*/
readonly uninstall: Effect.Effect<boolean, BootServiceError>;
readonly status: Effect.Effect<BootServiceStatus, BootServiceError>;
}
>()("t3/cloud/bootService") {}
export interface BootServiceHost {
readonly execPath: string;
readonly cliEntryPath: string;
}
export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
readonly baseDir: string;
readonly logsDir: string;
readonly cliVersion: string;
readonly host?: BootServiceHost;
}) {
const hostExecPath = yield* HostProcessExecutablePath;
const hostArguments = yield* HostProcessArguments;
const host = input.host ?? {
execPath: hostExecPath,
// When running the packed CLI this is dist/bin.mjs; when stable (global
// install, repo checkout) the boot service runs this same artifact.
cliEntryPath: hostArguments[1] ?? "",
};
const platform = yield* HostProcessPlatform;
const homeDir = yield* Config.string("HOME").pipe(Config.withDefault(""));
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const runner = yield* ProcessRunner.ProcessRunner;
const unitDir = path.join(homeDir, ".config", "systemd", "user");
const unitPath = path.join(unitDir, BOOT_SERVICE_UNIT_FILE);
const logPath = path.join(input.logsDir, "boot-service.log");
const runtimeVersionDir = path.join(
input.baseDir,
BOOT_RUNTIME_DIR,
"versions",
input.cliVersion,
);
const runtimeEntryPath = path.join(runtimeVersionDir, "node_modules", "t3", "dist", "bin.mjs");
const runtimeSentinelPath = path.join(runtimeVersionDir, ".install-complete");
const requireSystemdLinux = Effect.gen(function* () {
if (platform !== "linux" || homeDir === "") {
return yield* new BootServiceUnsupportedError({ platform });
}
});
const runStep = Effect.fn("cloud.boot_service.run_step")(function* (
step: string,
command: string,
args: ReadonlyArray<string>,
options?: { readonly timeout?: Duration.Input },
) {
return yield* runner.run({ command, args, timeout: options?.timeout }).pipe(
Effect.mapError((cause) => new BootServiceCommandError({ step, cause })),
Effect.filterOrFail(
(result) => result.code === 0,
(result) =>
new BootServiceCommandError({
step,
exitCode: Number(result.code),
stdoutLength: result.stdout.length,
stderrLength: result.stderr.length,
}),
),
Effect.tapError((error) =>
DateTime.now.pipe(
Effect.flatMap((now) =>
fs.writeFileString(logPath, `${DateTime.formatIso(now)} ${error.message}\n`, {
flag: "a",
}),
),
Effect.ignore,
),
),
);
});
/**
* Ensures plannedEntryPath exists before the unit points at it. A stable
* install (global bin, repo checkout) is used as-is; an ephemeral cache
* entry is replaced by `npm install --prefix`-ing the exact running
* version into <baseDir>/runtime/versions/<v>. A real install (not a copy
* of bin.mjs) because t3 ships native deps like node-pty.
*/
const ensurePinnedRuntime = Effect.gen(function* () {
if (!isEphemeralCacheEntry(host.cliEntryPath)) {
return;
}
// The sentinel is written only after npm exits 0. Checking the entry
// file alone is not enough: npm extracts files before running native
// builds (node-pty), so a killed install leaves a plausible-looking but
// broken tree behind.
const alreadyPinned = yield* Effect.all([
fs.exists(runtimeSentinelPath),
fs.exists(runtimeEntryPath),
]).pipe(
Effect.map(([sentinelExists, entryExists]) => sentinelExists && entryExists),
Effect.mapError((cause) => new BootServiceInstallError({ cause })),
);
if (alreadyPinned) {
return;
}
yield* fs.remove(runtimeVersionDir, { recursive: true, force: true }).pipe(
Effect.andThen(fs.makeDirectory(runtimeVersionDir, { recursive: true })),
Effect.mapError((cause) => new BootServiceInstallError({ cause })),
);
yield* runStep(
"installing the pinned t3 runtime (this can take a few minutes)",
"npm",
[
"install",
"--prefix",
runtimeVersionDir,
"--no-fund",
"--no-audit",
`t3@${input.cliVersion}`,
],
// Native deps (node-pty) can compile from source on slow boxes; the
// ProcessRunner default of 60s would kill a healthy install.
{ timeout: PINNED_RUNTIME_INSTALL_TIMEOUT },
).pipe(
Effect.tapError(() =>
fs.remove(runtimeVersionDir, { recursive: true, force: true }).pipe(Effect.ignore),
),
);
yield* fs
.writeFileString(runtimeSentinelPath, `${input.cliVersion}\n`)
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
});
// Where the unit will point: derivable without touching the network, so
// status can compare units purely; install materializes it first.
const plannedEntryPath = isEphemeralCacheEntry(host.cliEntryPath)
? runtimeEntryPath
: host.cliEntryPath;
const plan: BootServicePlan = {
nodePath: host.execPath,
t3EntryPath: plannedEntryPath,
baseDir: input.baseDir,
logPath,
unitPath,
};
const install: BootService["Service"]["install"] = Effect.gen(function* () {
yield* requireSystemdLinux;
yield* fs
.makeDirectory(input.logsDir, { recursive: true })
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
yield* ensurePinnedRuntime;
const previousUnit = yield* fs.exists(unitPath).pipe(
Effect.flatMap((exists) =>
exists
? fs.readFileString(unitPath).pipe(Effect.map(Option.some))
: Effect.succeed(Option.none<string>()),
),
Effect.mapError((cause) => new BootServiceInstallError({ cause })),
);
yield* fs.makeDirectory(unitDir, { recursive: true }).pipe(
Effect.andThen(fs.writeFileString(unitPath, renderBootServiceUnit(plan))),
Effect.mapError((cause) => new BootServiceInstallError({ cause })),
);
// If any activation step fails, remove the unit again: a leftover file
// would make the next `t3 connect` report the service as already set up
// even though it was never enabled or lingered.
yield* Effect.gen(function* () {
yield* runStep("reloading systemd user units", "systemctl", ["--user", "daemon-reload"]);
yield* runStep("enabling the service", "systemctl", [
"--user",
"enable",
BOOT_SERVICE_UNIT_FILE,
]);
// restart rather than enable --now: --now does not replace an already
// running process, so repairing a stale unit would leave the old
// server running until reboot. restart also starts a stopped service.
yield* runStep("starting the service", "systemctl", [
"--user",
"restart",
BOOT_SERVICE_UNIT_FILE,
]);
// Linger keeps the user manager (and this service) running without an
// open session — the whole point on a box reached over SSH. No
// username argument: loginctl defaults to the calling user, which is
// always right, while $USER can be stale (su without -l) or unset.
yield* runStep("enabling lingering for this user", "loginctl", ["enable-linger"]);
}).pipe(Effect.tapError(() => rollbackFailedInstall(previousUnit)));
return plan;
}).pipe(Effect.withSpan("cloud.boot_service.install"));
// If activation fails partway (e.g. enable succeeds but restart/linger
// fails), leave nothing behind: disable removes the enable symlink, remove
// deletes the file, daemon-reload clears the stale definition — otherwise a
// dangling wants/ symlink logs "Failed to load unit" at every boot and the
// next connect misreports the state.
const rollbackFailedInstall = Effect.fn("cloud.boot_service.rollback_failed_install")(function* (
previousUnit: Option.Option<string>,
) {
if (Option.isSome(previousUnit)) {
yield* fs.writeFileString(unitPath, previousUnit.value).pipe(Effect.ignore);
} else {
yield* runStep("cleaning up the service", "systemctl", [
"--user",
"disable",
"--now",
BOOT_SERVICE_UNIT_FILE,
]).pipe(Effect.ignore);
yield* fs.remove(unitPath).pipe(Effect.ignore);
}
yield* runStep("reloading systemd user units", "systemctl", ["--user", "daemon-reload"]).pipe(
Effect.ignore,
);
if (Option.isSome(previousUnit)) {
yield* runStep("restoring the previous service", "systemctl", [
"--user",
"restart",
BOOT_SERVICE_UNIT_FILE,
]).pipe(Effect.ignore);
}
});
const uninstall: BootService["Service"]["uninstall"] = Effect.gen(function* () {
yield* requireSystemdLinux;
const exists = yield* fs
.exists(unitPath)
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
if (!exists) {
return false;
}
yield* runStep("stopping the service", "systemctl", [
"--user",
"disable",
"--now",
BOOT_SERVICE_UNIT_FILE,
]);
yield* fs
.remove(unitPath)
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
yield* runStep("reloading systemd user units", "systemctl", ["--user", "daemon-reload"]);
return true;
}).pipe(Effect.withSpan("cloud.boot_service.uninstall"));
const status: BootService["Service"]["status"] = Effect.gen(function* () {
if (platform !== "linux" || homeDir === "") {
return { supported: false, installed: false, current: false, unitPath, logPath };
}
const unitExists = yield* fs.exists(unitPath);
if (!unitExists) {
return { supported: true, installed: false, current: false, unitPath, logPath };
}
const unit = yield* fs.readFileString(unitPath);
// A unit is current only if it matches what install would write now (an
// older CLI wrote a different runtime/node path) AND the entry point it
// references still exists (a pinned runtime under ~/.t3 can be deleted to
// reclaim space). Either mismatch makes connect offer a repair.
const entryExists = yield* fs.exists(plannedEntryPath);
const current = unit === renderBootServiceUnit(plan) && entryExists;
return { supported: true, installed: true, current, unitPath, logPath };
}).pipe(
Effect.mapError((cause) => new BootServiceInstallError({ cause })),
Effect.withSpan("cloud.boot_service.status"),
);
return BootService.of({ install, uninstall, status });
});
export const layer = (input: {
readonly baseDir: string;
readonly logsDir: string;
readonly cliVersion: string;
readonly host?: BootServiceHost;
}) => Layer.effect(BootService, make(input));
+31
View File
@@ -0,0 +1,31 @@
import { expect, it } from "@effect/vitest";
import {
renderLoopbackAuthorizationCompleteHtml,
resolveLoopbackAuthorizationStage,
} from "./cliAuthHtml.ts";
it("renders the branded loopback authorization completion page", () => {
const html = renderLoopbackAuthorizationCompleteHtml();
expect(resolveLoopbackAuthorizationStage()).toBe("dev");
expect(html).toContain("T3 Code (Dev)");
expect(html).toContain('class="stage stage-dev"');
expect(html).not.toContain("Secure terminal handoff");
expect(html).toContain("You're connected");
expect(html).toContain("Return to your terminal");
expect(html).not.toContain('class="next"');
expect(html).toContain('name="viewport"');
expect(html).not.toContain('class="status"');
});
it("renders the matching header treatment for each release channel", () => {
const nightly = renderLoopbackAuthorizationCompleteHtml("nightly");
const latest = renderLoopbackAuthorizationCompleteHtml("latest");
expect(nightly).toContain("T3 Code (Nightly)");
expect(nightly).toContain('class="stage stage-nightly"');
expect(latest).toContain('<p class="brand">T3 Code</p>');
expect(latest).not.toContain("(Latest)");
expect(latest).toContain('class="stage stage-latest"');
});
+155
View File
@@ -0,0 +1,155 @@
export type LoopbackAuthorizationStage = "dev" | "nightly" | "latest";
declare const __T3CODE_BUILD_CHANNEL__: "nightly" | "latest" | undefined;
export function resolveLoopbackAuthorizationStage(): LoopbackAuthorizationStage {
return typeof __T3CODE_BUILD_CHANNEL__ === "undefined" ? "dev" : __T3CODE_BUILD_CHANNEL__;
}
const stageBrands = {
dev: "T3 Code (Dev)",
nightly: "T3 Code (Nightly)",
latest: "T3 Code",
} as const satisfies Record<LoopbackAuthorizationStage, string>;
export function renderLoopbackAuthorizationCompleteHtml(
stage: LoopbackAuthorizationStage = resolveLoopbackAuthorizationStage(),
): string {
const stageBrand = stageBrands[stage];
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="color-scheme" content="light dark" />
<title>T3 Connect authorization complete</title>
<style>
:root {
color-scheme: light dark;
font-family: ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
background: #f6f7f9;
color: #17191f;
}
* { box-sizing: border-box; }
body {
min-height: 100vh;
margin: 0;
display: grid;
place-items: center;
padding: 32px 16px;
background:
radial-gradient(48rem 22rem at 50% -8rem, rgba(47, 119, 235, 0.15), transparent),
#f6f7f9;
}
main {
width: min(100%, 576px);
overflow: hidden;
border: 1px solid rgba(23, 25, 31, 0.1);
border-radius: 20px;
background: rgba(255, 255, 255, 0.94);
box-shadow: 0 24px 64px rgba(16, 24, 40, 0.16);
}
.stage {
position: relative;
height: 96px;
overflow: hidden;
padding: 22px 24px;
color: white;
}
.stage-latest {
background:
radial-gradient(circle at 76% 18%, rgba(136, 204, 255, 0.52), transparent 38%),
linear-gradient(135deg, #2468df, #172f82);
}
.stage-dev {
background: linear-gradient(145deg, #5ab8fa 0%, #347ff8 46%, #1939bd 100%);
}
.stage-dev::before {
content: "";
position: absolute;
inset: 0;
opacity: 0.42;
background-image:
linear-gradient(rgba(234, 246, 255, 0.25) 1px, transparent 1px),
linear-gradient(90deg, rgba(234, 246, 255, 0.25) 1px, transparent 1px),
linear-gradient(rgba(234, 246, 255, 0.12) 1px, transparent 1px),
linear-gradient(90deg, rgba(234, 246, 255, 0.12) 1px, transparent 1px);
background-size: 32px 32px, 32px 32px, 8px 8px, 8px 8px;
}
.stage-nightly {
background:
radial-gradient(22rem 8rem at 78% 18%, rgba(81, 101, 216, 0.42), transparent 58%),
linear-gradient(145deg, #07152f 0%, #151443 52%, #32155b 100%);
}
.stage-nightly::before {
content: "";
position: absolute;
inset: 0;
opacity: 0.78;
background-image:
radial-gradient(circle at 12px 12px, rgba(228, 234, 255, 0.9) 0 1px, transparent 1.5px),
radial-gradient(circle at 38px 28px, rgba(228, 234, 255, 0.58) 0 0.8px, transparent 1.3px),
radial-gradient(circle at 58px 9px, rgba(200, 215, 255, 0.72) 0 0.9px, transparent 1.4px);
background-size: 72px 48px, 96px 64px, 128px 56px;
}
.stage::after {
content: "";
position: absolute;
inset: 0;
background:
radial-gradient(circle at 78% 20%, rgba(210, 255, 255, 0.36), transparent 34%),
linear-gradient(to bottom, transparent 24%, rgba(8, 28, 89, 0.38));
}
.stage-content {
position: relative;
z-index: 1;
height: 100%;
display: flex;
align-items: center;
justify-content: space-between;
}
.brand {
margin: 0;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.2em;
text-transform: uppercase;
}
.brand { color: rgba(255, 255, 255, 0.82); }
.content { padding: 30px 32px 34px; }
.eyebrow {
margin: 0 0 8px;
color: #2866cc;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 { margin: 0; font-size: clamp(26px, 5vw, 34px); line-height: 1.12; letter-spacing: -0.035em; }
.description { margin: 12px 0 0; color: #646975; font-size: 15px; line-height: 1.6; }
@media (prefers-color-scheme: dark) {
:root { background: #101115; color: #f1f3f7; }
body { background: radial-gradient(48rem 22rem at 50% -8rem, rgba(55, 102, 210, 0.2), transparent), #101115; }
main { border-color: rgba(255, 255, 255, 0.1); background: rgba(25, 27, 33, 0.96); }
.eyebrow { color: #77a8ff; }
.description { color: #a8adb8; }
}
</style>
</head>
<body>
<main>
<header class="stage stage-${stage}" data-stage="${stage}">
<div class="stage-content">
<p class="brand">${stageBrand}</p>
</div>
</header>
<section class="content">
<p class="eyebrow">Browser authorization complete</p>
<h1>You're connected</h1>
<p class="description">Return to your terminal to finish setting up T3 Connect. You can close this window.</p>
</section>
</main>
</body>
</html>`;
}
+37 -1
View File
@@ -11,7 +11,13 @@ import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import * as CliTokenManager from "./CliTokenManager.ts";
import { consumeCloudReplayGuards, reconcileDesiredCloudLink } from "./http.ts";
import type { RelayLinkProofRequest } from "@t3tools/contracts/relay";
import {
consumeCloudReplayGuards,
isSupportedLinkProviderKind,
linkProofScopes,
reconcileDesiredCloudLink,
} from "./http.ts";
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
import { traceAuthenticatedRelayRequest, traceRelayRequest } from "./traceRelayRequest.ts";
@@ -194,6 +200,7 @@ describe("reconcileDesiredCloudLink", () => {
get: unusedSecretStoreOperation(),
getExisting: Effect.succeed(Option.none()),
hasCredential: unusedSecretStoreOperation(),
store: () => unusedSecretStoreOperation(),
clear: unusedSecretStoreOperation(),
}),
),
@@ -205,3 +212,32 @@ describe("reconcileDesiredCloudLink", () => {
),
);
});
describe("link proof provider kinds", () => {
const proofRequest = (
providerKind: RelayLinkProofRequest["endpoint"]["providerKind"],
): RelayLinkProofRequest => ({
challenge: "challenge",
relayIssuer: "https://relay.example.test",
endpoint: {
httpBaseUrl: "http://127.0.0.1:7331",
wsBaseUrl: "ws://127.0.0.1:7331",
providerKind,
},
origin: { localHttpHost: "127.0.0.1", localHttpPort: 7331 },
});
it("accepts managed and manual endpoints but not t3_relay", () => {
expect(isSupportedLinkProviderKind(proofRequest("cloudflare_tunnel"))).toBe(true);
expect(isSupportedLinkProviderKind(proofRequest("manual"))).toBe(true);
expect(isSupportedLinkProviderKind(proofRequest("t3_relay"))).toBe(false);
});
it("only claims the managed-tunnel scope for tunnel links", () => {
expect(linkProofScopes(proofRequest("cloudflare_tunnel"))).toEqual([
"agent_activity_notifications",
"managed_tunnels",
]);
expect(linkProofScopes(proofRequest("manual"))).toEqual(["agent_activity_notifications"]);
});
});
+40 -18
View File
@@ -68,7 +68,7 @@ import {
RELAY_URL_SECRET,
} from "./config.ts";
import { relayUrlConfig } from "./publicConfig.ts";
import { setCliDesiredCloudLink } from "./CliState.ts";
import { readCliDesiredLinkMode, setCliDesiredCloudLink } from "./CliState.ts";
import * as CliTokenManager from "./CliTokenManager.ts";
import { getOrCreateEnvironmentKeyPairFromSecretStore } from "./environmentKeys.ts";
import { traceRelayRequest } from "./traceRelayRequest.ts";
@@ -299,8 +299,23 @@ function isAllowedEndpointOrigin(input: {
return input.origin.localHttpPort === endpointRequestPort(url);
}
function providerKindMatchesRequestedLinkScopes(request: RelayLinkProofRequest): boolean {
return request.endpoint.providerKind === "cloudflare_tunnel";
// A managed (Cloudflare tunnel) endpoint is provisioned by the relay and must
// point at a loopback origin. A manual endpoint is reached out of band (e.g.
// Tailscale) or not advertised at all for publish-only links, so it is not
// tied to the managed-tunnel scope.
export function isSupportedLinkProviderKind(request: RelayLinkProofRequest): boolean {
return (
request.endpoint.providerKind === "cloudflare_tunnel" ||
request.endpoint.providerKind === "manual"
);
}
export function linkProofScopes(
request: RelayLinkProofRequest,
): RelayEnvironmentLinkProofPayload["scopes"] {
return request.endpoint.providerKind === "cloudflare_tunnel"
? ["agent_activity_notifications", "managed_tunnels"]
: ["agent_activity_notifications"];
}
function hasExactScope(input: {
@@ -352,7 +367,7 @@ const makeCloudLinkProof = Effect.fn("environment.cloud.makeLinkProof")(function
) {
const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(dependencies.secrets);
if (
!providerKindMatchesRequestedLinkScopes(request) ||
!isSupportedLinkProviderKind(request) ||
!isAllowedEndpointOrigin({
origin: request.origin,
requestUrl,
@@ -379,7 +394,7 @@ const makeCloudLinkProof = Effect.fn("environment.cloud.makeLinkProof")(function
environmentPublicKey: normalizePemForSignedPayload(keyPair.publicKey),
endpoint: request.endpoint,
origin: request.origin,
scopes: ["agent_activity_notifications", "managed_tunnels"],
scopes: linkProofScopes(request),
} satisfies RelayEnvironmentLinkProofPayload;
return yield* signRelayJwt({
privateKey: keyPair.privateKey,
@@ -537,6 +552,8 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
}),
),
);
const mode = yield* readCliDesiredLinkMode;
const managedTunnelsEnabled = mode !== "publish_only";
const relayUrl = yield* requireRelayUrl;
const challenge = yield* relayClientRequest(dependencies, {
url: `${relayUrl}/v1/client/environment-link-challenges`,
@@ -544,7 +561,7 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
payload: {
notificationsEnabled: true,
liveActivitiesEnabled: true,
managedTunnelsEnabled: true,
managedTunnelsEnabled,
},
schema: RelayEnvironmentLinkChallengeResponse,
});
@@ -556,7 +573,7 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
endpoint: {
httpBaseUrl: localOrigin,
wsBaseUrl: localWsOrigin,
providerKind: "cloudflare_tunnel",
providerKind: managedTunnelsEnabled ? "cloudflare_tunnel" : "manual",
},
origin: {
localHttpHost: localUrl.hostname,
@@ -572,11 +589,11 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
proof,
notificationsEnabled: true,
liveActivitiesEnabled: true,
managedTunnelsEnabled: true,
managedTunnelsEnabled,
},
schema: RelayEnvironmentLinkResponse,
});
yield* setCliDesiredCloudLink(true);
yield* setCliDesiredCloudLink(true, mode);
return yield* applyCloudRelayConfig(dependencies, {
relayUrl,
relayIssuer: link.relayIssuer,
@@ -608,20 +625,25 @@ export const reconcileDesiredCloudLink = Effect.fn("environment.cloud.reconcileD
const readCloudLinkState = Effect.fn("environment.cloud.readLinkState")(function* (
dependencies: CloudHttpDependencies,
) {
const [cloudUserId, relayUrl, relayIssuer, publishAgentActivity] = yield* Effect.all(
[
dependencies.secrets.get(CLOUD_LINKED_USER_ID),
dependencies.secrets.get(RELAY_URL_SECRET),
dependencies.secrets.get(RELAY_ISSUER_SECRET),
dependencies.secrets.get(PUBLISH_AGENT_ACTIVITY_SECRET),
],
{ concurrency: 4 },
);
const [cloudUserId, relayUrl, relayIssuer, endpointRuntimeConfig, publishAgentActivity] =
yield* Effect.all(
[
dependencies.secrets.get(CLOUD_LINKED_USER_ID),
dependencies.secrets.get(RELAY_URL_SECRET),
dependencies.secrets.get(RELAY_ISSUER_SECRET),
dependencies.secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG),
dependencies.secrets.get(PUBLISH_AGENT_ACTIVITY_SECRET),
],
{ concurrency: 5 },
);
return {
linked: Option.isSome(cloudUserId),
cloudUserId: Option.isSome(cloudUserId) ? bytesToString(cloudUserId.value) : null,
relayUrl: Option.isSome(relayUrl) ? bytesToString(relayUrl.value) : null,
relayIssuer: Option.isSome(relayIssuer) ? bytesToString(relayIssuer.value) : null,
// The managed tunnel runtime config is only stored for managed links; a
// publish-only link leaves it absent.
managedTunnelActive: Option.isSome(endpointRuntimeConfig),
publishAgentActivity: Option.isSome(publishAgentActivity)
? bytesToString(publishAgentActivity.value) === "true"
: false,
@@ -4,6 +4,7 @@ import * as Effect from "effect/Effect";
import * as Result from "effect/Result";
import {
hostedAppUrlConfig,
makeCloudCliOAuthConfig,
makeRelayUrlConfig,
resolveRelayClientTracingConfig,
@@ -47,6 +48,40 @@ it.effect("rejects an injected relay URL with a non-origin path", () =>
makeRelayUrlConfig("https://embedded.example.test/path").pipe(provideEnv({}), Effect.flip),
);
it.effect("normalizes the hosted app URL to an absolute origin", () =>
Effect.gen(function* () {
assert.equal(
yield* hostedAppUrlConfig.pipe(
provideEnv({ T3CODE_HOSTED_APP_URL: "https://nightly.app.t3.codes" }),
),
"https://nightly.app.t3.codes",
);
assert.equal(
yield* hostedAppUrlConfig.pipe(
provideEnv({ T3CODE_HOSTED_APP_URL: "http://localhost:5733" }),
),
"http://localhost:5733",
);
}),
);
it.effect("rejects malformed or insecure hosted app URLs", () =>
Effect.gen(function* () {
for (const value of [
"app.t3.codes",
"http://app.t3.codes",
"https://app.t3.codes/nested",
"https://app.t3.codes?alias=true",
]) {
const result = yield* hostedAppUrlConfig.pipe(
provideEnv({ T3CODE_HOSTED_APP_URL: value }),
Effect.result,
);
assert.isTrue(Result.isFailure(result), value);
}
}),
);
it.effect("derives direct Clerk OAuth endpoints from statically injected public config", () =>
Effect.gen(function* () {
const config = yield* makeCloudCliOAuthConfig({
+40 -1
View File
@@ -1,3 +1,4 @@
import { CONNECT_OAUTH_SCOPES, DEFAULT_HOSTED_APP_URL } from "@t3tools/shared/connectAuth";
import { clerkFrontendApiUrlFromPublishableKey } from "@t3tools/shared/relayAuth";
import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl";
import * as Config from "effect/Config";
@@ -15,7 +16,7 @@ declare const __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_DATASET__: string | undefi
declare const __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_TOKEN__: string | undefined;
const CLOUD_CLI_OAUTH_REDIRECT_URI = "http://127.0.0.1:34338/callback";
const CLOUD_CLI_OAUTH_SCOPES = ["openid", "profile", "email"] as const;
const CLOUD_CLI_OAUTH_SCOPES = CONNECT_OAUTH_SCOPES;
function validateRelayUrl(value: string) {
const relayUrl = normalizeSecureRelayUrl(value);
@@ -100,6 +101,44 @@ export function makeRelayUrlConfig(fallback = buildTimeRelayUrl) {
export const relayUrlConfig = makeRelayUrlConfig();
/**
* Hosted app origin used for out-of-band OAuth on headless
* machines. Overridable so staging/nightly builds can point their CLIs at a
* matching hosted deployment.
*/
export const hostedAppUrlConfig = makePublicValueConfig(
"T3CODE_HOSTED_APP_URL",
DEFAULT_HOSTED_APP_URL,
).pipe(Config.mapOrFail(validateHostedAppUrl));
function validateHostedAppUrl(value: string) {
try {
const url = new URL(value);
const isLoopbackHttp =
url.protocol === "http:" &&
(url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]");
if (
(url.protocol !== "https:" && !isLoopbackHttp) ||
url.pathname !== "/" ||
url.search !== "" ||
url.hash !== ""
) {
throw new Error("invalid hosted app origin");
}
return Effect.succeed(url.origin);
} catch {
return Effect.fail(
new Config.ConfigError(
new Schema.SchemaError(
new SchemaIssue.InvalidValue(Option.some(value), {
message: "Hosted app URL must be an absolute HTTPS origin (or HTTP loopback origin).",
}),
),
),
);
}
}
function makePublicValueConfig(name: string, fallback: string) {
const runtimeConfig = Config.nonEmptyString(name);
return (fallback ? runtimeConfig.pipe(Config.withDefault(fallback)) : runtimeConfig).pipe(
+9 -1
View File
@@ -45,6 +45,10 @@ export interface ServerDerivedPaths {
readonly secretsDir: string;
}
export interface DeriveServerPathsOptions {
readonly baseDirIsExplicit?: boolean;
}
/**
* ServerConfig - Service tag for server runtime configuration.
*/
@@ -91,9 +95,13 @@ export const layer = (config: ServerConfig["Service"]) => Layer.succeed(ServerCo
export const deriveServerPaths = Effect.fn(function* (
baseDir: ServerConfig["Service"]["baseDir"],
devUrl: ServerConfig["Service"]["devUrl"],
options: DeriveServerPathsOptions = {},
): Effect.fn.Return<ServerDerivedPaths, never, Path.Path> {
const { join } = yield* Path.Path;
const stateDir = join(baseDir, devUrl !== undefined ? "dev" : "userdata-v2");
const stateDir = join(
baseDir,
devUrl !== undefined && !options.baseDirIsExplicit ? "dev" : "userdata-v2",
);
const dbPath = join(stateDir, "state.sqlite");
const attachmentsDir = join(stateDir, "attachments");
const logsDir = join(stateDir, "logs");
@@ -67,6 +67,7 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
expect(first.environmentId).toBe(second.environmentId);
expect(second.capabilities.repositoryIdentity).toBe(true);
expect(second.capabilities.connectionProbe).toBe(true);
}),
);
@@ -135,6 +135,7 @@ export const make = Effect.gen(function* () {
serverVersion: packageJson.version,
capabilities: {
repositoryIdentity: true,
connectionProbe: true,
},
};
+1 -16
View File
@@ -25,11 +25,7 @@ import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
import { OtlpTracer } from "effect/unstable/observability";
import * as ServerConfig from "./config.ts";
import {
ASSET_ROUTE_PREFIX,
FALLBACK_PROJECT_FAVICON_SVG,
resolveAsset,
} from "./assets/AssetAccess.ts";
import { ASSET_ROUTE_PREFIX, resolveAsset } from "./assets/AssetAccess.ts";
import * as BrowserTraceCollector from "./observability/BrowserTraceCollector.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import { traceRelayRequest } from "./cloud/traceRelayRequest.ts";
@@ -196,17 +192,6 @@ export const assetRouteLayer = HttpRouter.add(
if (!asset) {
return HttpServerResponse.text("Not Found", { status: 404 });
}
if (asset.kind === "project-favicon-fallback") {
return HttpServerResponse.text(FALLBACK_PROJECT_FAVICON_SVG, {
status: 200,
contentType: "image/svg+xml",
headers: {
"Cache-Control": "private, max-age=3600",
"X-Content-Type-Options": "nosniff",
},
});
}
return yield* HttpServerResponse.file(asset.path, {
status: 200,
headers: {
+57
View File
@@ -32,6 +32,63 @@ describe("imageMime", () => {
});
});
it("rejects payload with characters outside the base64 alphabet", () => {
expect(parseBase64DataUrl("data:image/png;base64,SGVs!bG8=")).toBeNull();
expect(parseBase64DataUrl("data:image/png;base64,SGVs,bG8=")).toBeNull();
});
it("rejects structurally malformed base64", () => {
// '=' before the trailing padding position
expect(parseBase64DataUrl("data:image/png;base64,AB=CD===")).toBeNull();
expect(parseBase64DataUrl("data:image/png;base64,SGV=bG8=")).toBeNull();
// more than two padding characters
expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8=====AAA")).toBeNull();
// length not a multiple of 4
expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8")).toBeNull();
});
it("accepts base64 with one or two trailing padding characters", () => {
expect(parseBase64DataUrl("data:image/png;base64,SGVsbA==")).toEqual({
mimeType: "image/png",
base64: "SGVsbA==",
});
expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8h")).toEqual({
mimeType: "image/png",
base64: "SGVsbG8h",
});
});
it("rejects empty and whitespace-only payloads", () => {
expect(parseBase64DataUrl("data:image/png;base64,")).toBeNull();
expect(parseBase64DataUrl("data:image/png;base64, \r\n")).toBeNull();
});
it("parses a case-insensitive scheme and mime type", () => {
expect(parseBase64DataUrl("DATA:IMAGE/PNG;BASE64,SGVsbG8=")).toEqual({
mimeType: "image/png",
base64: "SGVsbG8=",
});
});
it("parses a multi-megabyte payload from a deep call stack", () => {
// Regression: matching the payload with a regex borrowed the JS call
// stack, so a ~10 MB image parsed inside fiber execution threw
// "RangeError: Maximum call stack size exceeded".
const dataUrl = `data:image/png;base64,${"A".repeat(14_000_000)}`;
const atDepth = (depth: number): ReturnType<typeof parseBase64DataUrl> =>
depth === 0 ? parseBase64DataUrl(dataUrl) : atDepth(depth - 1);
const findMaxDepth = (depth: number): number => {
try {
return findMaxDepth(depth + 1);
} catch {
return depth;
}
};
const result = atDepth(Math.floor(findMaxDepth(0) * 0.85));
expect(result?.mimeType).toBe("image/png");
expect(result?.base64.length).toBe(14_000_000);
});
it("does not read inherited keys from mime extension map", () => {
expect(inferImageExtension({ mimeType: "constructor" })).toBe(".bin");
});
+63 -8
View File
@@ -29,17 +29,43 @@ export const SAFE_IMAGE_FILE_EXTENSIONS = new Set([
".webp",
]);
// Whether `code` is a character the base64 payload may contain, aside from
// the whitespace handled separately below.
function isBase64Char(code: number): boolean {
return (
(code >= 0x61 && code <= 0x7a) || // a-z
(code >= 0x41 && code <= 0x5a) || // A-Z
(code >= 0x30 && code <= 0x39) || // 0-9
code === 0x2b || // +
code === 0x2f || // /
code === 0x3d // =
);
}
function isBase64Whitespace(code: number): boolean {
return code === 0x0d || code === 0x0a || code === 0x20; // \r \n space
}
// Data URLs carry the full image payload, so this parser must never run a
// regex across the payload: V8's regex engine borrows the JS call stack, and
// matching a multi-megabyte string from a deep call stack (e.g. inside fiber
// execution) throws "Maximum call stack size exceeded".
export function parseBase64DataUrl(
dataUrl: string,
): { readonly mimeType: string; readonly base64: string } | null {
const match = /^data:([^,]+),([a-z0-9+/=\r\n ]+)$/i.exec(dataUrl.trim());
if (!match) return null;
const trimmed = dataUrl.trim();
if (trimmed.slice(0, 5).toLowerCase() !== "data:") return null;
const commaIndex = trimmed.indexOf(",");
if (commaIndex === -1) return null;
const header = trimmed.slice(5, commaIndex);
if (header.length === 0) return null;
const headerParts: Array<string> = [];
for (const part of (match[1] ?? "").split(";")) {
const trimmed = part.trim();
if (trimmed.length > 0) {
headerParts.push(trimmed);
for (const part of header.split(";")) {
const partTrimmed = part.trim();
if (partTrimmed.length > 0) {
headerParts.push(partTrimmed);
}
}
if (headerParts.length < 2) {
@@ -51,8 +77,37 @@ export function parseBase64DataUrl(
}
const mimeType = headerParts[0]?.toLowerCase();
const base64 = match[2]?.replace(/\s+/g, "");
if (!mimeType || !base64) return null;
if (!mimeType) return null;
const payload = trimmed.slice(commaIndex + 1);
const runs: Array<string> = [];
let runStart = -1;
for (let index = 0; index < payload.length; index += 1) {
const code = payload.charCodeAt(index);
if (isBase64Char(code)) {
if (runStart === -1) runStart = index;
continue;
}
if (!isBase64Whitespace(code)) return null;
if (runStart !== -1) {
runs.push(payload.slice(runStart, index));
runStart = -1;
}
}
if (runStart !== -1) {
runs.push(payload.slice(runStart));
}
const base64 = runs.length === 1 ? runs[0]! : runs.join("");
if (base64.length === 0 || base64.length % 4 !== 0) return null;
const firstPad = base64.indexOf("=");
if (firstPad !== -1) {
// '=' is only valid as one or two trailing padding characters; Node's
// decoder would otherwise silently truncate at the first '='.
if (base64.length - firstPad > 2) return null;
for (let index = firstPad; index < base64.length; index += 1) {
if (base64.charCodeAt(index) !== 0x3d) return null;
}
}
return { mimeType, base64 };
}
+22
View File
@@ -411,6 +411,28 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
}).pipe(Effect.provide(makeKeybindingsLayer())),
);
it.effect("replacing with a rule that already exists elsewhere does not duplicate it", () =>
Effect.gen(function* () {
const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
yield* writeKeybindingsConfig(keybindingsConfigPath, [
{ key: "mod+r", command: "script.run-tests.run" },
{ key: "mod+alt+r", command: "script.run-tests.run" },
]);
yield* Effect.gen(function* () {
const keybindings = yield* Keybindings.Keybindings;
return yield* keybindings.upsertKeybindingRule({
key: "mod+alt+r",
command: "script.run-tests.run",
replace: { key: "mod+r", command: "script.run-tests.run" },
});
});
const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
const persistedView = persisted.map(({ key, command }) => ({ key, command }));
assert.deepEqual(persistedView, [{ key: "mod+alt+r", command: "script.run-tests.run" }]);
}).pipe(Effect.provide(makeKeybindingsLayer())),
);
it.effect("removes only the targeted custom keybinding", () =>
Effect.gen(function* () {
const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
+3 -1
View File
@@ -644,7 +644,9 @@ const make = Effect.gen(function* () {
const nextConfig = [
...customConfig.filter((entry) => {
if (replaceTarget) {
return !isSameKeybindingRule(entry, replaceTarget);
return (
!isSameKeybindingRule(entry, replaceTarget) && !isSameKeybindingRule(entry, rule)
);
}
return !isSameKeybindingRule(entry, rule);
}),
@@ -15,6 +15,7 @@ import {
type OrchestrationV2ProviderThread,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Fiber from "effect/Fiber";
@@ -178,6 +179,7 @@ describe("AcpAdapterV2", () => {
const instanceId = ProviderInstanceId.make("acp-test");
const adapter = makeAcpAdapterV2({
crypto: yield* Crypto.Crypto,
instanceId,
flavor: {
driver: ACP_TEST_DRIVER,
@@ -235,6 +237,7 @@ describe("AcpAdapterV2", () => {
);
const instanceId = ProviderInstanceId.make("acp-test");
const adapter = makeAcpAdapterV2({
crypto: yield* Crypto.Crypto,
instanceId,
flavor: {
driver: ACP_TEST_DRIVER,
@@ -283,6 +286,7 @@ describe("AcpAdapterV2", () => {
const protocolEvents = yield* Queue.bounded<EffectAcpProtocol.AcpProtocolLogEvent>(256);
const instanceId = ProviderInstanceId.make("acp-test");
const adapter = makeAcpAdapterV2({
crypto: yield* Crypto.Crypto,
instanceId,
flavor: {
driver: ACP_TEST_DRIVER,
@@ -385,6 +389,7 @@ describe("AcpAdapterV2", () => {
);
const instanceId = ProviderInstanceId.make("acp-test");
const adapter = makeAcpAdapterV2({
crypto: yield* Crypto.Crypto,
instanceId,
flavor: {
driver: ACP_TEST_DRIVER,
@@ -471,6 +476,7 @@ describe("AcpAdapterV2", () => {
const instanceId = ProviderInstanceId.make("acp-test");
const protocolEvents = yield* Queue.bounded<EffectAcpProtocol.AcpProtocolLogEvent>(256);
const adapter = makeAcpAdapterV2({
crypto: yield* Crypto.Crypto,
instanceId,
flavor: {
driver: ACP_TEST_DRIVER,
@@ -4,6 +4,7 @@ import {
type ProviderReplayTranscript,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Crypto from "effect/Crypto";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
@@ -155,7 +156,7 @@ export function makeAcpReplayRuntime(input: {
) => Effect.Effect<
AcpSessionRuntime.AcpSessionRuntime["Service"],
EffectAcpErrors.AcpError,
Scope.Scope
Crypto.Crypto | Scope.Scope
> {
const encodedTranscript = Buffer.from(JSON.stringify(input.transcript), "utf8").toString(
"base64",
@@ -24,6 +24,7 @@ import {
} from "@t3tools/contracts";
import { modelSelectionsEqual } from "@t3tools/shared/model";
import * as Cause from "effect/Cause";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
@@ -120,7 +121,7 @@ export interface AcpAdapterV2Flavor {
) => Effect.Effect<
AcpSessionRuntime.AcpSessionRuntime["Service"],
EffectAcpErrors.AcpError,
Scope.Scope
Crypto.Crypto | Scope.Scope
>;
readonly resolveModelId?: (selection: ModelSelection) => string | undefined;
readonly registerExtensions?: (
@@ -145,6 +146,7 @@ export interface AcpAdapterV2SubagentUpdate {
export interface AcpAdapterV2Options {
readonly instanceId: ProviderInstanceId;
readonly flavor: AcpAdapterV2Flavor;
readonly crypto: Crypto.Crypto;
readonly fileSystem: FileSystem.FileSystem;
readonly idAllocator: IdAllocatorV2Shape;
readonly serverConfig: ServerConfig["Service"];
@@ -635,25 +637,27 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
const nativeLogging = options.nativeLogging?.(input.threadId);
const runtime = yield* flavor.makeRuntime({
cwd: input.runtimePolicy.cwd ?? process.cwd(),
mcpServers: acpMcpServers(input.threadId),
interruptPromptOnCancel: false,
clientCapabilities: {
fs: { readTextFile: false, writeTextFile: false },
terminal: false,
elicitation: { form: {} },
},
clientInfo: { name: "t3-code", version: "0.0.0" },
...(nativeLogging?.requestLogger === undefined
? {}
: { requestLogger: nativeLogging.requestLogger }),
protocolLogging: nativeLogging?.protocolLogging ?? {
logIncoming: true,
logOutgoing: true,
logger: () => Effect.void,
},
});
const runtime = yield* flavor
.makeRuntime({
cwd: input.runtimePolicy.cwd ?? process.cwd(),
mcpServers: acpMcpServers(input.threadId),
interruptPromptOnCancel: false,
clientCapabilities: {
fs: { readTextFile: false, writeTextFile: false },
terminal: false,
elicitation: { form: {} },
},
clientInfo: { name: "t3-code", version: "0.0.0" },
...(nativeLogging?.requestLogger === undefined
? {}
: { requestLogger: nativeLogging.requestLogger }),
protocolLogging: nativeLogging?.protocolLogging ?? {
logIncoming: true,
logOutgoing: true,
logger: () => Effect.void,
},
})
.pipe(Effect.provideService(Crypto.Crypto, options.crypto));
const resolveItemOrdinal = Effect.fnUntraced(function* (
context: ActiveAcpTurn,
@@ -2,6 +2,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import { ProviderInstanceId, ProviderSessionId, ThreadId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Crypto from "effect/Crypto";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
@@ -107,6 +108,7 @@ describe("AcpRegistryAdapterV2", () => {
});
const instanceId = ProviderInstanceId.make("acp-registry-fixture");
const adapter = makeAcpRegistryAdapterV2({
crypto: yield* Crypto.Crypto,
instanceId,
settings,
environment: {
@@ -1,6 +1,7 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { AcpRegistrySettings } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Crypto from "effect/Crypto";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
@@ -41,6 +42,7 @@ export function makeAcpRegistryProviderAdapterRegistryReplayLayer(transcript: Ac
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const crypto = yield* Crypto.Crypto;
const idAllocator = yield* IdAllocatorV2;
const serverConfig = yield* ServerConfig;
const replayDir = yield* fileSystem
@@ -57,6 +59,7 @@ export function makeAcpRegistryProviderAdapterRegistryReplayLayer(transcript: Ac
settings: REPLAY_SETTINGS,
environment: {},
childProcessSpawner,
crypto,
fileSystem,
idAllocator,
resolver: {
@@ -49,6 +49,7 @@ export interface AcpRegistryAdapterV2Options {
readonly settings: AcpRegistrySettings;
readonly environment: NodeJS.ProcessEnv;
readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
readonly crypto: Crypto.Crypto;
readonly fileSystem: FileSystem.FileSystem;
readonly idAllocator: IdAllocatorV2["Service"];
readonly resolver: AcpRegistryResolverShape;
@@ -59,7 +60,7 @@ export interface AcpRegistryAdapterV2Options {
) => Effect.Effect<
AcpSessionRuntime.AcpSessionRuntime["Service"],
EffectAcpErrors.AcpError,
Scope.Scope
Crypto.Crypto | Scope.Scope
>;
readonly assertComplete?: Effect.Effect<void, EffectAcpErrors.AcpError>;
}
@@ -70,7 +71,7 @@ function makeAcpRegistryRuntime(options: AcpRegistryAdapterV2Options) {
): Effect.Effect<
AcpSessionRuntime.AcpSessionRuntime["Service"],
EffectAcpErrors.AcpError,
Scope.Scope
Crypto.Crypto | Scope.Scope
> =>
Effect.gen(function* () {
const resolved = yield* options.resolver
@@ -111,6 +112,7 @@ export function makeAcpRegistryAdapterV2(options: AcpRegistryAdapterV2Options) {
return makeAcpAdapterV2({
instanceId: options.instanceId,
flavor,
crypto: options.crypto,
fileSystem: options.fileSystem,
idAllocator: options.idAllocator,
serverConfig: options.serverConfig,
@@ -139,6 +141,7 @@ export const AcpRegistryAdapterV2Driver: ProviderAdapterDriver<
function* (input: ProviderAdapterDriverCreateInput<AcpRegistrySettings>) {
const hostEnvironment = yield* HostProcessEnvironment;
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const crypto = yield* Crypto.Crypto;
const fileSystem = yield* FileSystem.FileSystem;
const idAllocator = yield* IdAllocatorV2;
const providerEventLoggers = yield* ProviderEventLoggers;
@@ -152,6 +155,7 @@ export const AcpRegistryAdapterV2Driver: ProviderAdapterDriver<
settings: { ...input.config, enabled: input.enabled },
environment: mergeProviderInstanceEnvironment(input.environment, hostEnvironment),
childProcessSpawner,
crypto,
fileSystem,
idAllocator,
resolver,
@@ -1,6 +1,7 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { GrokSettings } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Crypto from "effect/Crypto";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
@@ -34,6 +35,7 @@ export function makeGrokProviderAdapterRegistryReplayLayer(transcript: AcpReplay
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const crypto = yield* Crypto.Crypto;
const idAllocator = yield* IdAllocatorV2;
const serverConfig = yield* ServerConfig;
const replayDir = yield* fileSystem
@@ -50,6 +52,7 @@ export function makeGrokProviderAdapterRegistryReplayLayer(transcript: AcpReplay
settings: DEFAULT_GROK_SETTINGS,
environment: {},
childProcessSpawner,
crypto,
fileSystem,
idAllocator,
serverConfig,
@@ -84,6 +84,7 @@ export interface GrokAdapterV2Options {
readonly settings: GrokSettings;
readonly environment: NodeJS.ProcessEnv;
readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
readonly crypto: Crypto.Crypto;
readonly fileSystem: FileSystem.FileSystem;
readonly idAllocator: IdAllocatorV2["Service"];
readonly serverConfig: ServerConfig["Service"];
@@ -93,7 +94,7 @@ export interface GrokAdapterV2Options {
) => Effect.Effect<
AcpSessionRuntime.AcpSessionRuntime["Service"],
EffectAcpErrors.AcpError,
Scope.Scope
Crypto.Crypto | Scope.Scope
>;
readonly assertComplete?: Effect.Effect<void, EffectAcpErrors.AcpError>;
}
@@ -149,6 +150,7 @@ export function makeGrokAdapterV2(options: GrokAdapterV2Options) {
return makeAcpAdapterV2({
instanceId: options.instanceId,
flavor,
crypto: options.crypto,
fileSystem: options.fileSystem,
idAllocator: options.idAllocator,
serverConfig: options.serverConfig,
@@ -172,6 +174,7 @@ export const GrokAdapterV2Driver: ProviderAdapterDriver<GrokSettings, GrokAdapte
function* (input: ProviderAdapterDriverCreateInput<GrokSettings>) {
const hostEnvironment = yield* HostProcessEnvironment;
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const crypto = yield* Crypto.Crypto;
const fileSystem = yield* FileSystem.FileSystem;
const idAllocator = yield* IdAllocatorV2;
const providerEventLoggers = yield* ProviderEventLoggers;
@@ -182,6 +185,7 @@ export const GrokAdapterV2Driver: ProviderAdapterDriver<GrokSettings, GrokAdapte
settings: { ...input.config, enabled: input.enabled },
environment: mergeProviderInstanceEnvironment(input.environment, hostEnvironment),
childProcessSpawner,
crypto,
fileSystem,
idAllocator,
serverConfig,
@@ -222,6 +226,7 @@ export const layer: Layer.Layer<
Effect.gen(function* () {
const hostEnvironment = yield* HostProcessEnvironment;
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const crypto = yield* Crypto.Crypto;
const fileSystem = yield* FileSystem.FileSystem;
const idAllocator = yield* IdAllocatorV2;
const providerEventLoggers = yield* ProviderEventLoggers;
@@ -232,6 +237,7 @@ export const layer: Layer.Layer<
settings: DEFAULT_GROK_SETTINGS,
environment: hostEnvironment,
childProcessSpawner,
crypto,
fileSystem,
idAllocator,
serverConfig,
@@ -331,6 +331,13 @@ function makeOpenCodeReplayRuntimeLayer(transcript: OpenCodeSdkReplayTranscript)
detail: "OpenCode replay does not load inventory.",
}),
),
loadInventoryFromCli: () =>
Effect.fail(
new OpenCodeRuntimeError({
operation: "loadInventoryFromCli",
detail: "OpenCode replay does not load inventory.",
}),
),
} satisfies OpenCodeRuntimeShape);
}),
);
@@ -0,0 +1,33 @@
import type { ApplicationStoredEvent } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { coalesceShellApplicationEvents } from "./ShellStream.ts";
function project(sequence: number, id: string): ApplicationStoredEvent {
return {
sequence,
aggregateKind: "project",
aggregateId: id,
} as ApplicationStoredEvent;
}
function thread(sequence: number, id: string): ApplicationStoredEvent {
return {
sequence,
event: { threadId: id },
} as ApplicationStoredEvent;
}
describe("coalesceShellApplicationEvents", () => {
it("keeps the newest event per aggregate and preserves sequence order", () => {
expect(
coalesceShellApplicationEvents([
thread(2, "thread-a"),
project(3, "project-a"),
thread(4, "thread-b"),
thread(5, "thread-a"),
project(6, "project-a"),
]).map((event) => event.sequence),
).toEqual([4, 5, 6]);
});
});
@@ -1,10 +1,28 @@
import type {
ApplicationStoredEvent,
OrchestrationV2ArchivedShellStreamItem,
OrchestrationV2ThreadShellSnapshot,
OrchestrationV2ShellStreamItem,
OrchestrationV2StoredEvent,
} from "@t3tools/contracts";
/** Keep only the newest shell-relevant event per project/thread aggregate. */
export function coalesceShellApplicationEvents(
events: ReadonlyArray<ApplicationStoredEvent>,
): ReadonlyArray<ApplicationStoredEvent> {
const latestByAggregate = new Map<string, ApplicationStoredEvent>();
for (const stored of events) {
const key =
"aggregateKind" in stored
? `project:${stored.aggregateId}`
: `thread:${stored.event.threadId}`;
latestByAggregate.set(key, stored);
}
return Array.from(latestByAggregate.values()).sort(
(left, right) => left.sequence - right.sequence,
);
}
/** Converts a committed event and its resulting shell snapshot into one delta. */
export function shellStreamItemFromSnapshot(input: {
readonly stored: OrchestrationV2StoredEvent;
+117
View File
@@ -0,0 +1,117 @@
import {
AuthOrchestrationReadScope,
EnvironmentHttpApi,
type OrchestrationProjectShell,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Predicate from "effect/Predicate";
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import {
annotateEnvironmentRequest,
failEnvironmentInternal,
failEnvironmentNotFound,
requireEnvironmentScope,
} from "../auth/http.ts";
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
import * as OrchestrationEventStore from "../persistence/Services/OrchestrationEventStore.ts";
import * as ProjectEnrichmentService from "../project/ProjectEnrichmentService.ts";
import * as ThreadManagementService from "./ThreadManagementService.ts";
function isThreadNotFound(error: unknown): boolean {
return (
Predicate.hasProperty(error, "cause") &&
Predicate.hasProperty(error.cause, "_tag") &&
error.cause._tag === "ProjectionStoreThreadNotFoundError"
);
}
/**
* Serves orchestration V2 snapshots over HTTP so clients can load the
* (potentially large) shell and thread projections off the socket — gzip
* compressible and cacheable — and then resume the WebSocket subscription via
* `afterSequence`.
*/
export const orchestrationHttpApiLayer = HttpApiBuilder.group(
EnvironmentHttpApi,
"orchestration",
Effect.fnUntraced(function* (handlers) {
const sql = yield* SqlClient.SqlClient;
const threadManagement = yield* ThreadManagementService.ThreadManagementService;
const applicationEvents = yield* OrchestrationEventStore.OrchestrationEventStore;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
const projectEnrichment = yield* ProjectEnrichmentService.ProjectEnrichmentService;
const enrichProjectShells = Effect.fn("http.orchestration.enrichProjectShells")(
(projects: ReadonlyArray<OrchestrationProjectShell>) =>
Effect.forEach(
projects,
(project) =>
projectEnrichment.getAvailable(project.workspaceRoot).pipe(
Effect.map((enrichment) => ({
...project,
repositoryIdentity: enrichment.repositoryIdentity,
})),
),
{ concurrency: 16 },
),
);
const loadShellSnapshot = Effect.fn("http.orchestration.loadShellSnapshot")(function* () {
const base = yield* sql.withTransaction(
Effect.gen(function* () {
const projects = yield* projectionSnapshotQuery.getShellSnapshotWithoutEnrichment();
const threads = yield* threadManagement.getShellSnapshot();
return {
schemaVersion: threads.schemaVersion,
snapshotSequence: yield* applicationEvents.latestApplicationSequence,
projects: projects.projects,
threads: threads.threads,
archivedThreads: threads.archivedThreads,
} as const;
}),
);
const projects = yield* enrichProjectShells(base.projects);
return { ...base, projects };
});
return handlers
.handle(
"shellSnapshot",
Effect.fn("environment.orchestration.shellSnapshot")(function* (args) {
yield* annotateEnvironmentRequest(args.endpoint.name);
yield* requireEnvironmentScope(AuthOrchestrationReadScope);
return yield* loadShellSnapshot().pipe(
Effect.catch((cause) =>
failEnvironmentInternal("orchestration_snapshot_failed", cause),
),
);
}),
)
.handle(
"threadSnapshot",
Effect.fn("environment.orchestration.threadSnapshot")(function* (args) {
yield* annotateEnvironmentRequest(args.endpoint.name);
yield* requireEnvironmentScope(AuthOrchestrationReadScope);
const snapshot = yield* threadManagement.getThreadSnapshot(args.params.threadId).pipe(
Effect.catch(
Effect.fnUntraced(function* (error) {
if (isThreadNotFound(error)) {
return yield* failEnvironmentNotFound("thread_not_found");
}
return yield* failEnvironmentInternal(
"orchestration_thread_snapshot_failed",
error,
);
}),
),
);
return {
snapshotSequence: snapshot.snapshotSequence,
projection: snapshot.projection,
};
}),
);
}),
);
@@ -311,8 +311,8 @@ const makeOrchestrationEngine = Effect.gen(function* () {
Effect.annotateLogs({ sequence: commandReadModel.snapshotSequence }),
);
const readEvents: OrchestrationEngineShape["readEvents"] = (fromSequenceExclusive) =>
eventStore.readFromSequence(fromSequenceExclusive);
const readEvents: OrchestrationEngineShape["readEvents"] = (fromSequenceExclusive, limit) =>
eventStore.readFromSequence(fromSequenceExclusive, limit);
const dispatch: OrchestrationEngineShape["dispatch"] = (command) =>
Effect.gen(function* () {
@@ -334,6 +334,11 @@ const makeOrchestrationEngine = Effect.gen(function* () {
get streamDomainEvents(): OrchestrationEngineShape["streamDomainEvents"] {
return Stream.fromPubSub(eventPubSub);
},
// The command read model's snapshotSequence tracks the latest committed
// event sequence (updated on the worker fiber). A plain property read is a
// consistent, committed value — reassignment of `commandReadModel` is
// atomic on the single-threaded event loop.
latestSequence: Effect.sync(() => commandReadModel.snapshotSequence),
} satisfies OrchestrationEngineShape;
});
@@ -16,6 +16,7 @@ import {
OrchestrationReadModel,
OrchestrationShellSnapshot,
OrchestrationThread,
OrchestrationThreadDetailSnapshot,
type OrchestrationCheckpointSummary,
type OrchestrationLatestTurn,
type OrchestrationMessage,
@@ -2050,6 +2051,35 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
);
});
const getThreadDetailSnapshot: ProjectionSnapshotQueryShape["getThreadDetailSnapshot"] = (
threadId,
) =>
// Read the thread detail and the snapshot sequence within a single
// transaction so the sequence is consistent with the returned state; a
// projector update landing between two separate reads could otherwise return
// a sequence ahead of the thread detail, causing the client to resume from
// too far and drop events.
sql
.withTransaction(
Effect.gen(function* () {
const thread = yield* getThreadDetailById(threadId);
if (Option.isNone(thread)) {
return Option.none<OrchestrationThreadDetailSnapshot>();
}
const { snapshotSequence } = yield* getSnapshotSequence();
return Option.some({ snapshotSequence, thread: thread.value });
}),
)
.pipe(
Effect.mapError((error) =>
isPersistenceError(error)
? error
: toPersistenceSqlError("ProjectionSnapshotQuery.getThreadDetailSnapshot:transaction")(
error,
),
),
);
return {
getCommandReadModel,
getSnapshot,
@@ -2065,6 +2095,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
getFullThreadDiffContext,
getThreadShellById,
getThreadDetailById,
getThreadDetailSnapshot,
} satisfies ProjectionSnapshotQueryShape;
});
@@ -29,10 +29,15 @@ export interface OrchestrationEngineShape {
* Replay persisted orchestration events from an exclusive sequence cursor.
*
* @param fromSequenceExclusive - Sequence cursor (exclusive).
* @param limit - Maximum number of events to read. Defaults to the event
* store's page-bounded default; pass a higher value when the caller must
* read every event after the cursor (e.g. per-thread catch-up that filters
* a small subset out of a potentially larger global range).
* @returns Stream containing ordered events.
*/
readonly readEvents: (
fromSequenceExclusive: number,
limit?: number,
) => Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError, never>;
/**
@@ -54,6 +59,13 @@ export interface OrchestrationEngineShape {
* This is a hot runtime stream (new events only), not a historical replay.
*/
readonly streamDomainEvents: Stream.Stream<OrchestrationEvent>;
/**
* The latest sequence reflected in the engine's authoritative command read
* model (0 if none). Used to gauge how far behind a resuming client is before
* choosing between an incremental replay and a fresh projected snapshot.
*/
readonly latestSequence: Effect.Effect<number, never, never>;
}
/**
@@ -14,6 +14,7 @@ import type {
OrchestrationReadModel,
OrchestrationShellSnapshot,
OrchestrationThread,
OrchestrationThreadDetailSnapshot,
OrchestrationThreadShell,
} from "@t3tools/contracts/legacy-orchestration";
import * as Context from "effect/Context";
@@ -166,6 +167,16 @@ export interface ProjectionSnapshotQueryShape {
readonly getThreadDetailById: (
threadId: ThreadId,
) => Effect.Effect<Option.Option<OrchestrationThread>, ProjectionRepositoryError>;
/**
* Read a single active thread detail together with the projection snapshot
* sequence in one consistent transaction, so the returned `snapshotSequence`
* exactly matches the state reflected in `thread` (no interleaving projector
* update between the two reads).
*/
readonly getThreadDetailSnapshot: (
threadId: ThreadId,
) => Effect.Effect<Option.Option<OrchestrationThreadDetailSnapshot>, ProjectionRepositoryError>;
}
/**
@@ -5,6 +5,7 @@ import type {
OrchestrationReadModel,
OrchestrationThread,
} from "@t3tools/contracts/legacy-orchestration";
import { normalizeProjectPathForComparison } from "@t3tools/shared/path";
import * as Effect from "effect/Effect";
import { OrchestrationCommandInvariantError } from "./Errors.ts";
@@ -70,6 +71,30 @@ export function requireProjectAbsent(input: {
);
}
export function requireActiveProjectWorkspaceRootAbsent(input: {
readonly readModel: OrchestrationReadModel;
readonly command: OrchestrationCommand;
readonly workspaceRoot: string;
readonly exceptProjectId?: ProjectId;
}): Effect.Effect<void, OrchestrationCommandInvariantError> {
const normalizedWorkspaceRoot = normalizeProjectPathForComparison(input.workspaceRoot);
const existingProject = input.readModel.projects.find(
(project) =>
project.deletedAt === null &&
normalizeProjectPathForComparison(project.workspaceRoot) === normalizedWorkspaceRoot &&
project.id !== input.exceptProjectId,
);
if (existingProject === undefined) {
return Effect.void;
}
return Effect.fail(
invariantError(
input.command.type,
`Active project '${existingProject.id}' already exists for workspace root '${normalizedWorkspaceRoot}'.`,
),
);
}
export function requireThread(input: {
readonly readModel: OrchestrationReadModel;
readonly command: OrchestrationCommand;
+23 -2
View File
@@ -12,6 +12,7 @@ import type * as PlatformError from "effect/PlatformError";
import { OrchestrationCommandInvariantError } from "./Errors.ts";
import {
listThreadsByProjectId,
requireActiveProjectWorkspaceRootAbsent,
requireProject,
requireProjectAbsent,
requireThread,
@@ -111,6 +112,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
command,
projectId: command.projectId,
});
yield* requireActiveProjectWorkspaceRootAbsent({
readModel,
command,
workspaceRoot: command.workspaceRoot,
exceptProjectId: command.projectId,
});
return {
...(yield* withEventBase({
@@ -138,6 +145,14 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
command,
projectId: command.projectId,
});
if (command.workspaceRoot !== undefined) {
yield* requireActiveProjectWorkspaceRootAbsent({
readModel,
command,
workspaceRoot: command.workspaceRoot,
exceptProjectId: command.projectId,
});
}
const occurredAt = yield* nowIso;
return {
...(yield* withEventBase({
@@ -313,11 +328,17 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
}
case "thread.meta.update": {
yield* requireThread({
const thread = yield* requireThread({
readModel,
command,
threadId: command.threadId,
});
const branch =
command.branch !== undefined &&
command.expectedBranch !== undefined &&
thread.branch !== command.expectedBranch
? thread.branch
: command.branch;
const occurredAt = yield* nowIso;
return {
...(yield* withEventBase({
@@ -333,7 +354,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
...(command.modelSelection !== undefined
? { modelSelection: command.modelSelection }
: {}),
...(command.branch !== undefined ? { branch: command.branch } : {}),
...(branch !== undefined ? { branch } : {}),
...(command.worktreePath !== undefined ? { worktreePath: command.worktreePath } : {}),
updatedAt: occurredAt,
},
@@ -203,6 +203,20 @@ layer("OrchestrationEventStore", (it) => {
assert.isTrue("aggregateKind" in applicationEvents[0]!);
assert.isTrue("event" in applicationEvents[1]!);
const finiteReplay = yield* eventStore
.readApplicationEvents({
afterSequence: baselineSequence,
throughSequence: threadEvent!.sequence,
})
.pipe(
Stream.runCollect,
Effect.map((chunk) => Array.from(chunk)),
);
assert.deepEqual(
finiteReplay.map((event) => event.sequence),
[projectEvent.sequence, threadEvent!.sequence],
);
const legacyReplay = yield* eventStore.readFromSequence(projectEvent.sequence - 1).pipe(
Stream.runCollect,
Effect.map((chunk) => Array.from(chunk)),
@@ -504,7 +504,7 @@ const makeEventStore = Effect.gen(function* () {
),
);
const readApplicationEvents = (input: {
const readApplicationEventPage = (input: {
readonly afterSequence: number;
readonly throughSequence: number;
readonly limit: number;
@@ -534,7 +534,7 @@ const makeEventStore = Effect.gen(function* () {
afterSequence: number,
): Stream.Stream<ApplicationStoredEvent, OrchestrationEventStoreError> =>
Stream.unwrap(
readApplicationEvents({
readApplicationEventPage({
afterSequence,
throughSequence: input.throughSequence,
limit: READ_PAGE_SIZE,
@@ -581,6 +581,7 @@ const makeEventStore = Effect.gen(function* () {
readAgentEvents,
latestAgentSequence,
latestApplicationSequence,
readApplicationEvents: catchUpApplicationEvents,
publishCommitted: (events) => PubSub.publishAll(committedEvents, events).pipe(Effect.asVoid),
streamApplicationEvents,
} satisfies OrchestrationEventStoreShape;
+4 -8
View File
@@ -139,15 +139,11 @@ export interface RunMigrationsOptions {
export const runMigrations = Effect.fn("runMigrations")(function* ({
toMigrationInclusive,
}: RunMigrationsOptions = {}) {
yield* Effect.log(
toMigrationInclusive === undefined
? "Running all migrations..."
: `Running migrations 1 through ${toMigrationInclusive}...`,
);
const executedMigrations = yield* run({ loader: makeMigrationLoader(toMigrationInclusive) });
yield* Effect.log("Migrations ran successfully").pipe(
Effect.annotateLogs({ migrations: executedMigrations.map(([id, name]) => `${id}_${name}`) }),
);
const migrations = executedMigrations.map(([id, name]) => `${id}_${name}`);
yield* migrations.length === 0
? Effect.logDebug("Database schema is current")
: Effect.log("Migrations ran successfully").pipe(Effect.annotateLogs({ migrations }));
return executedMigrations;
});
@@ -1,7 +1,9 @@
import * as Arr from "effect/Array";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import * as Struct from "effect/Struct";
import * as SqlClient from "effect/unstable/sql/SqlClient";
@@ -275,18 +277,30 @@ export const make = Effect.gen(function* () {
),
),
Effect.flatMap((rows) =>
// Skip rows that no longer decode (e.g. written by an older build)
// instead of failing the whole list — one stale row must not disable
// every consumer that enumerates sessions, such as the reaper.
Effect.forEach(rows, (row) =>
decodeRuntimeRow(row).pipe(
Effect.mapError((cause) =>
PersistenceDecodeError.fromSchemaError(
"ProviderSessionRuntimeRepository.list:decodeRows",
cause,
{ threadId: row.threadId },
),
Effect.map(Option.some),
Effect.catch((cause) =>
Effect.logWarning("provider.session.runtime.row-skipped", {
threadId: row.threadId,
error: PersistenceDecodeError.fromSchemaError(
"ProviderSessionRuntimeRepository.list:decodeRows",
cause,
{ threadId: row.threadId },
).message,
}).pipe(Effect.as(Option.none<ProviderSessionRuntime>())),
),
),
),
),
Effect.map((decoded) =>
Arr.filterMap(decoded, (row) =>
Option.isSome(row) ? Result.succeed(row.value) : Result.failVoid,
),
),
);
const deleteByThreadId: ProviderSessionRuntimeRepository["Service"]["deleteByThreadId"] = (
@@ -182,7 +182,7 @@ describe("persistence error correlation", () => {
}).pipe(Effect.provide(authPairingLinkLayer)),
);
it.effect("correlates provider runtime SQL and per-row decode failures by thread", () =>
it.effect("skips undecodable provider runtime rows and correlates SQL failures by thread", () =>
Effect.gen(function* () {
const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
const sql = yield* SqlClient.SqlClient;
@@ -215,16 +215,24 @@ describe("persistence error correlation", () => {
)
`;
const decodeError = yield* Effect.flip(runtimes.list());
assert.instanceOf(decodeError, PersistenceErrors.PersistenceDecodeError);
assert.deepStrictEqual(decodeError.correlation, { threadId });
assert.equal(
decodeError.message,
`Decode error in ProviderSessionRuntimeRepository.list:decodeRows: ${decodeError.issue}`,
const validThreadId = ThreadId.make("thread-valid");
yield* runtimes.upsert({
threadId: validThreadId,
providerName: "codex",
providerInstanceId: null,
adapterKey: "codex",
runtimeMode: "full-access",
status: "running",
lastSeenAt,
resumeCursor: null,
runtimePayload: null,
});
const listed = yield* runtimes.list();
assert.deepStrictEqual(
listed.map((runtime) => runtime.threadId),
[validThreadId],
);
assert.notInclude(decodeError.issue, runtimePayload);
assert.notInclude(decodeError.message, runtimePayload);
assert.notInclude(decodeError.message, lastSeenAt);
yield* sql`DROP TABLE provider_session_runtime`;
const sqlFailure = yield* Effect.flip(
@@ -82,6 +82,12 @@ export interface OrchestrationEventStoreShape {
readonly latestApplicationSequence: Effect.Effect<number, OrchestrationEventStoreError>;
/** Read the finite retained application-event range `(afterSequence, throughSequence]`. */
readonly readApplicationEvents: (input: {
readonly afterSequence: number;
readonly throughSequence: number;
}) => Stream.Stream<ApplicationStoredEvent, OrchestrationEventStoreError>;
/** Publish only after the surrounding event/projection transaction commits. */
readonly publishCommitted: (events: ReadonlyArray<ApplicationStoredEvent>) => Effect.Effect<void>;
@@ -1,3 +1,5 @@
import type { ProviderInteractionMode } from "@t3tools/contracts";
const T3_CODE_BROWSER_TOOL_INSTRUCTIONS = `
## T3 Code collaborative browser
@@ -155,3 +157,26 @@ In Default mode, strongly prefer making reasonable assumptions and executing the
${T3_CODE_BROWSER_TOOL_INSTRUCTIONS}
${T3_CODE_THREAD_ORCHESTRATION_INSTRUCTIONS}
</collaboration_mode>`;
export interface CodexRuntimeInfo {
readonly model: string;
readonly reasoningEffort: string;
}
// Values come from trusted config, but keep the block single-line regardless.
function toSingleLine(value: string): string {
return value.replaceAll(/\s+/g, " ").trim();
}
export function buildCodexDeveloperInstructions(
interactionMode: ProviderInteractionMode,
runtime: CodexRuntimeInfo,
): string {
const base =
interactionMode === "plan"
? CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS
: CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS;
return `${base}
<runtime_info>In case you're asked: you are running in T3 Code through the Codex harness, as ${toSingleLine(runtime.model)} with ${toSingleLine(runtime.reasoningEffort)} reasoning effort. No need to mention this otherwise.</runtime_info>`;
}
@@ -121,6 +121,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const path = yield* Path.Path;
const { cwd } = yield* ServerConfig;
const httpClient = yield* HttpClient.HttpClient;
const serverSettings = yield* ServerSettingsService;
const processEnv = mergeProviderInstanceEnvironment(environment);
@@ -167,11 +168,11 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
capacity: 1,
timeToLive: CAPABILITIES_PROBE_TTL,
lookup: () =>
probeClaudeCapabilities(effectiveConfig, processEnv).pipe(
probeClaudeCapabilities(effectiveConfig, processEnv, cwd).pipe(
Effect.provideService(Path.Path, path),
),
});
const capabilitiesCacheKey = yield* makeClaudeCapabilitiesCacheKey(effectiveConfig);
const capabilitiesCacheKey = yield* makeClaudeCapabilitiesCacheKey(effectiveConfig, cwd);
const checkProvider = checkClaudeProviderStatus(
effectiveConfig,
@@ -0,0 +1,124 @@
import { describe, expect, it } from "@effect/vitest";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { SpawnExecutableResolution } from "@t3tools/shared/shell";
import * as Effect from "effect/Effect";
import { ClaudeExecutableFileCheck, resolveClaudeSdkExecutablePath } from "./ClaudeExecutable.ts";
const NPM_DIR = "C:\\Users\\dev\\AppData\\Roaming\\npm";
const NPM_SHIM = `${NPM_DIR}\\claude.cmd`;
const NPM_PACKAGE_EXE = `${NPM_DIR}\\node_modules\\@anthropic-ai\\claude-code\\bin\\claude.exe`;
const NPM_PACKAGE_CLI = `${NPM_DIR}\\node_modules\\@anthropic-ai\\claude-code\\cli.js`;
function withWindowsResolution(input: {
readonly resolvedCommand: string | undefined;
readonly existingFiles?: ReadonlyArray<string>;
}) {
const existing = new Set(input.existingFiles ?? []);
return <A, E, R>(effect: Effect.Effect<A, E, R>) =>
effect.pipe(
Effect.provideService(HostProcessPlatform, "win32"),
Effect.provideService(SpawnExecutableResolution, () => input.resolvedCommand),
Effect.provideService(ClaudeExecutableFileCheck, (filePath) => existing.has(filePath)),
);
}
describe("resolveClaudeSdkExecutablePath", () => {
it.effect("returns the configured path unchanged on non-Windows platforms", () =>
Effect.gen(function* () {
expect(
yield* resolveClaudeSdkExecutablePath("claude", {}).pipe(
Effect.provideService(HostProcessPlatform, "darwin"),
Effect.provideService(SpawnExecutableResolution, () => {
throw new Error("must not resolve on non-Windows platforms");
}),
),
).toBe("claude");
}),
);
it.effect("returns the resolved absolute path for native Windows executables", () =>
Effect.gen(function* () {
const nativeBinary = "C:\\Users\\dev\\.local\\bin\\claude.exe";
expect(
yield* resolveClaudeSdkExecutablePath("claude", {}).pipe(
withWindowsResolution({ resolvedCommand: nativeBinary }),
),
).toBe(nativeBinary);
}),
);
it.effect("follows an npm launcher shim to the packaged native binary", () =>
Effect.gen(function* () {
expect(
yield* resolveClaudeSdkExecutablePath("claude", {}).pipe(
withWindowsResolution({
resolvedCommand: NPM_SHIM,
existingFiles: [NPM_PACKAGE_EXE, NPM_PACKAGE_CLI],
}),
),
).toBe(NPM_PACKAGE_EXE);
}),
);
it.effect("follows .bat and .ps1 launcher shims the same way", () =>
Effect.gen(function* () {
for (const shim of [`${NPM_DIR}\\claude.bat`, `${NPM_DIR}\\claude.ps1`]) {
expect(
yield* resolveClaudeSdkExecutablePath("claude", {}).pipe(
withWindowsResolution({
resolvedCommand: shim,
existingFiles: [NPM_PACKAGE_EXE],
}),
),
).toBe(NPM_PACKAGE_EXE);
}
}),
);
it.effect("normalizes mixed-case shim extensions before matching", () =>
Effect.gen(function* () {
expect(
yield* resolveClaudeSdkExecutablePath("claude", {}).pipe(
withWindowsResolution({
resolvedCommand: `${NPM_DIR}\\claude.CMD`,
existingFiles: [NPM_PACKAGE_EXE],
}),
),
).toBe(NPM_PACKAGE_EXE);
}),
);
it.effect("falls back to cli.js when the package ships no native binary", () =>
Effect.gen(function* () {
expect(
yield* resolveClaudeSdkExecutablePath("claude", {}).pipe(
withWindowsResolution({
resolvedCommand: NPM_SHIM,
existingFiles: [NPM_PACKAGE_CLI],
}),
),
).toBe(NPM_PACKAGE_CLI);
}),
);
it.effect("returns the configured path when a shim has no known package entry", () =>
Effect.gen(function* () {
expect(
yield* resolveClaudeSdkExecutablePath("claude", {}).pipe(
withWindowsResolution({ resolvedCommand: NPM_SHIM }),
),
).toBe("claude");
}),
);
it.effect("returns the configured path when command resolution finds nothing", () =>
Effect.gen(function* () {
expect(
yield* resolveClaudeSdkExecutablePath("claude", {}).pipe(
withWindowsResolution({ resolvedCommand: undefined }),
),
).toBe("claude");
}),
);
});
@@ -0,0 +1,90 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeFS from "node:fs";
import * as NodePath from "node:path";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { SpawnExecutableResolution } from "@t3tools/shared/shell";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
/**
* Windows launcher-script extensions that Node cannot spawn without a shell
* (`spawn EINVAL` since Node 20.12) and that the Claude Agent SDK therefore
* cannot use as `pathToClaudeCodeExecutable`.
*/
const WINDOWS_SHIM_EXTENSIONS: ReadonlySet<string> = new Set([".cmd", ".bat", ".ps1"]);
/**
* Entry points of the npm `@anthropic-ai/claude-code` package relative to the
* global `node_modules` directory that sits next to the npm launcher shim.
* Newer package versions ship a native `bin/claude.exe`; older versions only
* ship `cli.js`, which the SDK runs with a JavaScript runtime.
*/
const NPM_PACKAGE_ENTRY_CANDIDATES = [
["node_modules", "@anthropic-ai", "claude-code", "bin", "claude.exe"],
["node_modules", "@anthropic-ai", "claude-code", "cli.js"],
] as const;
export type ExecutableFileCheck = (filePath: string) => boolean;
function isExistingFile(filePath: string): boolean {
try {
return NodeFS.statSync(filePath).isFile();
} catch {
return false;
}
}
/** Injectable file-existence check so tests can run against a fake filesystem. */
export const ClaudeExecutableFileCheck = Context.Reference<ExecutableFileCheck>(
"server/provider/Drivers/ClaudeExecutableFileCheck",
{
defaultValue: () => isExistingFile,
},
);
/**
* Resolves the configured Claude binary path into a value the Claude Agent
* SDK can spawn directly via `pathToClaudeCodeExecutable`.
*
* The SDK spawns the given path without a shell and without Windows PATH /
* PATHEXT resolution, so a bare command name like `claude` fails with
* "native binary not found" and an npm `claude.cmd` shim fails with
* `spawn EINVAL`. CLI probes avoid this via `resolveSpawnCommand`, which can
* fall back to `shell: true`; the SDK offers no such escape hatch.
*
* On Windows this resolves the command against PATH/PATHEXT and, when the
* result is an npm launcher shim, follows it to the real package entry
* (`bin/claude.exe`, or `cli.js` for older package versions). On other
* platforms the configured value is returned unchanged.
*/
export const resolveClaudeSdkExecutablePath = Effect.fn("resolveClaudeSdkExecutablePath")(
function* (binaryPath: string, environment: NodeJS.ProcessEnv): Effect.fn.Return<string> {
const platform = yield* HostProcessPlatform;
if (platform !== "win32") {
return binaryPath;
}
const resolveExecutable = yield* SpawnExecutableResolution;
const isFile = yield* ClaudeExecutableFileCheck;
const resolved = resolveExecutable(binaryPath, platform, environment) ?? binaryPath;
const extension = NodePath.win32.extname(resolved).toLowerCase();
if (!WINDOWS_SHIM_EXTENSIONS.has(extension)) {
return resolved;
}
const shimDirectory = NodePath.win32.dirname(resolved);
for (const entrySegments of NPM_PACKAGE_ENTRY_CANDIDATES) {
const candidate = NodePath.win32.join(shimDirectory, ...entrySegments);
if (isFile(candidate)) {
return candidate;
}
}
yield* Effect.logWarning(
"Claude launcher shim resolved but no known package entry was found next to it; the Claude Agent SDK cannot spawn launcher scripts directly.",
{ binaryPath, resolvedShimPath: resolved },
);
return binaryPath;
},
);
@@ -31,14 +31,23 @@ it.layer(NodeServices.layer)("ClaudeHome", (it) => {
const resolved = path.resolve(NodeOS.homedir(), ".claude-work");
expect(yield* resolveClaudeHomePath({ homePath })).toBe(resolved);
expect((yield* makeClaudeEnvironment({ homePath })).HOME).toBe(resolved);
expect((yield* makeClaudeEnvironment({ homePath })).CLAUDE_CONFIG_DIR).toBe(resolved);
expect(yield* makeClaudeContinuationGroupKey({ homePath })).toBe(`claude:home:${resolved}`);
expect(yield* makeClaudeCapabilitiesCacheKey({ binaryPath: "claude", homePath })).toBe(
`claude\0${resolved}`,
`claude\0${resolved}\0`,
);
}),
);
it.effect("separates capability probes by cwd", () =>
Effect.gen(function* () {
const config = { binaryPath: "claude", homePath: "" };
const first = yield* makeClaudeCapabilitiesCacheKey(config, "/repo-a");
const second = yield* makeClaudeCapabilitiesCacheKey(config, "/repo-b");
expect(first).not.toBe(second);
}),
);
it.effect("keeps continuation compatible across instances with the same Claude HOME", () =>
Effect.gen(function* () {
const path = yield* Path.Path;
@@ -24,7 +24,13 @@ export const makeClaudeEnvironment = Effect.fn("makeClaudeEnvironment")(function
const resolvedHomePath = yield* resolveClaudeHomePath(config);
return {
...resolvedBaseEnv,
HOME: resolvedHomePath,
// Isolate this instance's config via CLAUDE_CONFIG_DIR rather than HOME.
// Overriding HOME also relocates the macOS login keychain lookup
// ($HOME/Library/Keychains), so the spawned CLI can't find its stored
// OAuth credentials and reports "Not logged in". CLAUDE_CONFIG_DIR points
// Claude Code at its config dir directly while leaving HOME (and the
// keychain) intact.
CLAUDE_CONFIG_DIR: resolvedHomePath,
};
});
@@ -38,8 +44,9 @@ export const makeClaudeContinuationGroupKey = Effect.fn("makeClaudeContinuationG
export const makeClaudeCapabilitiesCacheKey = Effect.fn("makeClaudeCapabilitiesCacheKey")(
function* (
config: Pick<ClaudeSettings, "binaryPath" | "homePath">,
cwd?: string,
): Effect.fn.Return<string, never, Path.Path> {
const resolvedHomePath = yield* resolveClaudeHomePath(config);
return `${config.binaryPath}\0${resolvedHomePath}`;
return `${config.binaryPath}\0${resolvedHomePath}\0${cwd ?? ""}`;
},
);
@@ -114,6 +114,9 @@ it.layer(NodeServices.layer)("CodexHomeLayout", (it) => {
const sessionsTarget = yield* fileSystem.readLink(path.join(shadowHome, "sessions"));
const configTarget = yield* fileSystem.readLink(path.join(shadowHome, "config.toml"));
const mcpOauthLocksTarget = yield* fileSystem.readLink(
path.join(shadowHome, "mcp-oauth-locks"),
);
const modelsCacheExists = yield* fileSystem.exists(
path.join(shadowHome, "models_cache.json"),
);
@@ -124,12 +127,45 @@ it.layer(NodeServices.layer)("CodexHomeLayout", (it) => {
expect(sessionsTarget).toBe(path.join(sharedHome, "sessions"));
expect(configTarget).toBe(path.join(sharedHome, "config.toml"));
expect(mcpOauthLocksTarget).toBe(path.join(sharedHome, "mcp-oauth-locks"));
expect(modelsCacheExists).toBe(false);
expect(authLinkResult._tag).toBe("Failure");
expect(authContents).toContain("shadow");
}),
);
it.effect("replaces Codex-created local MCP OAuth locks with the shared lock directory", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const sharedHome = yield* makeTempDir("t3code-codex-shared-");
const shadowRoot = yield* makeTempDir("t3code-codex-shadow-root-");
const shadowHome = path.join(shadowRoot, "shadow");
const sharedLocks = path.join(sharedHome, "mcp-oauth-locks");
const shadowLocks = path.join(shadowHome, "mcp-oauth-locks");
yield* writeTextFile(path.join(sharedLocks, "file-store.lock"), "");
yield* writeTextFile(path.join(shadowLocks, "file-store.lock"), "");
const layout = yield* resolveCodexHomeLayout(
decodeCodexSettings({
homePath: sharedHome,
shadowHomePath: shadowHome,
}),
);
yield* materializeCodexShadowHome(layout);
const locksTarget = yield* fileSystem.readLink(shadowLocks);
const sharedLockExists = yield* fileSystem.exists(
path.join(sharedLocks, "file-store.lock"),
);
expect(locksTarget).toBe(sharedLocks);
expect(sharedLockExists).toBe(true);
}),
);
it.effect("accepts Codex-created shadow-local runtime directories", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -26,10 +26,12 @@ const KNOWN_SHARED_DIRECTORIES = [
"plugins",
"cache",
"logs",
"mcp-oauth-locks",
] as const;
const PRIVATE_ENTRY_NAMES = new Set(["auth.json", "models_cache.json"]);
const SHADOW_LOCAL_ENTRY_NAMES = new Set(["log", "memories", "tmp"]);
const REPLACEABLE_SHARED_RUNTIME_DIRECTORIES = new Set(["mcp-oauth-locks"]);
function resolveHomePath(path: Path.Path, value: string | undefined): string {
const expanded =
@@ -225,16 +227,6 @@ const ensureSymlink = Effect.fn("CodexHomeLayout.ensureSymlink")(function* (inpu
linkPath: link,
});
if (state._tag === "NotSymlink") {
return yield* new CodexShadowHomeEntryConflictError({
sharedHomePath: input.sharedHomePath,
effectiveHomePath: input.effectiveHomePath,
entryName: input.entryName,
linkPath: link,
targetPath: target,
});
}
const createLink = input.fileSystem.symlink(target, link).pipe(
Effect.catchTags({
PlatformError: (cause) =>
@@ -250,6 +242,33 @@ const ensureSymlink = Effect.fn("CodexHomeLayout.ensureSymlink")(function* (inpu
}),
);
if (state._tag === "NotSymlink") {
if (!REPLACEABLE_SHARED_RUNTIME_DIRECTORIES.has(input.entryName)) {
return yield* new CodexShadowHomeEntryConflictError({
sharedHomePath: input.sharedHomePath,
effectiveHomePath: input.effectiveHomePath,
entryName: input.entryName,
linkPath: link,
targetPath: target,
});
}
yield* input.fileSystem.remove(link, { recursive: true }).pipe(
Effect.catchTags({
PlatformError: (cause) =>
new CodexShadowHomeFileSystemError({
sharedHomePath: input.sharedHomePath,
effectiveHomePath: input.effectiveHomePath,
operation: "remove",
path: link,
entryName: input.entryName,
cause,
}),
}),
);
return yield* createLink;
}
if (state._tag === "Missing") {
return yield* createLink;
}
@@ -86,6 +86,7 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
defaultConfig: (): GrokSettings => decodeGrokSettings({}),
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const httpClient = yield* HttpClient.HttpClient;
const serverSettings = yield* ServerSettingsService;
@@ -128,6 +129,7 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
const checkProvider = checkGrokProviderStatus(effectiveConfig, processEnv).pipe(
Effect.map(stampIdentity),
Effect.provideService(Crypto.Crypto, crypto),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
);
@@ -2,7 +2,6 @@ import {
type ClaudeSettings,
type ModelCapabilities,
type ModelSelection,
ProviderDriverKind,
type ServerProviderModel,
type ServerProviderSlashCommand,
} from "@t3tools/contracts";
@@ -37,13 +36,13 @@ import {
spawnAndCollect,
type ServerProviderDraft,
} from "../providerSnapshot.ts";
import { resolveClaudeSdkExecutablePath } from "../Drivers/ClaudeExecutable.ts";
import { makeClaudeEnvironment } from "../Drivers/ClaudeHome.ts";
const DEFAULT_CLAUDE_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabilities({
optionDescriptors: [],
});
const PROVIDER = ProviderDriverKind.make("claudeAgent");
const CLAUDE_PRESENTATION = {
displayName: "Claude",
showInteractionModeToggle: true,
@@ -193,6 +192,36 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
],
}),
},
{
slug: "claude-sonnet-5",
name: "Claude Sonnet 5",
isCustom: false,
capabilities: createModelCapabilities({
optionDescriptors: [
buildSelectOptionDescriptor({
id: "effort",
label: "Reasoning",
options: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "xhigh", label: "Extra High" },
{ value: "max", label: "Max" },
{ value: "ultrathink", label: "Ultrathink" },
],
promptInjectedValues: ["ultrathink"],
}),
buildSelectOptionDescriptor({
id: "contextWindow",
label: "Context Window",
options: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
],
}),
],
}),
},
{
slug: "claude-sonnet-4-6",
name: "Claude Sonnet 4.6",
@@ -322,7 +351,12 @@ export function normalizeClaudeCliEffort(
if (effort === "ultracode") {
return "xhigh";
}
if (effort === "xhigh" && model !== "claude-fable-5" && model !== "claude-opus-4-8") {
if (
effort === "xhigh" &&
model !== "claude-fable-5" &&
model !== "claude-opus-4-8" &&
model !== "claude-sonnet-5"
) {
return "max";
}
if (effort === "max" && model === "claude-sonnet-4-6") {
@@ -444,9 +478,19 @@ function claudeAuthMetadata(input: {
return undefined;
}
function apiProviderAuthMetadata(
apiProvider: string | undefined,
): { readonly type: string; readonly label: string } | undefined {
return apiProvider === "bedrock" ? { type: "bedrock", label: "Amazon Bedrock" } : undefined;
}
// ── SDK capability probe ────────────────────────────────────────────
const CAPABILITIES_PROBE_TIMEOUT_MS = 8_000;
// Amazon Bedrock initializes far slower than first-party auth: the SDK boots the
// Bedrock backend and runs the `awsAuthRefresh` credential hook before returning
// account info. The previous 8s budget expired mid-init, so the probe returned
// `undefined` and left the provider unverified and unselectable in the picker.
const CAPABILITIES_PROBE_TIMEOUT_MS = 25_000;
function nonEmptyProbeString(value: string): string | undefined {
const candidate = value.trim();
@@ -457,6 +501,12 @@ type ClaudeCapabilitiesProbe = {
readonly email: string | undefined;
readonly subscriptionType: string | undefined;
readonly tokenSource: string | undefined;
/**
* Active API backend reported by the SDK's `AccountInfo`. Anthropic OAuth
* login only applies when `"firstParty"`; for Amazon Bedrock (`"bedrock"`)
* the subscription/token fields are absent and auth is external AWS creds.
*/
readonly apiProvider: string | undefined;
readonly slashCommands: ReadonlyArray<ServerProviderSlashCommand>;
};
@@ -548,10 +598,15 @@ function waitForAbortSignal(signal: AbortSignal): Promise<void> {
const probeClaudeCapabilities = (
claudeSettings: ClaudeSettings,
environment?: NodeJS.ProcessEnv,
cwd?: string,
) => {
const abort = new AbortController();
return Effect.gen(function* () {
const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);
const executablePath = yield* resolveClaudeSdkExecutablePath(
claudeSettings.binaryPath,
claudeEnvironment,
);
return yield* Effect.tryPromise(async () => {
const q = claudeQuery({
// Never yield — we only need initialization data, not a conversation.
@@ -562,11 +617,12 @@ const probeClaudeCapabilities = (
})(),
options: {
persistSession: false,
pathToClaudeCodeExecutable: claudeSettings.binaryPath,
pathToClaudeCodeExecutable: executablePath,
abortController: abort,
settingSources: ["user", "project", "local"],
allowedTools: [],
env: claudeEnvironment,
...(cwd ? { cwd } : {}),
stderr: () => {},
},
});
@@ -576,12 +632,14 @@ const probeClaudeCapabilities = (
readonly email?: string;
readonly subscriptionType?: string;
readonly tokenSource?: string;
readonly apiProvider?: string;
}
| undefined;
return {
email: account?.email,
subscriptionType: account?.subscriptionType,
tokenSource: account?.tokenSource,
apiProvider: account?.apiProvider,
slashCommands: parseClaudeInitializationCommands(init.commands),
} satisfies ClaudeCapabilitiesProbe;
});
@@ -631,7 +689,6 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
const checkedAt = DateTime.formatIso(yield* DateTime.now);
const allModels = providerModelsFromSettings(
BUILT_IN_MODELS,
PROVIDER,
claudeSettings.customModels,
DEFAULT_CLAUDE_MODEL_CAPABILITIES,
);
@@ -722,7 +779,6 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
const models = providerModelsFromSettings(
getBuiltInClaudeModelsForVersion(parsedVersion),
PROVIDER,
claudeSettings.customModels,
DEFAULT_CLAUDE_MODEL_CAPABILITIES,
);
@@ -757,10 +813,11 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
});
}
const authMetadata = claudeAuthMetadata({
subscriptionType: capabilities.subscriptionType,
authMethod: capabilities.tokenSource,
});
const authMetadata =
claudeAuthMetadata({
subscriptionType: capabilities.subscriptionType,
authMethod: capabilities.tokenSource,
}) ?? apiProviderAuthMetadata(capabilities.apiProvider);
return buildServerProvider({
presentation: CLAUDE_PRESENTATION,
enabled: claudeSettings.enabled,
@@ -790,7 +847,6 @@ export const makePendingClaudeProvider = (
const checkedAt = yield* nowIso;
const models = providerModelsFromSettings(
BUILT_IN_MODELS,
PROVIDER,
claudeSettings.customModels,
DEFAULT_CLAUDE_MODEL_CAPABILITIES,
);
@@ -26,6 +26,7 @@ import { ServerSettingsError } from "@t3tools/contracts";
import { createModelCapabilities } from "@t3tools/shared/model";
import { resolveSpawnCommand } from "@t3tools/shared/shell";
import { codexAppServerArgs, resolveCodexLaunchArgs } from "./codexLaunchArgs.ts";
import {
AUTH_PROBE_TIMEOUT_MS,
buildServerProvider,
@@ -56,6 +57,8 @@ const REASONING_EFFORT_LABELS: Readonly<Record<string, string>> = {
medium: "Medium",
high: "High",
xhigh: "Extra High",
max: "Max",
ultra: "Ultra",
};
const DEFAULT_SERVICE_TIER_ID = "default";
@@ -287,6 +290,7 @@ export function buildCodexInitializeParams(): CodexSchema.V1InitializeParams {
const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(function* (input: {
readonly binaryPath: string;
readonly homePath?: string;
readonly launchArgs?: string;
readonly cwd: string;
readonly customModels?: ReadonlyArray<string>;
readonly environment?: NodeJS.ProcessEnv;
@@ -301,10 +305,14 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun
...input.environment,
...(resolvedHomePath ? { CODEX_HOME: resolvedHomePath } : {}),
};
const spawnCommand = yield* resolveSpawnCommand(input.binaryPath, ["app-server"], {
env: environment,
extendEnv: true,
});
const spawnCommand = yield* resolveSpawnCommand(
input.binaryPath,
codexAppServerArgs(input.launchArgs),
{
env: environment,
extendEnv: true,
},
);
const child = yield* spawner
.spawn(
ChildProcess.make(spawnCommand.command, spawnCommand.args, {
@@ -463,6 +471,7 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
probe: (input: {
readonly binaryPath: string;
readonly homePath?: string;
readonly launchArgs?: string;
readonly cwd: string;
readonly customModels: ReadonlyArray<string>;
readonly environment?: NodeJS.ProcessEnv;
@@ -501,6 +510,7 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
const probeResult = yield* probe({
binaryPath: codexSettings.binaryPath,
homePath: codexSettings.homePath,
launchArgs: resolveCodexLaunchArgs(codexSettings.launchArgs, resolvedEnvironment),
cwd: process.cwd(),
customModels: codexSettings.customModels,
environment: resolvedEnvironment,
@@ -4,14 +4,16 @@ import { it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { describe } from "vite-plus/test";
import { ThreadId } from "@t3tools/contracts";
import { DEFAULT_MODEL, ThreadId } from "@t3tools/contracts";
import * as CodexErrors from "effect-codex-app-server/errors";
import * as CodexRpc from "effect-codex-app-server/rpc";
import {
buildCodexDeveloperInstructions,
CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
} from "../CodexDeveloperInstructions.ts";
import { codexSessionAppServerArgs } from "./codexLaunchArgs.ts";
import {
buildTurnStartParams,
hasConfiguredMcpServer,
@@ -118,7 +120,10 @@ describe("buildTurnStartParams", () => {
settings: {
model: "gpt-5.3-codex",
reasoning_effort: "medium",
developer_instructions: CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
developer_instructions: buildCodexDeveloperInstructions("plan", {
model: "gpt-5.3-codex",
reasoningEffort: "medium",
}),
},
},
});
@@ -163,12 +168,31 @@ describe("buildTurnStartParams", () => {
settings: {
model: "gpt-5.3-codex",
reasoning_effort: "medium",
developer_instructions: CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
developer_instructions: buildCodexDeveloperInstructions("default", {
model: "gpt-5.3-codex",
reasoningEffort: "medium",
}),
},
},
});
});
it("reports the same fallback model and effort in settings and instructions", () => {
const params = Effect.runSync(
buildTurnStartParams({
threadId: "provider-thread-1",
runtimeMode: "full-access",
prompt: "Go",
interactionMode: "default",
}),
);
const settings = params.collaborationMode?.settings;
NodeAssert.equal(settings?.model, DEFAULT_MODEL);
NodeAssert.equal(settings?.reasoning_effort, "medium");
NodeAssert.ok(settings?.developer_instructions?.includes(`as ${DEFAULT_MODEL} with medium`));
});
it("omits collaboration mode when interaction mode is absent", () => {
const params = Effect.runSync(
buildTurnStartParams({
@@ -194,6 +218,53 @@ describe("buildTurnStartParams", () => {
});
});
describe("buildCodexDeveloperInstructions", () => {
it("appends runtime info after the mode instructions", () => {
const instructions = buildCodexDeveloperInstructions("default", {
model: "gpt-5.3-codex",
reasoningEffort: "high",
});
NodeAssert.ok(instructions.startsWith(CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS));
NodeAssert.match(instructions, /T3 Code/);
NodeAssert.match(instructions, /Codex harness/);
NodeAssert.match(instructions, /as gpt-5\.3-codex with high reasoning effort/);
});
it("includes runtime info alongside plan mode instructions", () => {
const instructions = buildCodexDeveloperInstructions("plan", {
model: "gpt-5.3-codex",
reasoningEffort: "medium",
});
NodeAssert.ok(instructions.startsWith(CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS));
NodeAssert.match(instructions, /as gpt-5\.3-codex with medium reasoning effort/);
});
it("varies with the model and effort of each turn", () => {
const first = buildCodexDeveloperInstructions("default", {
model: "gpt-5.3-codex",
reasoningEffort: "medium",
});
const second = buildCodexDeveloperInstructions("default", {
model: "gpt-5.4",
reasoningEffort: "high",
});
NodeAssert.notEqual(first, second);
});
it("flattens multiline metadata into single-line runtime info", () => {
const instructions = buildCodexDeveloperInstructions("default", {
model: "gpt\n5.3\ncodex",
reasoningEffort: " high\neffort ",
});
NodeAssert.match(instructions, /as gpt 5\.3 codex with high effort reasoning effort/);
NodeAssert.doesNotMatch(instructions, /<runtime_info>[^<]*\n/);
});
});
describe("T3 browser developer instructions", () => {
it("prefers the product-native preview tools in both collaboration modes", () => {
for (const instructions of [
@@ -219,6 +290,33 @@ describe("hasConfiguredMcpServer", () => {
});
});
describe("codexSessionAppServerArgs", () => {
it("keeps the app-server subcommand when explicit args are provided", () => {
NodeAssert.deepStrictEqual(codexSessionAppServerArgs(["-c", "model=gpt-5"], undefined), [
"app-server",
"-c",
"model=gpt-5",
]);
});
it("keeps launch args when explicit app-server args are provided", () => {
NodeAssert.deepStrictEqual(
codexSessionAppServerArgs(
["-c", "mcp_servers.t3-code.url=http://127.0.0.1/mcp"],
"--strict-config --enable foo",
),
[
"app-server",
"--strict-config",
"--enable",
"foo",
"-c",
"mcp_servers.t3-code.url=http://127.0.0.1/mcp",
],
);
});
});
describe("isRecoverableThreadResumeError", () => {
it("matches missing thread errors", () => {
NodeAssert.equal(
@@ -36,11 +36,9 @@ import * as CodexRpc from "effect-codex-app-server/rpc";
import * as EffectCodexSchema from "effect-codex-app-server/schema";
import { buildCodexInitializeParams } from "./CodexProvider.ts";
import { codexSessionAppServerArgs } from "./codexLaunchArgs.ts";
import { expandHomePath } from "../../pathExpansion.ts";
import {
CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
} from "../CodexDeveloperInstructions.ts";
import { buildCodexDeveloperInstructions } from "../CodexDeveloperInstructions.ts";
const decodeV2TurnStartResponse = Schema.decodeUnknownEffect(EffectCodexSchema.V2TurnStartResponse);
const PROVIDER = ProviderDriverKind.make("codex");
@@ -100,6 +98,7 @@ export interface CodexSessionRuntimeOptions {
readonly providerInstanceId?: ProviderInstanceId;
readonly binaryPath: string;
readonly homePath?: string;
readonly launchArgs?: string;
readonly environment?: NodeJS.ProcessEnv;
readonly cwd: string;
readonly runtimeMode: RuntimeMode;
@@ -331,15 +330,16 @@ function buildCodexCollaborationMode(input: {
return undefined;
}
const model = normalizeCodexModelSlug(input.model) ?? DEFAULT_MODEL;
const reasoningEffort = input.effort ?? "medium";
return {
mode: input.interactionMode,
settings: {
model,
reasoning_effort: input.effort ?? "medium",
developer_instructions:
input.interactionMode === "plan"
? CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS
: CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
reasoning_effort: reasoningEffort,
developer_instructions: buildCodexDeveloperInstructions(input.interactionMode, {
model,
reasoningEffort,
}),
},
};
}
@@ -719,11 +719,11 @@ export const makeCodexSessionRuntime = (
...(resolvedHomePath ? { CODEX_HOME: resolvedHomePath } : {}),
};
const extendEnv = options.environment === undefined;
const spawnCommand = yield* resolveSpawnCommand(
options.binaryPath,
["app-server", ...(options.appServerArgs ?? [])],
{ env, extendEnv },
);
const appServerArgs = codexSessionAppServerArgs(options.appServerArgs, options.launchArgs);
const spawnCommand = yield* resolveSpawnCommand(options.binaryPath, appServerArgs, {
env,
extendEnv,
});
const child = yield* spawner
.spawn(
ChildProcess.make(spawnCommand.command, spawnCommand.args, {
@@ -7,7 +7,6 @@ import type {
ServerProviderModel,
ServerProviderState,
} from "@t3tools/contracts";
import { ProviderDriverKind } from "@t3tools/contracts";
import { createModelCapabilities } from "@t3tools/shared/model";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
@@ -24,7 +23,6 @@ import {
} from "../providerSnapshot.ts";
import { CursorSdkCatalog } from "./CursorSdkCatalog.ts";
const PROVIDER = ProviderDriverKind.make("cursor");
const CURSOR_PRESENTATION = {
displayName: "Cursor",
showInteractionModeToggle: true,
@@ -77,7 +75,7 @@ export function buildInitialCursorProviderSnapshot(
export function getCursorFallbackModels(
cursorSettings: Pick<CursorSettings, "customModels">,
): ReadonlyArray<ServerProviderModel> {
return providerModelsFromSettings([], PROVIDER, cursorSettings.customModels, EMPTY_CAPABILITIES);
return providerModelsFromSettings([], cursorSettings.customModels, EMPTY_CAPABILITIES);
}
function toTitleCaseWords(value: string): string {
@@ -228,7 +226,6 @@ export function buildCursorProviderSnapshot(input: {
checkedAt: input.checkedAt,
models: providerModelsFromSettings(
input.discoveredModels ?? [],
PROVIDER,
input.cursorSettings.customModels,
EMPTY_CAPABILITIES,
),
@@ -1,12 +1,12 @@
import {
type GrokSettings,
type ModelCapabilities,
ProviderDriverKind,
type ServerProvider,
type ServerProviderModel,
} from "@t3tools/contracts";
import type * as EffectAcpSchema from "effect-acp/schema";
import { causeErrorTag } from "@t3tools/shared/observability";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
@@ -36,7 +36,6 @@ const GROK_PRESENTATION = {
showInteractionModeToggle: false,
requiresNewThreadForModelChange: true,
} as const;
const PROVIDER = ProviderDriverKind.make("grok");
const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({
optionDescriptors: [],
});
@@ -96,12 +95,7 @@ function grokModelsFromSettings(
customModels: ReadonlyArray<string> | undefined,
builtInModels: ReadonlyArray<ServerProviderModel> = GROK_BUILT_IN_MODELS,
): ReadonlyArray<ServerProviderModel> {
return providerModelsFromSettings(
builtInModels,
PROVIDER,
customModels ?? [],
EMPTY_CAPABILITIES,
);
return providerModelsFromSettings(builtInModels, customModels ?? [], EMPTY_CAPABILITIES);
}
function buildGrokDiscoveredModelsFromSessionModelState(
@@ -166,7 +160,11 @@ const runGrokVersionCommand = (
export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(function* (
grokSettings: GrokSettings,
environment: NodeJS.ProcessEnv = process.env,
): Effect.fn.Return<ServerProviderDraft, never, ChildProcessSpawner.ChildProcessSpawner> {
): Effect.fn.Return<
ServerProviderDraft,
never,
ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto
> {
const checkedAt = DateTime.formatIso(yield* DateTime.now);
const fallbackModels = grokModelsFromSettings(grokSettings.customModels);
@@ -95,6 +95,13 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
}),
)
: Effect.succeed(runtimeMock.state.inventory as OpenCodeInventory),
loadInventoryFromCli: () =>
runtimeMock.state.inventoryError
? Effect.succeed({
providerList: { all: [], default: {}, connected: [] as string[] },
agents: [],
} as OpenCodeInventory)
: Effect.succeed(runtimeMock.state.inventory as OpenCodeInventory),
};
beforeEach(() => {
@@ -197,11 +204,22 @@ it.layer(testLayer)("checkOpenCodeProviderStatus", (it) => {
}),
);
it.effect("closes the local OpenCode server scope after provider refresh", () =>
it.effect("does not spawn a local server for health check (uses CLI instead)", () =>
Effect.gen(function* () {
yield* checkOpenCodeProviderStatus(makeOpenCodeSettings(), process.cwd());
NodeAssert.equal(runtimeMock.state.closeCalls, 1);
NodeAssert.equal(runtimeMock.state.closeCalls, 0);
}),
);
it.effect("degrades gracefully on CLI failure for local installs", () =>
Effect.gen(function* () {
runtimeMock.state.inventoryError = new Error("opencode models failed");
const snapshot = yield* checkOpenCodeProviderStatus(makeOpenCodeSettings(), process.cwd());
NodeAssert.equal(snapshot.status, "warning");
NodeAssert.equal(snapshot.installed, true);
NodeAssert.equal(snapshot.models.length, 0);
}),
);
});
@@ -1,5 +1,4 @@
import {
ProviderDriverKind,
type ModelCapabilities,
type OpenCodeSettings,
type ServerProviderModel,
@@ -25,7 +24,6 @@ import {
} from "../opencodeRuntime.ts";
import type { Agent, ProviderListResponse } from "@opencode-ai/sdk/v2";
const PROVIDER = ProviderDriverKind.make("opencode");
const OPENCODE_PRESENTATION = {
displayName: "OpenCode",
showInteractionModeToggle: false,
@@ -259,7 +257,6 @@ export const makePendingOpenCodeProvider = (
const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
const models = providerModelsFromSettings(
[],
PROVIDER,
openCodeSettings.customModels,
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
);
@@ -319,12 +316,7 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu
presentation: OPENCODE_PRESENTATION,
enabled: openCodeSettings.enabled,
checkedAt,
models: providerModelsFromSettings(
[],
PROVIDER,
customModels,
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
),
models: providerModelsFromSettings([], customModels, DEFAULT_OPENCODE_MODEL_CAPABILITIES),
probe: {
installed: failure.installed,
version,
@@ -340,12 +332,7 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu
presentation: OPENCODE_PRESENTATION,
enabled: false,
checkedAt,
models: providerModelsFromSettings(
[],
PROVIDER,
customModels,
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
),
models: providerModelsFromSettings([], customModels, DEFAULT_OPENCODE_MODEL_CAPABILITIES),
probe: {
installed: false,
version: null,
@@ -391,12 +378,7 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu
presentation: OPENCODE_PRESENTATION,
enabled: openCodeSettings.enabled,
checkedAt,
models: providerModelsFromSettings(
[],
PROVIDER,
customModels,
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
),
models: providerModelsFromSettings([], customModels, DEFAULT_OPENCODE_MODEL_CAPABILITIES),
probe: {
installed: true,
version,
@@ -409,26 +391,32 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu
}
const inventoryExit = yield* Effect.exit(
Effect.scoped(
Effect.gen(function* () {
const server = yield* openCodeRuntime.connectToOpenCodeServer({
binaryPath: openCodeSettings.binaryPath,
serverUrl: openCodeSettings.serverUrl,
environment: resolvedEnvironment,
});
return yield* openCodeRuntime.loadOpenCodeInventory(
openCodeRuntime.createOpenCodeSdkClient({
baseUrl: server.url,
directory: cwd,
...(isExternalServer && openCodeSettings.serverPassword
? { serverPassword: openCodeSettings.serverPassword }
: {}),
(isExternalServer
? Effect.scoped(
Effect.gen(function* () {
const server = yield* openCodeRuntime.connectToOpenCodeServer({
binaryPath: openCodeSettings.binaryPath,
serverUrl: openCodeSettings.serverUrl,
environment: resolvedEnvironment,
});
return yield* openCodeRuntime.loadOpenCodeInventory(
openCodeRuntime.createOpenCodeSdkClient({
baseUrl: server.url,
directory: cwd,
...(openCodeSettings.serverPassword
? { serverPassword: openCodeSettings.serverPassword }
: {}),
}),
);
}),
);
}).pipe(
Effect.mapError(
(cause) => new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
),
)
: openCodeRuntime.loadInventoryFromCli({
binaryPath: openCodeSettings.binaryPath,
environment: resolvedEnvironment,
})
).pipe(
Effect.mapError(
(cause) => new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
),
),
);
@@ -438,7 +426,6 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu
const models = providerModelsFromSettings(
flattenOpenCodeModels(inventoryExit.value),
PROVIDER,
customModels,
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
);
@@ -63,6 +63,7 @@ const makeCodexConfig = (overrides: Partial<CodexSettings>): CodexSettings => ({
binaryPath: "codex",
homePath: "",
shadowHomePath: "",
launchArgs: "",
customModels: [],
...overrides,
});
@@ -55,6 +55,7 @@ const encodedDefaultServerSettings = encodeServerSettings(DEFAULT_SERVER_SETTING
const defaultClaudeSettings: ClaudeSettings = Schema.decodeSync(ClaudeSettings)({});
const defaultCodexSettings: CodexSettings = Schema.decodeSync(CodexSettings)({});
const decodeCodexSettings = Schema.decodeSync(CodexSettings);
const disabledCodexSettings: CodexSettings = Schema.decodeSync(CodexSettings)({
enabled: false,
});
@@ -100,6 +101,7 @@ type TestClaudeCapabilities = {
readonly email: string | undefined;
readonly subscriptionType: string | undefined;
readonly tokenSource: string | undefined;
readonly apiProvider: string | undefined;
readonly slashCommands: ReadonlyArray<ServerProviderSlashCommand>;
};
@@ -109,6 +111,7 @@ function claudeCapabilities(overrides: Partial<TestClaudeCapabilities> = {}) {
email: undefined,
subscriptionType: undefined,
tokenSource: undefined,
apiProvider: undefined,
slashCommands: [],
...overrides,
});
@@ -346,6 +349,21 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
}),
);
it.effect("passes configured launch args to the Codex provider probe", () =>
Effect.gen(function* () {
let observedLaunchArgs: string | undefined;
const settings = decodeCodexSettings({ launchArgs: "--strict-config --enable foo" });
const status = yield* checkCodexProviderStatus(settings, (input) => {
observedLaunchArgs = input.launchArgs;
return Effect.succeed(makeCodexProbeSnapshot());
});
assert.strictEqual(status.status, "ready");
assert.strictEqual(observedLaunchArgs, "--strict-config --enable foo");
}),
);
it.effect("returns unauthenticated when app-server requires OpenAI auth", () =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus(defaultCodexSettings, () =>
@@ -1396,7 +1414,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),
Layer.provideMerge(
mockCommandSpawnerLayer((command, args) => {
if (command === "agent") {
if (command === "cursor-agent") {
cursorSpawned = true;
}
const joined = args.join(" ");
@@ -1492,6 +1510,30 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
),
);
it.effect("returns ready and labels Bedrock-backed Claude as authenticated", () =>
Effect.gen(function* () {
// Bedrock authenticates via external AWS credentials, so the SDK init
// reports only `apiProvider` with no subscription or token.
const status = yield* checkClaudeProviderStatus(
defaultClaudeSettings,
claudeCapabilities({ apiProvider: "bedrock" }),
);
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.auth.status, "authenticated");
assert.strictEqual(status.auth.type, "bedrock");
assert.strictEqual(status.auth.label, "Amazon Bedrock");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("includes Claude Fable 5 on supported Claude Code versions", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus(
@@ -1719,8 +1761,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
),
);
it.effect("runs Claude status probes with the configured Claude HOME", () => {
const claudeHome = "/tmp/t3code-claude-home";
it.effect("runs Claude status probes with the configured CLAUDE_CONFIG_DIR", () => {
const claudeConfigDir = "/tmp/t3code-claude-home";
const recorded = recordingMockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
@@ -1737,14 +1779,14 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
const status = yield* checkClaudeProviderStatus(
{
...defaultClaudeSettings,
homePath: claudeHome,
homePath: claudeConfigDir,
},
claudeCapabilities(),
);
assert.strictEqual(status.status, "ready");
assert.deepStrictEqual(
recorded.commands.map((command) => command.env?.HOME),
[claudeHome],
recorded.commands.map((command) => command.env?.CLAUDE_CONFIG_DIR),
[claudeConfigDir],
);
}).pipe(Effect.provide(recorded.layer));
});
@@ -0,0 +1,59 @@
import * as NodeAssert from "node:assert/strict";
import { describe, it } from "vite-plus/test";
import {
codexAppServerArgs,
codexExecLaunchArgs,
resolveCodexLaunchArgs,
} from "./codexLaunchArgs.ts";
describe("resolveCodexLaunchArgs", () => {
it("uses T3CODE_CODEX_LAUNCH_ARGS before configured settings", () => {
NodeAssert.equal(
resolveCodexLaunchArgs(" --strict-config ", { T3CODE_CODEX_LAUNCH_ARGS: "--enable foo" }),
"--enable foo",
);
});
it("uses configured settings when T3CODE_CODEX_LAUNCH_ARGS is empty", () => {
NodeAssert.equal(
resolveCodexLaunchArgs(" --strict-config ", { T3CODE_CODEX_LAUNCH_ARGS: " " }),
"--strict-config",
);
});
it("ignores whitespace-only environment values", () => {
NodeAssert.equal(resolveCodexLaunchArgs("", { T3CODE_CODEX_LAUNCH_ARGS: " " }), "");
});
});
describe("codexAppServerArgs", () => {
it("returns the app-server command for empty launch args", () => {
NodeAssert.deepStrictEqual(codexAppServerArgs(""), ["app-server"]);
});
it("appends parsed launch args after app-server", () => {
NodeAssert.deepStrictEqual(codexAppServerArgs("--strict-config --enable foo"), [
"app-server",
"--strict-config",
"--enable",
"foo",
]);
});
});
describe("codexExecLaunchArgs", () => {
it("keeps shared codex flags and omits app-server-only flags", () => {
NodeAssert.deepStrictEqual(
codexExecLaunchArgs('--strict-config --enable foo --listen off --config model="gpt 5"'),
["--strict-config", "--enable", "foo", "--config", "model=gpt 5"],
);
});
it("does not pair value-taking flags with adjacent flags", () => {
NodeAssert.deepStrictEqual(codexExecLaunchArgs("--config --strict-config --enable --disable"), [
"--strict-config",
]);
});
});
@@ -0,0 +1,48 @@
import { tokenizeCliArgs } from "@t3tools/shared/cliArgs";
export const T3CODE_CODEX_LAUNCH_ARGS_ENV = "T3CODE_CODEX_LAUNCH_ARGS";
export const resolveCodexLaunchArgs = (
launchArgs?: string,
environment: NodeJS.ProcessEnv = process.env,
) => environment[T3CODE_CODEX_LAUNCH_ARGS_ENV]?.trim() || launchArgs?.trim() || "";
export const codexLaunchArgv = (launchArgs?: string): ReadonlyArray<string> =>
tokenizeCliArgs(launchArgs);
export const codexAppServerArgs = (launchArgs?: string) => [
"app-server",
...codexLaunchArgv(launchArgs),
];
export const codexExecLaunchArgs = (launchArgs?: string) => {
const args = codexLaunchArgv(launchArgs);
const execArgs: Array<string> = [];
for (let index = 0; index < args.length; index++) {
const arg = args[index];
if (arg === undefined) continue;
if (arg === "--strict-config" || arg.startsWith("--config=") || arg.startsWith("-c=")) {
execArgs.push(arg);
} else if (arg === "--config" || arg === "-c" || arg === "--enable" || arg === "--disable") {
const value = args[index + 1];
if (value !== undefined && !value.startsWith("-")) {
execArgs.push(arg, value);
index++;
}
} else if (arg.startsWith("--enable=") || arg.startsWith("--disable=")) {
execArgs.push(arg);
}
}
return execArgs;
};
export const codexSessionAppServerArgs = (
appServerArgs: ReadonlyArray<string> | undefined,
launchArgs: string | undefined,
) => {
const launchAppServerArgs = codexAppServerArgs(launchArgs);
return appServerArgs ? [...launchAppServerArgs, ...appServerArgs] : launchAppServerArgs;
};
@@ -203,6 +203,43 @@ describe("AcpSessionRuntime", () => {
),
);
it.effect("keeps assistant item IDs unique when a provider session restarts", () => {
const collectFirstAssistantItemId = Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
const started = yield* runtime.start();
expect(started.sessionId).toBe("mock-session-1");
yield* runtime.prompt({
prompt: [{ type: "text", text: "hi" }],
});
const events = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 4)));
const assistantStart = events.find((event) => event._tag === "AssistantItemStarted");
expect(assistantStart?._tag).toBe("AssistantItemStarted");
return assistantStart?._tag === "AssistantItemStarted" ? assistantStart.itemId : "";
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
spawn: {
command: mockAgentCommand,
args: mockAgentArgs,
},
cwd: process.cwd(),
clientInfo: { name: "t3-test", version: "0.0.0" },
authMethodId: "test",
}),
),
Effect.scoped,
);
return Effect.gen(function* () {
const beforeRestart = yield* collectFirstAssistantItemId;
const afterRestart = yield* collectFirstAssistantItemId;
expect(afterRestart).not.toBe(beforeRestart);
}).pipe(Effect.provide(NodeServices.layer));
});
it.effect("drops session updates emitted for a child ACP session", () =>
Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
@@ -1,6 +1,7 @@
import * as Cause from "effect/Cause";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
@@ -281,7 +282,7 @@ export class AcpSessionRuntime extends Context.Service<
): Layer.Layer<
AcpSessionRuntime,
EffectAcpErrors.AcpError,
ChildProcessSpawner.ChildProcessSpawner
ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto
> {
return Layer.effect(AcpSessionRuntime, make(options));
}
@@ -312,14 +313,24 @@ export const make = (
): Effect.Effect<
AcpSessionRuntime["Service"],
EffectAcpErrors.AcpError,
ChildProcessSpawner.ChildProcessSpawner | Scope.Scope
ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | Scope.Scope
> =>
Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const runtimeScope = yield* Scope.Scope;
const eventQueue = yield* Queue.unbounded<AcpSessionRuntimeEvent>();
const modeStateRef = yield* Ref.make<AcpSessionModeState | undefined>(undefined);
const toolCallsRef = yield* Ref.make(new Map<string, AcpToolCallState>());
const assistantItemRuntimeId = yield* crypto.randomUUIDv4.pipe(
Effect.mapError(
(cause) =>
new EffectAcpErrors.AcpTransportError({
detail: "Failed to generate an ACP assistant item runtime identifier.",
cause,
}),
),
);
const assistantSegmentRef = yield* Ref.make<AcpAssistantSegmentState>({ nextSegmentIndex: 0 });
const configOptionsRef = yield* Ref.make(sessionConfigOptionsFromSetup(undefined));
const startStateRef = yield* Ref.make<AcpStartState>({ _tag: "NotStarted" });
@@ -429,6 +440,7 @@ export const make = (
modeStateRef,
toolCallsRef,
assistantSegmentRef,
assistantItemRuntimeId,
params: notification,
});
}),
@@ -991,7 +1003,7 @@ export const layer = (
): Layer.Layer<
AcpSessionRuntime,
EffectAcpErrors.AcpError,
ChildProcessSpawner.ChildProcessSpawner
ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto
> => Layer.effect(AcpSessionRuntime, make(options));
function sessionConfigOptionsFromSetup(
@@ -1023,12 +1035,14 @@ const handleSessionUpdate = ({
modeStateRef,
toolCallsRef,
assistantSegmentRef,
assistantItemRuntimeId,
params,
}: {
readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;
readonly modeStateRef: Ref.Ref<AcpSessionModeState | undefined>;
readonly toolCallsRef: Ref.Ref<Map<string, AcpToolCallState>>;
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
readonly assistantItemRuntimeId: string;
readonly params: EffectAcpSchema.SessionNotification;
}): Effect.Effect<void> =>
Effect.gen(function* () {
@@ -1076,6 +1090,7 @@ const handleSessionUpdate = ({
queue,
assistantSegmentRef,
sessionId: params.sessionId,
assistantItemRuntimeId,
});
yield* Queue.offer(queue, {
...event,
@@ -1113,17 +1128,19 @@ function shouldEmitToolCallUpdate(
return previous === undefined || previous.title !== next.title || previous.detail !== next.detail;
}
const assistantItemId = (sessionId: string, segmentIndex: number) =>
`assistant:${sessionId}:segment:${segmentIndex}`;
const assistantItemId = (sessionId: string, runtimeId: string, segmentIndex: number) =>
`assistant:${sessionId}:runtime:${runtimeId}:segment:${segmentIndex}`;
const ensureActiveAssistantSegment = ({
queue,
assistantSegmentRef,
sessionId,
assistantItemRuntimeId,
}: {
readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
readonly sessionId: string;
readonly assistantItemRuntimeId: string;
}) =>
Ref.modify<AcpAssistantSegmentState, EnsureActiveAssistantSegmentResult>(
assistantSegmentRef,
@@ -1131,7 +1148,7 @@ const ensureActiveAssistantSegment = ({
if (current.activeItemId) {
return [{ itemId: current.activeItemId }, current] as const;
}
const itemId = assistantItemId(sessionId, current.nextSegmentIndex);
const itemId = assistantItemId(sessionId, assistantItemRuntimeId, current.nextSegmentIndex);
return [
{
itemId,
@@ -1,4 +1,5 @@
import { type GrokSettings, ProviderDriverKind } from "@t3tools/contracts";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Scope from "effect/Scope";
@@ -55,7 +56,7 @@ export const makeGrokAcpRuntime = (
): Effect.Effect<
AcpSessionRuntime.AcpSessionRuntime["Service"],
EffectAcpErrors.AcpError,
Scope.Scope
Crypto.Crypto | Scope.Scope
> =>
Effect.gen(function* () {
const acpContext = yield* Layer.build(
@@ -0,0 +1,229 @@
import * as NodeAssert from "node:assert/strict";
import { describe, it } from "vite-plus/test";
import { parseModelsCliOutput, parseAgentListCliOutput } from "./opencodeRuntime.ts";
describe("parseModelsCliOutput", () => {
it("parses a single model from a single provider", () => {
const stdout = [
"anthropic/claude-sonnet-4-5",
JSON.stringify({
id: "claude-sonnet-4-5",
providerID: "anthropic",
name: "Claude Sonnet 4.5",
capabilities: { temperature: true, reasoning: true, toolcall: true },
cost: { input: 3, output: 15 },
limit: { context: 200000, output: 8192 },
status: "active",
options: {},
headers: {},
release_date: "2025-01-01",
}),
].join("\n");
const result = parseModelsCliOutput(stdout);
NodeAssert.equal(result.providers.size, 1);
NodeAssert.equal(result.connected.length, 1);
NodeAssert.equal(result.connected[0], "anthropic");
const provider = result.providers.get("anthropic")!;
NodeAssert.ok(provider);
NodeAssert.equal(provider.id, "anthropic");
NodeAssert.equal(provider.name, "anthropic");
NodeAssert.equal(Object.keys(provider.models).length, 1);
const model = provider.models["claude-sonnet-4-5"]!;
NodeAssert.ok(model);
NodeAssert.equal(model.id, "claude-sonnet-4-5");
NodeAssert.equal(model.providerID, "anthropic");
NodeAssert.equal(model.name, "Claude Sonnet 4.5");
});
it("parses multiple models from multiple providers", () => {
const stdout = [
"anthropic/claude-sonnet-4-5",
JSON.stringify({ id: "claude-sonnet-4-5", providerID: "anthropic", name: "Sonnet 4.5" }),
"anthropic/claude-haiku-4-5",
JSON.stringify({ id: "claude-haiku-4-5", providerID: "anthropic", name: "Haiku 4.5" }),
"openai/gpt-4o",
JSON.stringify({ id: "gpt-4o", providerID: "openai", name: "GPT-4o" }),
].join("\n");
const result = parseModelsCliOutput(stdout);
NodeAssert.equal(result.providers.size, 2);
NodeAssert.equal(result.connected.length, 2);
NodeAssert.equal([...result.connected].sort().join(","), "anthropic,openai");
NodeAssert.equal(Object.keys(result.providers.get("anthropic")!.models).length, 2);
NodeAssert.equal(Object.keys(result.providers.get("openai")!.models).length, 1);
});
it("handles empty input", () => {
const result = parseModelsCliOutput("");
NodeAssert.equal(result.providers.size, 0);
NodeAssert.equal(result.connected.length, 0);
});
it("skips unparseable JSON blocks", () => {
const stdout = [
"anthropic/claude-sonnet-4-5",
"this is not valid json {{{",
"anthropic/claude-haiku-4-5",
JSON.stringify({ id: "claude-haiku-4-5", providerID: "anthropic", name: "Haiku 4.5" }),
].join("\n");
const result = parseModelsCliOutput(stdout);
NodeAssert.equal(result.providers.size, 1);
const provider = result.providers.get("anthropic")!;
NodeAssert.equal(Object.keys(provider.models).length, 1);
NodeAssert.ok(provider.models["claude-haiku-4-5"]);
});
it("handles Windows-style CRLF line endings", () => {
const stdout =
"anthropic/claude-sonnet-4-5\r\n" +
JSON.stringify({ id: "claude-sonnet-4-5", providerID: "anthropic", name: "Sonnet" }) +
"\r\n";
const result = parseModelsCliOutput(stdout);
NodeAssert.equal(result.providers.size, 1);
NodeAssert.ok(result.providers.get("anthropic")!.models["claude-sonnet-4-5"]);
});
it("handles model JSON with variants and nested fields", () => {
const stdout = [
"opencode/gpt-5.4",
JSON.stringify({
id: "gpt-5.4",
providerID: "opencode",
name: "GPT-5.4",
family: "gpt",
capabilities: {
temperature: true,
reasoning: true,
attachment: false,
toolcall: true,
input: { text: true, audio: false, image: false, video: false, pdf: false },
output: { text: true, audio: false, image: false, video: false, pdf: false },
interleaved: false,
},
cost: { input: 0, output: 0, cache: { read: 0, write: 0 } },
limit: { context: 200000, input: 160000, output: 32000 },
status: "active",
options: {},
headers: {},
release_date: "2025-01-01",
variants: { none: {}, low: {}, medium: {}, high: {} },
}),
].join("\n");
const result = parseModelsCliOutput(stdout);
const model = result.providers.get("opencode")!.models["gpt-5.4"]!;
NodeAssert.ok(model);
NodeAssert.ok(model.capabilities);
NodeAssert.equal(model.capabilities!.reasoning, true);
NodeAssert.ok(model.variants);
NodeAssert.equal(model.variants!["medium"] !== undefined, true);
});
});
describe("parseAgentListCliOutput", () => {
it("parses a single agent", () => {
const stdout = [
"build (primary)",
" " + JSON.stringify([{ permission: "*", action: "allow", pattern: "*" }]),
].join("\n");
const result = parseAgentListCliOutput(stdout);
NodeAssert.equal(result.length, 1);
NodeAssert.equal(result[0]!.name, "build");
NodeAssert.equal(result[0]!.mode, "primary");
NodeAssert.equal(result[0]!.permission.length, 1);
});
it("parses multiple agents", () => {
const stdout = [
"build (primary)",
" " + JSON.stringify([{ permission: "*", action: "allow", pattern: "*" }]),
"explore (subagent)",
" " + JSON.stringify([{ permission: "read", action: "allow", pattern: "*" }]),
"plan (primary)",
" " + JSON.stringify([{ permission: "edit", action: "ask", pattern: "*.md" }]),
].join("\n");
const result = parseAgentListCliOutput(stdout);
NodeAssert.equal(result.length, 3);
NodeAssert.equal(result[0]!.name, "build");
NodeAssert.equal(result[0]!.mode, "primary");
NodeAssert.equal(result[1]!.name, "explore");
NodeAssert.equal(result[1]!.mode, "subagent");
NodeAssert.equal(result[2]!.name, "plan");
NodeAssert.equal(result[2]!.mode, "primary");
});
it("handles empty input", () => {
const result = parseAgentListCliOutput("");
NodeAssert.equal(result.length, 0);
});
it("skips agents with unparseable permission JSON", () => {
const stdout = [
"build (primary)",
" not valid json {",
"explore (subagent)",
" " + JSON.stringify([{ permission: "read", action: "allow", pattern: "*" }]),
].join("\n");
const result = parseAgentListCliOutput(stdout);
NodeAssert.equal(result.length, 1);
NodeAssert.equal(result[0]!.name, "explore");
});
it("handles real-world permission blocks with nested paths", () => {
const permissions = [
{ permission: "*", action: "allow", pattern: "*" },
{
permission: "external_directory",
pattern: "C:\\Users\\test\\.local\\*",
action: "allow",
},
{ permission: "read", pattern: "*.env", action: "ask" },
];
const stdout = ["build (primary)", " " + JSON.stringify(permissions)].join("\n");
const result = parseAgentListCliOutput(stdout);
NodeAssert.equal(result.length, 1);
NodeAssert.equal(result[0]!.permission.length, 3);
NodeAssert.equal(result[0]!.permission[0]!.action, "allow");
NodeAssert.equal(result[0]!.permission[2]!.action, "ask");
});
it("handles agent names with spaces", () => {
const stdout = [
"code reviewer (subagent)",
" " + JSON.stringify([{ permission: "read", action: "allow", pattern: "*" }]),
"my custom agent (primary)",
" " + JSON.stringify([{ permission: "edit", action: "ask", pattern: "*.ts" }]),
].join("\n");
const result = parseAgentListCliOutput(stdout);
NodeAssert.equal(result.length, 2);
NodeAssert.equal(result[0]!.name, "code reviewer");
NodeAssert.equal(result[0]!.mode, "subagent");
NodeAssert.equal(result[1]!.name, "my custom agent");
NodeAssert.equal(result[1]!.mode, "primary");
});
it("marks known hidden agents", () => {
const stdout = [
"compaction (primary)",
" " + JSON.stringify([{ permission: "*", action: "allow", pattern: "*" }]),
"build (primary)",
" " + JSON.stringify([{ permission: "*", action: "allow", pattern: "*" }]),
].join("\n");
const result = parseAgentListCliOutput(stdout);
NodeAssert.equal(result[0]!.hidden, true);
NodeAssert.equal(result[1]!.hidden, false);
});
});
+177 -1
View File
@@ -5,6 +5,7 @@ import {
createOpencodeClient,
type Agent,
type FilePartInput,
type Model,
type OpencodeClient,
type PermissionRuleset,
type ProviderListResponse,
@@ -37,7 +38,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_MS = 5_000;
const DEFAULT_OPENCODE_SERVER_TIMEOUT_MS = 30_000;
const DEFAULT_HOSTNAME = "127.0.0.1";
export interface OpenCodeServerProcess {
readonly url: string;
@@ -147,6 +148,10 @@ export interface OpenCodeRuntimeShape {
readonly loadOpenCodeInventory: (
client: OpencodeClient,
) => Effect.Effect<OpenCodeInventory, OpenCodeRuntimeError>;
readonly loadInventoryFromCli: (input: {
readonly binaryPath: string;
readonly environment?: NodeJS.ProcessEnv;
}) => Effect.Effect<OpenCodeInventory, OpenCodeRuntimeError>;
}
function parseServerUrlFromOutput(output: string): string | null {
@@ -160,6 +165,113 @@ function parseServerUrlFromOutput(output: string): string | null {
return null;
}
const SLUG_LINE_RE = /^(\S+\/\S+)\s*$/;
const AGENT_HEADER_RE = /^(.+)\s+\((\S+)\)\s*$/;
// Agents that are always hidden in OpenCode but the CLI "agent list" command
// does not expose the hidden flag. Keep in sync with OpenCode agent
// definitions (in the OpenCode repo: packages/opencode/src/agent/agent.ts).
const KNOWN_HIDDEN_AGENTS = new Set(["compaction", "summary", "title"]);
/** @internal */
export function parseModelsCliOutput(stdout: string): {
readonly providers: ReadonlyMap<
string,
{ readonly id: string; readonly name: string; readonly models: { [key: string]: Model } }
>;
readonly connected: ReadonlyArray<string>;
} {
const providers = new Map<
string,
{ id: string; name: string; models: { [key: string]: Model } }
>();
const lines = stdout.split("\n");
let currentSlug: string | null = null;
const jsonLines: Array<string> = [];
const flushModel = () => {
if (currentSlug !== null && jsonLines.length > 0) {
const jsonStr = jsonLines.join("\n").trim();
if (jsonStr.length > 0) {
try {
const model = JSON.parse(jsonStr) as Model;
const separator = currentSlug.indexOf("/");
if (separator > 0) {
const providerID = currentSlug.slice(0, separator);
const modelID = currentSlug.slice(separator + 1);
let provider = providers.get(providerID);
if (!provider) {
provider = { id: providerID, name: providerID, models: {} };
providers.set(providerID, provider);
}
provider.models[modelID] = model;
}
} catch {
// Skip unparseable model JSON
}
}
}
currentSlug = null;
jsonLines.length = 0;
};
for (const line of lines) {
const slugMatch = SLUG_LINE_RE.exec(line);
if (slugMatch) {
flushModel();
currentSlug = slugMatch[1]!;
} else if (currentSlug !== null) {
jsonLines.push(line);
}
}
flushModel();
return { providers, connected: [...providers.keys()] };
}
/** @internal */
export function parseAgentListCliOutput(stdout: string): ReadonlyArray<Agent> {
const agents: Array<Agent> = [];
const lines = stdout.split("\n");
let currentHeader: { name: string; mode: string } | null = null;
const blockLines: Array<string> = [];
const flushAgent = () => {
if (currentHeader !== null) {
const jsonStr = blockLines.join("\n").trim();
if (jsonStr.length > 0) {
try {
const permission = JSON.parse(jsonStr);
agents.push({
name: currentHeader.name,
mode: currentHeader.mode as Agent["mode"],
hidden: KNOWN_HIDDEN_AGENTS.has(currentHeader.name),
permission,
options: {},
});
} catch {
// Skip unparseable agent
}
}
}
currentHeader = null;
blockLines.length = 0;
};
for (const line of lines) {
const match = AGENT_HEADER_RE.exec(line);
if (match) {
flushAgent();
currentHeader = { name: match[1]!, mode: match[2]! };
} else if (currentHeader !== null) {
blockLines.push(line);
}
}
flushAgent();
return agents;
}
export function parseOpenCodeModelSlug(
slug: string | null | undefined,
): ParsedOpenCodeModelSlug | null {
@@ -542,12 +654,76 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
Effect.map(([providerList, agents]) => ({ providerList, agents })),
);
const loadInventoryFromCli: OpenCodeRuntimeShape["loadInventoryFromCli"] = (input) =>
Effect.gen(function* () {
const env = input.environment !== undefined ? { environment: input.environment } : ({} as {});
const runModelsCli = () =>
runOpenCodeCommand({
binaryPath: input.binaryPath,
args: ["models", "--verbose"],
...env,
}).pipe(Effect.exit);
const runAgentsCli = () =>
runOpenCodeCommand({ binaryPath: input.binaryPath, args: ["agent", "list"], ...env }).pipe(
Effect.exit,
);
// First attempt — run both in parallel
let [modelsResult, agentsResult] = yield* Effect.all([runModelsCli(), runAgentsCli()], {
concurrency: "unbounded",
});
// Retry once after 1s on transient failures (e.g. SQLite "database is locked")
const needsModelsRetry = modelsResult._tag === "Failure" || modelsResult.value.code !== 0;
const needsAgentsRetry = agentsResult._tag === "Failure" || agentsResult.value.code !== 0;
if (needsModelsRetry || needsAgentsRetry) {
yield* Effect.sleep("1 second");
const [m2, a2] = yield* Effect.all(
[
needsModelsRetry ? runModelsCli() : Effect.succeed(modelsResult),
needsAgentsRetry ? runAgentsCli() : Effect.succeed(agentsResult),
],
{ concurrency: "unbounded" },
);
modelsResult = m2;
agentsResult = a2;
}
// Degrade gracefully on failure — return empty inventory (warning status, not error)
let connected: string[] = [];
let allProviders: ProviderListResponse["all"] = [];
if (modelsResult._tag === "Success" && modelsResult.value.code === 0) {
const parsed = parseModelsCliOutput(modelsResult.value.stdout);
connected = [...parsed.connected];
allProviders = [...parsed.providers.values()].map((p) => ({
id: p.id,
name: p.name,
source: "config" as const,
env: [],
options: {},
models: p.models,
}));
}
let agents: ReadonlyArray<Agent> = [];
if (agentsResult._tag === "Success" && agentsResult.value.code === 0) {
agents = parseAgentListCliOutput(agentsResult.value.stdout);
}
return {
providerList: { all: allProviders, default: {}, connected },
agents,
};
});
return {
startOpenCodeServerProcess,
connectToOpenCodeServer,
runOpenCodeCommand,
createOpenCodeSdkClient,
loadOpenCodeInventory,
loadInventoryFromCli,
} satisfies OpenCodeRuntimeShape;
});
@@ -1,5 +1,5 @@
import { describe, expect, it } from "@effect/vitest";
import { ProviderDriverKind, type ModelCapabilities } from "@t3tools/contracts";
import type { ModelCapabilities } from "@t3tools/contracts";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { createModelCapabilities } from "@t3tools/shared/model";
import * as Effect from "effect/Effect";
@@ -38,7 +38,6 @@ describe("providerModelsFromSettings", () => {
it("applies the provided capabilities to custom models", () => {
const models = providerModelsFromSettings(
[],
ProviderDriverKind.make("opencode"),
["openai/gpt-5"],
OPENCODE_CUSTOM_MODEL_CAPABILITIES,
);
@@ -52,6 +51,25 @@ describe("providerModelsFromSettings", () => {
},
]);
});
it("preserves a custom slug that collides with a provider alias", () => {
const capabilities = createModelCapabilities({ optionDescriptors: [] });
const models = providerModelsFromSettings(
[
{
slug: "claude-opus-4-8",
name: "Claude Opus 4.8",
isCustom: false,
capabilities,
},
],
[" opus "],
capabilities,
);
expect(models.map((model) => model.slug)).toEqual(["claude-opus-4-8", "opus"]);
expect(models[1]?.isCustom).toBe(true);
});
});
describe("ProviderCommandNotFoundError", () => {
+2 -3
View File
@@ -13,7 +13,7 @@ import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { normalizeModelSlug } from "@t3tools/shared/model";
import { normalizeCustomModelSlug } from "@t3tools/shared/model";
import { isWindowsCommandNotFound } from "../processRunner.ts";
import { createProviderVersionAdvisory } from "./providerMaintenance.ts";
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
@@ -140,7 +140,6 @@ export function parseGenericCliVersion(output: string): string | null {
export function providerModelsFromSettings(
builtInModels: ReadonlyArray<ServerProviderModel>,
provider: ProviderDriverKind,
customModels: ReadonlyArray<string>,
customModelCapabilities: ModelCapabilities,
): ReadonlyArray<ServerProviderModel> {
@@ -149,7 +148,7 @@ export function providerModelsFromSettings(
const customEntries: ServerProviderModel[] = [];
for (const candidate of customModels) {
const normalized = normalizeModelSlug(candidate, provider);
const normalized = normalizeCustomModelSlug(candidate);
if (!normalized || seen.has(normalized)) {
continue;
}
@@ -181,6 +181,24 @@ const makePublishProof = Effect.fn("makePublishProof")(function* (input: {
return yield* signRelayAgentActivityPublishProof({ privateKey: input.privateKey, payload });
});
// Compact, log-safe view of the fields the awareness phase ladder reads.
export function describeThreadShellForAwareness(
thread: Option.Option<OrchestrationV2ThreadShell>,
): Record<string, unknown> {
if (Option.isNone(thread)) {
return { found: false };
}
const shell = thread.value;
return {
found: true,
status: shell.status,
activeRunId: shell.activeRunId ?? null,
latestRunId: shell.latestRunId ?? null,
pendingRuntimeRequestKind: shell.pendingRuntimeRequest?.kind ?? null,
hasActionableProposedPlan: shell.hasActionableProposedPlan,
};
}
export function resolveAgentAwarenessRelayPublishSnapshot(input: {
readonly environmentId: EnvironmentId;
readonly threadId: ThreadId;
@@ -284,6 +302,14 @@ export const make = Effect.gen(function* () {
transformClient: relayEnvironmentClient(relayConfig.environmentCredential),
}).pipe(Effect.provide(FetchHttpClient.layer));
// Deadlines for publishes that need confirmation (tombstones and
// first-state completions). The confirming publish is re-enqueued through
// the same drainable worker as every other publish, so a confirmed
// tombstone can never race an in-flight live update; a recovered state
// clears the deadline. Assigned after the worker exists.
const publishConfirmDeadlines = new Map<ThreadId, number>();
let schedulePublishConfirm: (threadId: ThreadId) => Effect.Effect<void> = () => Effect.void;
const publishThreadUnsafe = Effect.fn("publishThreadUnsafe")(function* (threadId: ThreadId) {
const publishAgentActivity = yield* readPublishAgentActivityEnabled.pipe(
Effect.orElseSucceed(() => false),
@@ -362,6 +388,11 @@ export const make = Effect.gen(function* () {
const publishIdentity = agentAwarenessPublishIdentity(snapshot.state);
const publishedStateByThread = yield* Ref.get(publishedStateByThreadRef);
if (publishedStateByThread.get(threadId) === publishIdentity) {
// The projection is back at (or never left) the last published state, so
// any pending deferred confirmation is moot. Leaving the deadline in
// place would let a much later transient null find it already expired
// and publish a tombstone immediately, skipping the deferral window.
publishConfirmDeadlines.delete(threadId);
yield* Effect.logDebug("agent activity publish skipped; projected state unchanged", {
environmentId,
threadId,
@@ -370,6 +401,50 @@ export const make = Effect.gen(function* () {
return;
}
// Two projections need confirmation before publishing, because both can
// appear transiently while the projector is mid-write and publishing them
// immediately is destructive or noisy:
// - null (tombstone) while the previous published state was live: deletes
// the thread from every armed card mid-conversation.
// - completed as the thread's FIRST published state: sessions boot at
// "ready" before their first turn, which projects as completed for an
// instant and sends a spurious Done notification at thread birth.
// Defer, schedule a re-publish through the ordinary worker queue, and
// only publish if the projection still holds when it drains.
const requiresConfirmation =
(snapshot.state === null &&
publishedStateByThread.get(threadId) !== agentAwarenessPublishIdentity(null)) ||
(snapshot.state?.phase === "completed" && !publishedStateByThread.has(threadId));
if (requiresConfirmation) {
const nowMs = (yield* DateTime.now).epochMilliseconds;
const deadline = publishConfirmDeadlines.get(threadId);
if (deadline === undefined) {
publishConfirmDeadlines.set(threadId, nowMs + 5_000);
yield* Effect.logInfo("agent activity publish deferred pending confirmation", {
environmentId,
threadId,
reason: snapshot.reason,
statePhase: snapshot.state?.phase ?? null,
shell: describeThreadShellForAwareness(thread),
});
yield* schedulePublishConfirm(threadId);
return;
}
if (nowMs < deadline) {
return;
}
publishConfirmDeadlines.delete(threadId);
yield* Effect.logInfo("agent activity deferred publish confirmed", {
environmentId,
threadId,
reason: snapshot.reason,
statePhase: snapshot.state?.phase ?? null,
shell: describeThreadShellForAwareness(thread),
});
} else {
publishConfirmDeadlines.delete(threadId);
}
if (snapshot.reason === "thread-not-found") {
yield* Effect.logDebug("publishing agent activity tombstone; thread not found", {
environmentId,
@@ -461,6 +536,19 @@ export const make = Effect.gen(function* () {
const worker = yield* makeDrainableWorker(publishThread);
schedulePublishConfirm = (threadId) =>
Effect.forkDetach(
Effect.sleep("5 seconds").pipe(
Effect.andThen(worker.enqueue(threadId)),
Effect.catchCause((cause) =>
Effect.logWarning("deferred agent activity confirmation failed", {
threadId,
cause: Cause.pretty(cause),
}),
),
),
).pipe(Effect.asVoid);
const start: AgentAwarenessRelay["Service"]["start"] = Effect.fn("AgentAwarenessRelay.start")(
function* () {
const [relayConfig, publishEnabled] = yield* Effect.all([
+6 -1
View File
@@ -82,6 +82,7 @@ import {
makePersistedServerRuntimeState,
persistServerRuntimeState,
} from "./serverRuntimeState.ts";
import { orchestrationHttpApiLayer } from "./orchestration-v2/http.ts";
import { projectHttpApiLayer } from "./project/http.ts";
import * as NetService from "@t3tools/shared/Net";
import * as RelayClient from "@t3tools/shared/relayClient";
@@ -294,7 +295,10 @@ const RuntimeCoreDependenciesLive = RuntimeCoreDependenciesBaseLive.pipe(
Layer.provideMerge(ServerSecretStore.layer),
Layer.provideMerge(
Layer.mergeAll(
CloudCliTokenManager.layer.pipe(Layer.provide(ServerSecretStore.layer)),
CloudCliTokenManager.layer.pipe(
Layer.provide(ServerSecretStore.layer),
Layer.provide(ExternalLauncher.layer),
),
CloudManagedEndpointRuntimeLive,
),
),
@@ -320,6 +324,7 @@ export const makeRoutesLayer = Layer.mergeAll(
HttpApiBuilder.layer(EnvironmentHttpApi).pipe(
Layer.provide(authHttpApiLayer),
Layer.provide(connectHttpApiLayer),
Layer.provide(orchestrationHttpApiLayer),
Layer.provide(projectHttpApiLayer),
Layer.provide(serverEnvironmentHttpApiLayer),
Layer.provide(environmentAuthenticatedAuthLayer),
+2
View File
@@ -179,6 +179,7 @@ it.layer(NodeServices.layer)("server settings", (it) => {
binaryPath: "/opt/homebrew/bin/codex",
homePath: "/Users/julius/.codex",
shadowHomePath: "",
launchArgs: "",
customModels: [],
});
assert.deepEqual(next.providers.claudeAgent, {
@@ -420,6 +421,7 @@ it.layer(NodeServices.layer)("server settings", (it) => {
binaryPath: "/opt/homebrew/bin/codex",
homePath: "",
shadowHomePath: "",
launchArgs: "",
customModels: [],
});
assert.deepEqual(next.providers.claudeAgent, {
+57
View File
@@ -1334,6 +1334,63 @@ it.layer(
}),
);
it.effect("strips AppImage runtime env from terminal sessions", () =>
Effect.gen(function* () {
const appDir = "/tmp/.mount_T3Codeabc123";
const { manager, ptyAdapter } = yield* createManager(5, {
env: {
APPIMAGE: "/home/user/T3-Code.AppImage",
APPDIR: appDir,
ARGV0: "/home/user/T3-Code.AppImage",
OWD: "/home/user/project",
PATH: `${appDir}/usr/bin:${appDir}:/usr/local/bin:/usr/bin:/bin`,
LD_LIBRARY_PATH: `${appDir}/usr/lib:/home/user/.local/lib`,
TEST_TERMINAL_KEEP: "keep-me",
},
});
yield* manager.open(openInput());
const spawnInput = ptyAdapter.spawnInputs[0];
expect(spawnInput).toBeDefined();
if (!spawnInput) return;
// AppImage runtime markers must never reach the PTY — tools inside the
// terminal otherwise resolve against the AppImage mount (e.g. PHP_BINARY
// reporting the AppImage path instead of the real binary).
expect(spawnInput.env.APPIMAGE).toBeUndefined();
expect(spawnInput.env.APPDIR).toBeUndefined();
expect(spawnInput.env.ARGV0).toBeUndefined();
expect(spawnInput.env.OWD).toBeUndefined();
// PATH/LD_LIBRARY_PATH keep the user's real entries but drop the AppImage
// mount segments that the runtime prepended.
expect(spawnInput.env.PATH).toBe("/usr/local/bin:/usr/bin:/bin");
expect(spawnInput.env.LD_LIBRARY_PATH).toBe("/home/user/.local/lib");
// Unrelated host vars still pass through untouched.
expect(spawnInput.env.TEST_TERMINAL_KEEP).toBe("keep-me");
}),
);
it.effect("leaves the environment untouched when not launched from an AppImage", () =>
Effect.gen(function* () {
const { manager, ptyAdapter } = yield* createManager(5, {
env: {
PATH: "/usr/local/bin:/usr/bin:/bin",
LD_LIBRARY_PATH: "/home/user/.local/lib",
// Without APPIMAGE/APPDIR set, OWD is an ordinary variable and must
// not be stripped — only an AppImage launch gives it special meaning.
OWD: "/home/user/keep-this",
},
});
yield* manager.open(openInput());
const spawnInput = ptyAdapter.spawnInputs[0];
expect(spawnInput).toBeDefined();
if (!spawnInput) return;
expect(spawnInput.env.PATH).toBe("/usr/local/bin:/usr/bin:/bin");
expect(spawnInput.env.LD_LIBRARY_PATH).toBe("/home/user/.local/lib");
expect(spawnInput.env.OWD).toBe("/home/user/keep-this");
}),
);
it.effect("injects runtime env overrides into spawned terminals", () =>
Effect.gen(function* () {
const { manager, ptyAdapter } = yield* createManager();
+48 -1
View File
@@ -1065,6 +1065,53 @@ function shouldExcludeTerminalEnvKey(key: string): boolean {
return TERMINAL_ENV_BLOCKLIST.has(normalizedKey);
}
// Marker variables the AppImage runtime injects into the process it launches.
// They describe the AppImage itself, not the user's session, so terminals must
// not inherit them.
const APPIMAGE_RUNTIME_ENV_KEYS = ["APPIMAGE", "APPDIR", "ARGV0", "OWD"] as const;
// PATH-style variables the AppImage runtime prepends with its temporary mount
// (e.g. /tmp/.mount_T3-XXXX/usr/bin). Only the mount segments are dropped; the
// user's real entries are preserved.
const APPIMAGE_PATH_LIKE_ENV_KEYS = ["PATH", "LD_LIBRARY_PATH"] as const;
function isPathSegmentUnderAppDir(segment: string, appDir: string): boolean {
return segment === appDir || segment.startsWith(`${appDir}/`);
}
// On Linux AppImage builds the runtime mounts the app under a temporary dir and
// injects APPIMAGE/APPDIR/ARGV0/OWD plus mount entries on PATH/LD_LIBRARY_PATH.
// The integrated terminal inherits the server process environment, so without
// this scrub those leak into the PTY and tools resolve against the AppImage
// mount instead of the user's real environment (e.g. `php` reporting
// PHP_BINARY as the AppImage path). See issue #1699. The scrub is gated on an
// actual AppImage launch so non-AppImage environments are left untouched.
function stripAppImageRuntimeEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
if (env.APPIMAGE === undefined && env.APPDIR === undefined) return env;
const scrubbed: NodeJS.ProcessEnv = { ...env };
for (const key of APPIMAGE_RUNTIME_ENV_KEYS) {
delete scrubbed[key];
}
const appDir = env.APPDIR?.replace(/\/+$/, "");
if (appDir) {
for (const key of APPIMAGE_PATH_LIKE_ENV_KEYS) {
const value = scrubbed[key];
if (value === undefined) continue;
const kept = value
.split(":")
.filter((segment) => segment.length > 0 && !isPathSegmentUnderAppDir(segment, appDir));
if (kept.length > 0) {
scrubbed[key] = kept.join(":");
} else {
delete scrubbed[key];
}
}
}
return scrubbed;
}
function createTerminalSpawnEnv(
baseEnv: NodeJS.ProcessEnv,
runtimeEnv?: Record<string, string> | null,
@@ -1080,7 +1127,7 @@ function createTerminalSpawnEnv(
spawnEnv[key] = value;
}
}
return spawnEnv;
return stripAppImageRuntimeEnv(spawnEnv);
}
function normalizedRuntimeEnv(
@@ -51,8 +51,8 @@ function makeFakeClaudeBinary(dir: string) {
" exit 4",
" }",
"fi",
'if [ -n "$T3_FAKE_CLAUDE_HOME_MUST_BE" ] && [ "$HOME" != "$T3_FAKE_CLAUDE_HOME_MUST_BE" ]; then',
' printf "%s\\n" "HOME was $HOME" >&2',
'if [ -n "$T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE" ] && [ "$CLAUDE_CONFIG_DIR" != "$T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE" ]; then',
' printf "%s\\n" "CLAUDE_CONFIG_DIR was $CLAUDE_CONFIG_DIR" >&2',
" exit 5",
"fi",
'if [ -n "$T3_FAKE_CLAUDE_STDERR" ]; then',
@@ -76,7 +76,7 @@ function withFakeClaudeEnv<A, E, R>(
argsMustContain?: string;
argsMustNotContain?: string;
stdinMustContain?: string;
homeMustBe?: string;
configDirMustBe?: string;
claudeConfig?: Partial<ClaudeSettings>;
},
effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect<A, E, R>,
@@ -92,7 +92,7 @@ function withFakeClaudeEnv<A, E, R>(
const previousArgsMustContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
const previousArgsMustNotContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
const previousStdinMustContain = process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
const previousHomeMustBe = process.env.T3_FAKE_CLAUDE_HOME_MUST_BE;
const previousConfigDirMustBe = process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE;
yield* Effect.acquireRelease(
Effect.sync(() => {
@@ -129,10 +129,10 @@ function withFakeClaudeEnv<A, E, R>(
delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
}
if (input.homeMustBe !== undefined) {
process.env.T3_FAKE_CLAUDE_HOME_MUST_BE = input.homeMustBe;
if (input.configDirMustBe !== undefined) {
process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE = input.configDirMustBe;
} else {
delete process.env.T3_FAKE_CLAUDE_HOME_MUST_BE;
delete process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE;
}
}),
() =>
@@ -175,10 +175,10 @@ function withFakeClaudeEnv<A, E, R>(
process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = previousStdinMustContain;
}
if (previousHomeMustBe === undefined) {
delete process.env.T3_FAKE_CLAUDE_HOME_MUST_BE;
if (previousConfigDirMustBe === undefined) {
delete process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE;
} else {
process.env.T3_FAKE_CLAUDE_HOME_MUST_BE = previousHomeMustBe;
process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE = previousConfigDirMustBe;
}
}),
);
@@ -286,10 +286,10 @@ it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGeneration", (it) => {
),
);
it.effect("runs Claude text generation with the configured Claude HOME", () =>
it.effect("runs Claude text generation with the configured CLAUDE_CONFIG_DIR", () =>
Effect.gen(function* () {
const path = yield* Path.Path;
const claudeHome = path.join(process.cwd(), ".claude-work-test");
const claudeConfigDir = path.join(process.cwd(), ".claude-work-test");
return yield* withFakeClaudeEnv(
{
// @effect-diagnostics-next-line preferSchemaOverJson:off
@@ -298,8 +298,8 @@ it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGeneration", (it) => {
title: "Use Claude home",
},
}),
homeMustBe: claudeHome,
claudeConfig: { homePath: claudeHome },
configDirMustBe: claudeConfigDir,
claudeConfig: { homePath: claudeConfigDir },
},
(textGeneration) =>
Effect.gen(function* () {
@@ -35,6 +35,8 @@ function makeFakeCodexBinary(
requireServiceTier?: string;
requireReasoningEffort?: string;
forbidReasoningEffort?: boolean;
requireArg?: string;
forbidArg?: string;
stdinMustContain?: string;
stdinMustNotContain?: string;
},
@@ -50,6 +52,7 @@ function makeFakeCodexBinary(
codexPath,
[
"#!/bin/sh",
'original_args="$*"',
'output_path=""',
'seen_image="0"',
'seen_service_tier=""',
@@ -87,6 +90,22 @@ function makeFakeCodexBinary(
" shift",
"done",
'stdin_content="$(cat)"',
...(input.requireArg !== undefined
? [
`case " $original_args " in *" ${input.requireArg} "*) ;; *)`,
` printf "%s\\n" "missing arg: ${input.requireArg}" >&2`,
` exit 8`,
"esac",
]
: []),
...(input.forbidArg !== undefined
? [
`case " $original_args " in *" ${input.forbidArg} "*)`,
` printf "%s\\n" "forbidden arg: ${input.forbidArg}" >&2`,
` exit 9`,
"esac",
]
: []),
...(input.requireImage
? [
'if [ "$seen_image" != "1" ]; then',
@@ -166,8 +185,12 @@ function withFakeCodexEnv<A, E, R>(
requireServiceTier?: string;
requireReasoningEffort?: string;
forbidReasoningEffort?: boolean;
requireArg?: string;
forbidArg?: string;
stdinMustContain?: string;
stdinMustNotContain?: string;
launchArgs?: string;
environment?: NodeJS.ProcessEnv;
},
effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect<A, E, R>,
) {
@@ -175,8 +198,8 @@ function withFakeCodexEnv<A, E, R>(
const fs = yield* FileSystem.FileSystem;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" });
const codexPath = yield* makeFakeCodexBinary(tempDir, input);
const config = decodeCodexSettings({ binaryPath: codexPath });
const textGeneration = yield* makeCodexTextGeneration(config);
const config = decodeCodexSettings({ binaryPath: codexPath, launchArgs: input.launchArgs });
const textGeneration = yield* makeCodexTextGeneration(config, input.environment);
return yield* effectFn(textGeneration);
}).pipe(Effect.scoped);
}
@@ -237,6 +260,51 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
),
);
it.effect("passes exec-safe launch args into codex exec", () =>
withFakeCodexEnv(
{
output: JSON.stringify({
subject: "Add important change",
body: "",
}),
launchArgs: "--strict-config --listen off",
requireArg: "--strict-config",
forbidArg: "--listen",
},
(textGeneration) =>
textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/codex-effect",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
}),
),
);
it.effect("uses T3CODE_CODEX_LAUNCH_ARGS for codex exec over settings", () =>
withFakeCodexEnv(
{
output: JSON.stringify({
subject: "Add important change",
body: "",
}),
launchArgs: "--enable settings-feature",
environment: { T3CODE_CODEX_LAUNCH_ARGS: " --strict-config --listen off " },
requireArg: "--strict-config",
forbidArg: "settings-feature",
},
(textGeneration) =>
textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/codex-effect",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
}),
),
);
it.effect("defaults git text generation codex effort to low", () =>
withFakeCodexEnv(
{
@@ -14,6 +14,7 @@ import { resolveSpawnCommand } from "@t3tools/shared/shell";
import { resolveAttachmentPath } from "../attachmentStore.ts";
import * as ServerConfig from "../config.ts";
import { expandHomePath } from "../pathExpansion.ts";
import { codexExecLaunchArgs, resolveCodexLaunchArgs } from "../provider/Layers/codexLaunchArgs.ts";
import { TextGenerationError } from "@t3tools/contracts";
import * as TextGeneration from "./TextGeneration.ts";
import {
@@ -174,6 +175,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
const outputPath = yield* writeTempFile(operation, "codex-output", "");
const runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () {
const launchArgs = resolveCodexLaunchArgs(codexConfig.launchArgs, resolvedEnvironment);
const reasoningEffort =
getModelSelectionStringOptionValue(modelSelection, "reasoningEffort") ??
CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
@@ -182,6 +184,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
codexConfig.binaryPath || "codex",
[
"exec",
...codexExecLaunchArgs(launchArgs),
"--ephemeral",
"--skip-git-repo-check",
"-s",
@@ -1,3 +1,4 @@
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
@@ -37,6 +38,7 @@ export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(functi
grokSettings: GrokSettings,
environment: NodeJS.ProcessEnv = process.env,
) {
const crypto = yield* Crypto.Crypto;
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const runGrokJson = <S extends Schema.Top>({
@@ -65,7 +67,7 @@ export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(functi
childProcessSpawner: commandSpawner,
cwd,
clientInfo: { name: "t3-code-git-text", version: "0.0.0" },
});
}).pipe(Effect.provideService(Crypto.Crypto, crypto));
yield* runtime.handleSessionUpdate((notification) => {
const update = notification.update;
@@ -107,6 +107,14 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntimeShape = {
cause: null,
}),
),
loadInventoryFromCli: () =>
Effect.fail(
new OpenCodeRuntime.OpenCodeRuntimeError({
operation: "loadInventoryFromCli",
detail: "OpenCodeRuntimeTestDouble.loadInventoryFromCli not used in this test",
cause: null,
}),
),
};
const DEFAULT_TEST_MODEL_SELECTION = {
@@ -6,6 +6,9 @@ import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Scope from "effect/Scope";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { GitCommandError } from "@t3tools/contracts";
import { ServerConfig } from "../config.ts";
@@ -20,6 +23,21 @@ const TestLayer = GitVcsDriver.layer.pipe(
Layer.provideMerge(NodeServices.layer),
);
const makeNonRepositoryHandle = () =>
ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(1),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(128)),
isRunning: Effect.succeed(false),
kill: () => Effect.void,
unref: Effect.succeed(Effect.void),
stdin: Sink.drain,
stdout: Stream.empty,
stderr: Stream.encodeText(Stream.make("fatal: not a git repository")),
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
});
const makeTmpDir = (
prefix = "git-vcs-driver-test-",
): Effect.Effect<string, PlatformError.PlatformError, FileSystem.FileSystem | Scope.Scope> =>
@@ -77,7 +95,62 @@ const initRepoWithCommit = (
return { initialBranch };
});
it.effect("uses stable diagnostics for every parsed non-repository command", () => {
const commands: Array<{ readonly args: ReadonlyArray<string>; readonly lcAll?: string }> = [];
const spawner = ChildProcessSpawner.make((command) =>
Effect.sync(() => {
if (!ChildProcess.isStandardCommand(command)) {
return assert.fail("expected a standard Git command");
}
commands.push({
args: command.args,
...(command.options.env?.LC_ALL ? { lcAll: command.options.env.LC_ALL } : {}),
});
return makeNonRepositoryHandle();
}),
);
const nodeServicesLayer = Layer.merge(
NodeServices.layer,
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
);
const layer = GitVcsDriver.layer.pipe(
Layer.provide(ServerConfigLayer),
Layer.provideMerge(nodeServicesLayer),
);
return Effect.gen(function* () {
const driver = yield* GitVcsDriver.GitVcsDriver;
const cwd = "/repo";
yield* driver.statusDetailsLocal(cwd);
yield* driver.statusDetailsRemote(cwd, { refreshUpstream: false });
yield* driver.listRefs({ cwd });
assert.deepStrictEqual(commands, [
{ args: ["status", "--porcelain=2", "--branch"], lcAll: "C" },
{ args: ["rev-parse", "--abbrev-ref", "HEAD"], lcAll: "C" },
{ args: ["branch", "--no-color", "--no-column"], lcAll: "C" },
]);
}).pipe(Effect.provide(layer));
});
it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
describe("process environment", () => {
it.effect("preserves the caller locale for general Git subprocesses", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const locale = yield* git(
cwd,
["-c", 'alias.print-locale=!printf "%s" "$LC_ALL"', "print-locale"],
{ LC_ALL: "zh_CN.UTF-8" },
);
assert.equal(locale, "zh_CN.UTF-8");
}),
);
});
describe("structured errors", () => {
it.effect("preserves structured spawn context and the platform cause", () =>
Effect.gen(function* () {
@@ -620,6 +693,24 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
assert.notInclude(status, "a.txt");
}),
);
it.effect("treats selected file paths literally", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
yield* initRepoWithCommit(cwd);
const driver = yield* GitVcsDriver.GitVcsDriver;
yield* writeTextFile(cwd, "selected[1].txt", "literal\n");
yield* writeTextFile(cwd, "selected1.txt", "pattern match\n");
yield* driver.prepareCommitContext(cwd, ["selected[1].txt"]);
assert.equal(yield* git(cwd, ["diff", "--cached", "--name-only"]), "selected[1].txt");
const status = yield* git(cwd, ["status", "--porcelain"]);
assert.include(status, "?? selected1.txt");
}),
);
});
describe("remote operations", () => {
+18 -3
View File
@@ -830,6 +830,20 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
}),
);
const executeGitWithStableDiagnostics = (
operation: string,
cwd: string,
args: readonly string[],
options: ExecuteGitOptions = {},
): Effect.Effect<GitVcsDriver.ExecuteGitResult, GitCommandError> =>
executeGit(operation, cwd, args, {
...options,
env: {
...options.env,
LC_ALL: "C",
},
});
const runGit = (
operation: string,
cwd: string,
@@ -1184,7 +1198,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
});
const readStatusDetailsRemote = Effect.fn("readStatusDetailsRemote")(function* (cwd: string) {
const branchResult = yield* executeGit(
const branchResult = yield* executeGitWithStableDiagnostics(
"GitVcsDriver.statusDetailsRemote.branch",
cwd,
["rev-parse", "--abbrev-ref", "HEAD"],
@@ -1304,7 +1318,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
});
const readStatusDetailsLocal = Effect.fn("readStatusDetailsLocal")(function* (cwd: string) {
const statusResult = yield* executeGit(
const statusResult = yield* executeGitWithStableDiagnostics(
"GitVcsDriver.statusDetails.status",
cwd,
["status", "--porcelain=2", "--branch"],
@@ -1524,6 +1538,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
}),
);
yield* runGit("GitVcsDriver.prepareCommitContext.addSelected", cwd, [
"--literal-pathspecs",
"add",
"-A",
"--",
@@ -1985,7 +2000,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
const branchRecencyPromise = readBranchRecency(input.cwd).pipe(
Effect.orElseSucceed(() => new Map<string, number>()),
);
const localBranchResult = yield* executeGit(
const localBranchResult = yield* executeGitWithStableDiagnostics(
"GitVcsDriver.listRefs.branchNoColor",
input.cwd,
["branch", "--no-color", "--no-column"],
+208 -85
View File
@@ -20,6 +20,7 @@ import {
AuthAccessReadScope,
AuthAccessStreamError,
type AuthAccessStreamEvent,
type ApplicationStoredEvent,
type AuthEnvironmentScope,
AuthSessionId,
CommandId,
@@ -35,6 +36,7 @@ import {
OrchestrationV2GetThreadProjectionError,
OrchestrationV2ThreadLaunchError,
type OrchestrationProjectShell,
type OrchestrationV2ShellSnapshot,
type ProjectEntriesFailure,
type ProjectFileFailure,
type ProjectFileOperation,
@@ -74,6 +76,7 @@ import * as ThreadLaunchService from "./orchestration-v2/ThreadLaunchService.ts"
import * as ScheduledTasks from "./scheduledTasks/ScheduledTaskService.ts";
import {
archivedShellStreamItemFromSnapshot,
coalesceShellApplicationEvents,
shellStreamItemFromSnapshot,
} from "./orchestration-v2/ShellStream.ts";
import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
@@ -313,6 +316,7 @@ const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
[ORCHESTRATION_V2_WS_METHODS.subscribeArchivedShell, AuthOrchestrationReadScope],
[ORCHESTRATION_V2_WS_METHODS.subscribeShell, AuthOrchestrationReadScope],
[ORCHESTRATION_V2_WS_METHODS.subscribeThread, AuthOrchestrationReadScope],
[WS_METHODS.serverProbe, AuthOrchestrationReadScope],
[WS_METHODS.serverGetConfig, AuthOrchestrationReadScope],
[WS_METHODS.serverRefreshProviders, AuthOrchestrationOperateScope],
[WS_METHODS.serverUpdateProvider, AuthOrchestrationOperateScope],
@@ -593,6 +597,8 @@ const makeWsRpcLayer = (
otlpMetricsEnabled: config.otlpMetricsUrl !== undefined,
},
settings,
shellResumeCompletionMarker: true,
threadResumeCompletionMarker: true,
};
});
@@ -602,11 +608,89 @@ const makeWsRpcLayer = (
.pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach, Effect.asVoid);
const subscribeOrchestrationV2Thread = Effect.fn("ws.orchestrationV2.subscribeThread")(
function* (input: { readonly threadId: ThreadId }) {
function* (input: {
readonly threadId: ThreadId;
readonly afterSequence?: number;
readonly requestCompletionMarker?: boolean;
}) {
yield* Effect.annotateCurrentSpan({
"orchestration_v2.thread_id": input.threadId,
});
const eventStreamFrom = (afterSequence: number) =>
threadManagement
.streamStoredEventsFrom({
threadId: input.threadId,
afterSequence,
})
.pipe(
Stream.map((stored) => ({
kind: "event" as const,
sequence: stored.sequence,
event: stored.event,
})),
Stream.mapError(
(cause) =>
new OrchestrationV2GetThreadProjectionError({
threadId: input.threadId,
message: `Failed while streaming orchestration V2 thread ${input.threadId}`,
cause,
}),
),
);
const replayThrough = (afterSequence: number, throughSequence: number) =>
applicationEvents
.readAgentEvents({
threadId: input.threadId,
afterSequence,
throughSequence,
})
.pipe(
Stream.map((stored) => ({
kind: "event" as const,
sequence: stored.sequence,
event: stored.event,
})),
Stream.mapError(
(cause) =>
new OrchestrationV2GetThreadProjectionError({
threadId: input.threadId,
message: `Failed while replaying orchestration V2 thread ${input.threadId}`,
cause,
}),
),
);
const completionMarker =
input.requestCompletionMarker === true
? Stream.make({ kind: "synchronized" as const })
: Stream.empty;
// When the client already holds the projection (cached, or loaded over
// HTTP) it passes that snapshot's sequence, and we resume by replaying
// persisted events after it instead of re-sending the (potentially
// multi-KB) snapshot frame over the socket. The event sink subscribes
// to live events before reading the persisted tail, so no event
// published during the replay window is lost; overlapping events are
// deduped by sequence on the client.
if (input.afterSequence !== undefined) {
const highWater = yield* applicationEvents.latestAgentSequence(input.threadId).pipe(
Effect.mapError(
(cause) =>
new OrchestrationV2GetThreadProjectionError({
threadId: input.threadId,
message: `Failed to prepare orchestration V2 thread ${input.threadId} replay`,
cause,
}),
),
);
return Stream.concat(
Stream.concat(replayThrough(input.afterSequence, highWater), completionMarker),
eventStreamFrom(highWater),
);
}
const snapshot = yield* threadManagement.getThreadSnapshot(input.threadId).pipe(
Effect.mapError(
(cause) =>
@@ -619,40 +703,25 @@ const makeWsRpcLayer = (
);
const { projection, snapshotSequence } = snapshot;
const liveStream = threadManagement
.streamStoredEventsFrom({
threadId: input.threadId,
afterSequence: snapshotSequence,
})
.pipe(
Stream.map((stored) => ({
kind: "event" as const,
sequence: stored.sequence,
event: stored.event,
})),
Stream.mapError(
(cause) =>
new OrchestrationV2GetThreadProjectionError({
threadId: input.threadId,
message: `Failed while streaming orchestration V2 thread ${input.threadId}`,
cause,
}),
),
);
return Stream.concat(
Stream.make({
kind: "snapshot" as const,
snapshotSequence,
projection,
}),
liveStream,
Stream.concat(
Stream.make({
kind: "snapshot" as const,
snapshotSequence,
projection,
}),
completionMarker,
),
eventStreamFrom(snapshotSequence),
);
},
);
const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subscribeShell")(
function* () {
function* (input: {
readonly afterSequence?: number;
readonly requestCompletionMarker?: boolean;
}) {
const enrichmentChanges = yield* projectEnrichment.subscribeChanges;
const loadSnapshot = Effect.fn("ws.orchestrationV2.loadShellSnapshot")(function* () {
const base = yield* sql.withTransaction(
@@ -671,57 +740,65 @@ const makeWsRpcLayer = (
const projects = yield* enrichProjectShells(base.projects);
return { ...base, projects };
});
const snapshot = yield* loadSnapshot().pipe(
Effect.mapError(
(cause) =>
new OrchestrationV2GetShellSnapshotError({
message: "Failed to load the application shell snapshot",
cause,
}),
),
);
const live = applicationEvents
.streamApplicationEvents({ afterSequence: snapshot.snapshotSequence })
.pipe(
Stream.mapEffect((stored) =>
Effect.gen(function* () {
if ("aggregateKind" in stored) {
if (stored.type === "project.deleted") {
return {
kind: "project.removed" as const,
sequence: stored.sequence,
projectId: stored.payload.projectId,
};
}
const project = yield* projectionSnapshotQuery.getProjectShellById(
stored.payload.projectId,
);
return Option.match(project, {
onNone: () => ({
kind: "project.removed" as const,
sequence: stored.sequence,
projectId: stored.payload.projectId,
}),
onSome: (value) => ({
kind: "project.updated" as const,
sequence: stored.sequence,
project: value,
}),
});
}
const nextSnapshot = yield* threadManagement.getShellSnapshot();
return shellStreamItemFromSnapshot({ stored, snapshot: nextSnapshot });
}),
),
Stream.mapError(
(cause) =>
new OrchestrationV2GetShellSnapshotError({
message: "Failed while streaming the application shell",
cause,
}),
),
const projectItem = Effect.fn("ws.orchestrationV2.projectShellItem")(function* (
stored: Extract<ApplicationStoredEvent, { readonly aggregateKind: "project" }>,
) {
if (stored.type === "project.deleted") {
return {
kind: "project.removed" as const,
sequence: stored.sequence,
projectId: stored.payload.projectId,
};
}
const project = yield* projectionSnapshotQuery.getProjectShellById(
stored.payload.projectId,
);
return Option.match(project, {
onNone: () => ({
kind: "project.removed" as const,
sequence: stored.sequence,
projectId: stored.payload.projectId,
}),
onSome: (value) => ({
kind: "project.updated" as const,
sequence: stored.sequence,
project: value,
}),
});
});
const projectShellItems = Effect.fn("ws.orchestrationV2.projectShellItems")(function* (
events: ReadonlyArray<ApplicationStoredEvent>,
) {
const survivors = coalesceShellApplicationEvents(events);
const needsThreadSnapshot = survivors.some((stored) => !("aggregateKind" in stored));
const threadSnapshot = needsThreadSnapshot
? yield* threadManagement.getShellSnapshot().pipe(Effect.map(Option.some))
: Option.none();
return yield* Effect.forEach(
survivors,
(stored) =>
"aggregateKind" in stored
? projectItem(stored)
: Effect.succeed(
shellStreamItemFromSnapshot({
stored,
snapshot: Option.getOrThrow(threadSnapshot),
}),
),
{ concurrency: 8 },
);
});
const toShellStream = <E, R>(stream: Stream.Stream<ApplicationStoredEvent, E, R>) =>
stream.pipe(
Stream.groupedWithin(512, Duration.millis(50)),
Stream.mapEffect((events) => projectShellItems(Array.from(events))),
Stream.flatMap(Stream.fromIterable),
);
const liveFrom = (afterSequence: number) =>
toShellStream(applicationEvents.streamApplicationEvents({ afterSequence }));
const enrichmentRefreshes = Stream.fromSubscription(enrichmentChanges).pipe(
Stream.filter((change) => change.repositoryIdentityResolved),
@@ -730,10 +807,52 @@ const makeWsRpcLayer = (
Stream.map((snapshot) => ({ kind: "snapshot" as const, snapshot })),
);
return Stream.merge(
Stream.concat(Stream.make({ kind: "snapshot" as const, snapshot }), live),
enrichmentRefreshes,
).pipe(
// When the client already holds a shell snapshot (cached, or loaded
// over HTTP) it passes that snapshot's sequence, and we resume by
// replaying application events after it instead of re-sending the
// whole projects/threads list over the socket. The event store
// subscribes to live events before reading the persisted tail, so no
// event published during the replay window is lost; overlapping events
// are deduped by sequence on the client.
const completionMarker =
input.requestCompletionMarker === true
? Stream.make({ kind: "synchronized" as const })
: Stream.empty;
const snapshotThenLive = (snapshot: OrchestrationV2ShellSnapshot) =>
Stream.concat(
Stream.concat(Stream.make({ kind: "snapshot" as const, snapshot }), completionMarker),
liveFrom(snapshot.snapshotSequence),
);
const base = yield* Effect.gen(function* () {
if (input.afterSequence === undefined) {
return snapshotThenLive(yield* loadSnapshot());
}
const highWater = yield* applicationEvents.latestApplicationSequence;
const replayGap = highWater - input.afterSequence;
if (replayGap < 0 || replayGap > 1_000) {
return snapshotThenLive(yield* loadSnapshot());
}
const replay = toShellStream(
applicationEvents.readApplicationEvents({
afterSequence: input.afterSequence,
throughSequence: highWater,
}),
);
return Stream.concat(Stream.concat(replay, completionMarker), liveFrom(highWater));
}).pipe(
Effect.mapError(
(cause) =>
new OrchestrationV2GetShellSnapshotError({
message: "Failed to prepare the application shell stream",
cause,
}),
),
);
return Stream.merge(base, enrichmentRefreshes).pipe(
Stream.mapError(
(cause) =>
new OrchestrationV2GetShellSnapshotError({
@@ -1013,10 +1132,10 @@ const makeWsRpcLayer = (
subscribeOrchestrationV2ArchivedShell(),
{ "rpc.aggregate": "orchestration" },
),
[ORCHESTRATION_V2_WS_METHODS.subscribeShell]: (_input) =>
[ORCHESTRATION_V2_WS_METHODS.subscribeShell]: (input) =>
observeRpcStreamEffect(
ORCHESTRATION_V2_WS_METHODS.subscribeShell,
subscribeOrchestrationV2Shell(),
subscribeOrchestrationV2Shell(input),
{
"rpc.aggregate": "orchestrationV2",
},
@@ -1057,6 +1176,10 @@ const makeWsRpcLayer = (
"rpc.aggregate": "scheduledTasks",
"scheduled_task.id": input.id,
}),
[WS_METHODS.serverProbe]: (_input) =>
observeRpcEffect(WS_METHODS.serverProbe, Effect.succeed({}), {
"rpc.aggregate": "server",
}),
[WS_METHODS.serverGetConfig]: (_input) =>
observeRpcEffect(WS_METHODS.serverGetConfig, loadServerConfig, {
"rpc.aggregate": "server",