chore(deps): upgrade @effect/tsgo to 0.46.1 (#16360)

Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
authored and GitHub committed 2026-10-06 10:52:08 -07:00
1 parent b38aa18365
commit 78552a8c61
72 files changed
+969 -655

No files matched your search

@@ -1,9 +1,11 @@
import { assert, describe, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as TestClock from "effect/testing/TestClock";
import { beforeEach, vi } from "vite-plus/test";
const { handleMock, netFetchMock, unhandleMock } = vi.hoisted(() => ({
@@ -174,7 +176,11 @@ describe("ElectronProtocol", () => {
targetOrigin: new URL("http://127.0.0.1:5733/"),
clerkFrontendApiHostname: undefined,
});
return yield* Effect.promise(() => handler!(new Request("t3code-dev://app/")));
const fiber = yield* Effect.forkChild(
Effect.promise(() => handler!(new Request("t3code-dev://app/"))),
);
yield* TestClock.adjust("50 millis");
return yield* Fiber.join(fiber);
}),
);
@@ -183,6 +189,50 @@ describe("ElectronProtocol", () => {
}).pipe(Effect.provide(layerProtocol)),
);
it.effect("rejects with the last renderer target failure after 50ms and 150ms retries", () =>
Effect.gen(function* () {
let handler: ((request: Request) => Promise<Response>) | undefined;
handleMock.mockImplementation((_scheme, nextHandler) => {
handler = nextHandler;
});
const lastFailure = new Error("connect ECONNREFUSED 127.0.0.1:5733 (3)");
netFetchMock
.mockRejectedValueOnce(new Error("connect ECONNREFUSED 127.0.0.1:5733 (1)"))
.mockRejectedValueOnce(new Error("connect ECONNREFUSED 127.0.0.1:5733 (2)"))
.mockRejectedValueOnce(lastFailure);
const rejection = yield* Effect.scoped(
Effect.gen(function* () {
const protocol = yield* ElectronProtocol.ElectronProtocol;
yield* protocol.registerDesktopProtocol({
scheme: "t3code-dev",
targetOrigin: new URL("http://127.0.0.1:5733/"),
clerkFrontendApiHostname: undefined,
});
const fiber = yield* Effect.forkChild(
Effect.promise(() =>
handler!(new Request("t3code-dev://app/")).then(
() => null,
(error: unknown) => error,
),
),
);
yield* TestClock.adjust("49 millis");
assert.equal(netFetchMock.mock.calls.length, 1);
yield* TestClock.adjust("1 millis");
assert.equal(netFetchMock.mock.calls.length, 2);
yield* TestClock.adjust("149 millis");
assert.equal(netFetchMock.mock.calls.length, 2);
yield* TestClock.adjust("1 millis");
return yield* Fiber.join(fiber);
}),
);
assert.strictEqual(rejection, lastFailure);
assert.equal(netFetchMock.mock.calls.length, 3);
}).pipe(Effect.provide(layerProtocol)),
);
it.effect("preserves protocol registration failures", () =>
Effect.gen(function* () {
const cause = new Error("protocol registration failed");
+32 -27
View File
@@ -3,10 +3,10 @@ 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 NodeTimersPromises from "node:timers/promises";
import * as Path from "effect/Path";
import * as Mime from "effect/http/Mime";
import * as Ref from "effect/Ref";
import * as Schedule from "effect/Schedule";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
@@ -150,11 +150,29 @@ const registerDesktopSchemePrivileges = Effect.sync(registerDesktopSchemePrivile
export const layerSchemePrivileges = Layer.effectDiscard(registerDesktopSchemePrivileges);
async function proxyRequest(
class ElectronProtocolFetchError extends Schema.TaggedError<ElectronProtocolFetchError>()(
"ElectronProtocolFetchError",
{ cause: Schema.Defect() },
) {}
const netFetch = (url: string, init: RequestInit) =>
Effect.tryPromise({
try: () => Electron.net.fetch(url, init),
catch: (cause) => new ElectronProtocolFetchError({ cause }),
});
// The dev renderer target can briefly refuse connections while Vite restarts:
// retry idempotent requests after 50ms, then 150ms, and keep the last failure.
const fetchWithTransientRetry = (url: string, init: RequestInit) =>
netFetch(url, init).pipe(
Effect.retry({ schedule: Schedule.exponential("50 millis", 3), times: 2 }),
);
const proxyRequest = Effect.fn("desktop.protocol.proxyRequest")(function* (
request: Request,
targetOrigin: URL,
contentSecurityPolicy: string,
): Promise<Response> {
) {
const requestUrl = new URL(request.url);
if (requestUrl.host !== DESKTOP_HOST) {
return new Response(null, { status: 404 });
@@ -190,12 +208,10 @@ async function proxyRequest(
}
const response =
request.method === "GET" || request.method === "HEAD"
? await fetchWithTransientRetry(targetUrl.toString(), init)
: await Electron.net.fetch(targetUrl.toString(), init);
? yield* fetchWithTransientRetry(targetUrl.toString(), init)
: yield* netFetch(targetUrl.toString(), init);
return withContentSecurityPolicy(response, contentSecurityPolicy);
}
const TRANSIENT_FETCH_RETRY_DELAYS_MS = [0, 50, 150] as const;
});
// Serves the packaged web client without a backend: files resolve within the
// asset directory, and any other path falls back to index.html so the SPA
@@ -238,24 +254,6 @@ const serveDesktopAsset = Effect.fn("desktop.protocol.serveAsset")(function* (
});
});
async function fetchWithTransientRetry(url: string, init: RequestInit): Promise<Response> {
let lastError: unknown;
for (const delayMs of TRANSIENT_FETCH_RETRY_DELAYS_MS) {
if (delayMs > 0) {
await NodeTimersPromises.setTimeout(delayMs);
}
try {
return await Electron.net.fetch(url, init);
} catch (error) {
lastError = error;
}
}
throw lastError;
}
/** @public Service construction is part of the canonical Effect module API. */
export const make = Effect.gen(function* () {
const registered = yield* Ref.make(false);
@@ -278,7 +276,14 @@ export const make = Effect.gen(function* () {
contentSecurityPolicy,
);
}
return proxyRequest(request, input.targetOrigin, contentSecurityPolicy);
// Reject with net.fetch's own error, as an unproxied fetch would.
return runPromise(
proxyRequest(request, input.targetOrigin, contentSecurityPolicy).pipe(
Effect.catchTags({
ElectronProtocolFetchError: (error) => Effect.die(error.cause),
}),
),
);
});
},
catch: (cause) => new ElectronProtocolRegistrationError({ scheme: input.scheme, cause }),
@@ -18,6 +18,7 @@ import {
} from "@t3tools/ssh/errors";
import * as SshTunnel from "@t3tools/ssh/tunnel";
import * as Context from "effect/Context";
import type * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
@@ -29,6 +30,7 @@ import * as DesktopSshPasswordPrompts from "./DesktopSshPasswordPrompts.ts";
export type DesktopSshEnvironmentRuntimeServices =
| ChildProcessSpawner.ChildProcessSpawner
| Crypto.Crypto
| FileSystem.FileSystem
| Path.Path
| HttpClient.HttpClient
+1
View File
@@ -34,6 +34,7 @@
"@effect/platform-node-shared": "catalog:",
"@ff-labs/fff-node": "0.9.4",
"@napi-rs/keyring": "^1.3.0",
"@noble/hashes": "catalog:",
"@opencode-ai/sdk": "^1.3.15",
"@opencode/client": "2.0.23",
"@opencode/protocol": "2.0.23",
+1
View File
@@ -1,3 +1,4 @@
// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no timingSafeEqual.
import * as NodeCrypto from "node:crypto";
import { AuthSessionId } from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
+1
View File
@@ -4,6 +4,7 @@ import type {
AuthClientPresentationMetadata,
} from "@t3tools/contracts";
import type * as HttpServerRequest from "effect/http/HttpServerRequest";
// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no createHmac or timingSafeEqual.
import * as NodeCrypto from "node:crypto";
import * as Base64Url from "effect/encoding/Base64Url";
import * as Result from "effect/Result";
@@ -1,3 +1,4 @@
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import { assert, it, vi } from "@effect/vitest";
import { CheckpointRef, CheckpointScopeId, RunId, ThreadId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
@@ -59,6 +60,7 @@ function layerFor(input: {
}),
),
),
Layer.provideMerge(NodeCrypto.layer),
);
}
@@ -80,7 +82,7 @@ it.effect("computes V2 run diffs from projected checkpoint scopes", () => {
});
assert.deepEqual(diffCheckpoints.mock.calls[0]?.[0], {
cwd: "/repo",
fromCheckpointRef: checkpointRefForScopeOrdinal({
fromCheckpointRef: yield* checkpointRefForScopeOrdinal({
scopeId: firstScopeId,
ordinalWithinScope: 0,
}),
@@ -15,6 +15,7 @@ import {
type ThreadId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
@@ -77,6 +78,7 @@ function buildTurnDiffResult(
export const make = Effect.gen(function* () {
const threads = yield* ThreadManagement.ThreadManagementService;
const checkpointStore = yield* CheckpointStore.CheckpointStore;
const crypto = yield* Crypto.Crypto;
const getTurnDiff: CheckpointDiffQuery["Service"]["getTurnDiff"] = Effect.fn("getTurnDiff")(
function* (input) {
@@ -155,21 +157,20 @@ export const make = Effect.gen(function* () {
});
}
// The root scope is shared by every run in this thread. Its runId
// tracks the latest owner, while ordinal zero stays the baseline.
const firstScope =
input.fromTurnCount === 0
? projection.checkpointScopes.find((scope) => scope.kind === "root_run")
: undefined;
const fromCheckpointRef =
input.fromTurnCount === 0
? (() => {
// The root scope is shared by every run in this thread. Its
// runId tracks the latest owner, while ordinal zero stays the baseline.
const firstScope = projection.checkpointScopes.find(
(scope) => scope.kind === "root_run",
);
return firstScope === undefined
? undefined
: checkpointRefForScopeOrdinal({
scopeId: firstScope.id,
ordinalWithinScope: 0,
});
})()
? firstScope === undefined
? undefined
: yield* checkpointRefForScopeOrdinal({
scopeId: firstScope.id,
ordinalWithinScope: 0,
}).pipe(Effect.provideService(Crypto.Crypto, crypto))
: readyCheckpoints.find((checkpoint) => checkpoint.appRunOrdinal === input.fromTurnCount)
?.ref;
if (fromCheckpointRef === undefined) {
+1
View File
@@ -4,6 +4,7 @@
* and mint requests, and keeping the managed tunnel registered, recovered and
* released. HTTP handlers, server startup and shutdown all go through it.
*/
// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no createPublicKey.
import * as NodeCrypto from "node:crypto";
import {
AuthStandardClientScopes,
+1
View File
@@ -1,3 +1,4 @@
// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no generateKeyPairSync.
import * as NodeCrypto from "node:crypto";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
@@ -41,7 +41,9 @@ console.log(readFileSync(args[args.indexOf('--config') + 1], 'utf8'));
if (process.env.AGENT_DEVICE_DAEMON_BASE_URL) process.exit(2);`,
);
const shim = yield* ensureAgentDeviceShim({ entryPath, stateDir: dir });
const files = ["mini", "android"].map((host) => agentDeviceConfigPath(dir, host, path));
const files = yield* Effect.forEach(["mini", "android"], (host) =>
agentDeviceConfigPath(dir, host, path),
);
for (const [index, file] of files.entries())
yield* writeAgentDeviceConfig(file, {
baseUrl: `http://127.0.0.1:${1000 + index}`,
@@ -73,8 +75,8 @@ if (process.env.AGENT_DEVICE_DAEMON_BASE_URL) process.exit(2);`,
});
expect((yield* Effect.promise(() => invoke(files[0]!))).daemonAuthToken).toBe("new");
expect(yield* fs.readFileString(files[1]!)).toBe(second);
expect(agentDeviceSession("thread", "mini", "same-id")).not.toBe(
agentDeviceSession("thread", "android", "same-id"),
expect(yield* agentDeviceSession("thread", "mini", "same-id")).not.toBe(
yield* agentDeviceSession("thread", "android", "same-id"),
);
for (const args of [
["snapshot"],
+12 -6
View File
@@ -1,6 +1,7 @@
import * as NodeCrypto from "node:crypto";
import * as Schema from "effect/Schema";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Hex from "effect/encoding/Hex";
import * as Schema from "effect/Schema";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
@@ -12,15 +13,20 @@ const encodeEndpoint = Schema.encodeEffect(
),
);
const key = (value: string) =>
NodeCrypto.createHash("sha256").update(value).digest("hex").slice(0, 24);
const key = Effect.fn("AgentDeviceTarget.key")(function* (value: string) {
const crypto = yield* Crypto.Crypto;
const digest = yield* crypto
.digest("SHA-256", new TextEncoder().encode(value))
.pipe(Effect.orDie);
return Hex.encode(digest).slice(0, 24);
});
/** A stable file per host lets forwarded endpoints change without retargeting other commands. */
export const agentDeviceConfigPath = (stateDir: string, hostId: string, path: Path.Path) =>
path.join(stateDir, "device", "hosts", `${key(hostId)}.json`);
key(hostId).pipe(Effect.map((hash) => path.join(stateDir, "device", "hosts", `${hash}.json`)));
export const agentDeviceSession = (threadId: string, hostId: string, deviceId: string) =>
`t3-${key(JSON.stringify([threadId, hostId, deviceId]))}`;
key(JSON.stringify([threadId, hostId, deviceId])).pipe(Effect.map((hash) => `t3-${hash}`));
export const writeAgentDeviceConfig = Effect.fn("AgentDeviceTarget.writeConfig")(function* (
file: string,
@@ -2,6 +2,7 @@ import { expect, it } from "@effect/vitest";
import { ThreadId } from "@t3tools/contracts";
import * as Deferred from "effect/Deferred";
import * as Fiber from "effect/Fiber";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as Effect from "effect/Effect";
import { HttpClient, HttpClientResponse } from "effect/http";
import * as ServerSettings from "../serverSettings.ts";
@@ -77,7 +78,7 @@ it.effect("keeps hosts independent when serials collide and another host fails",
order.push("write finished");
return "/host-config.json";
}),
).pipe(Effect.provideService(HttpClient.HttpClient, http));
).pipe(Effect.provide(NodeCrypto.layer), Effect.provideService(HttpClient.HttpClient, http));
expect(yield* service.agentReadinessIfSupported("b")).not.toBeNull();
const listed = yield* service.list;
expect(listed.devices.map((device) => device.hostId).sort()).toEqual(["a", "b"]);
@@ -7,6 +7,7 @@ import {
ThreadId,
type DeviceServiceState,
} from "@t3tools/contracts";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Deferred from "effect/Deferred";
@@ -135,6 +136,7 @@ const fixture = Effect.fn("fixture")(function* (
undefined,
installTool,
).pipe(
Effect.provide(NodeCrypto.layer),
Effect.provideService(DeviceHost.DeviceHost, host),
Effect.provideService(
ServerSettings.ServerSettingsService,
@@ -482,6 +484,7 @@ it.effect.each(["shutdown", "close"] as const)(
}),
);
const service = yield* DeviceService.makeWithHosts(new Map([[host.id, host]])).pipe(
Effect.provide(NodeCrypto.layer),
Effect.provideService(HttpClient.HttpClient, http),
);
const input = { threadId, deviceId, platform: "ios" as const };
@@ -574,6 +577,7 @@ it.effect.each([
}),
);
const service = yield* DeviceService.makeWithHosts(new Map([[host.id, host]])).pipe(
Effect.provide(NodeCrypto.layer),
Effect.provideService(HttpClient.HttpClient, http),
);
yield* service.list;
+20 -14
View File
@@ -46,6 +46,7 @@ import {
writeAgentDeviceConfig,
} from "./AgentDeviceTarget.ts";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
@@ -186,6 +187,7 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*
installTool?: (tool: "hub" | "agent") => Effect.Effect<unknown, DeviceError>,
) {
const settings = yield* ServerSettings.ServerSettingsService;
const crypto = yield* Crypto.Crypto;
const lifecycleLock = yield* Semaphore.make(1);
const readDeviceSettings = settings.getSettings.pipe(
Effect.map((value) => ({
@@ -943,12 +945,12 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*
return yield* configureAgent(input.hostId, ready);
}),
);
return [
"--config",
configPath,
"--session",
agentDeviceSession(input.threadId, input.hostId, input.deviceId),
];
const session = yield* agentDeviceSession(
input.threadId,
input.hostId,
input.deviceId,
).pipe(Effect.provideService(Crypto.Crypto, crypto));
return ["--config", configPath, "--session", session];
}),
state: SynchronizedRef.get(stateRef).pipe(Effect.map(({ state }) => state)),
subscribe: PubSub.subscribe(statePubSub),
@@ -998,9 +1000,17 @@ export const make = Effect.gen(function* () {
const hosts = new Map<DeviceHostId, DeviceHost.DeviceHost["Service"]>([
[localHost.id, localHost],
]);
const configureAgent = (hostId: DeviceHostId, ready: DeviceHost.DeviceHostAgentReady) => {
const file = agentDeviceConfigPath(config.stateDir, hostId, path);
return writeAgentDeviceConfig(file, ready.agentDevice).pipe(
const crypto = yield* Crypto.Crypto;
const configPath = (hostId: DeviceHostId) =>
agentDeviceConfigPath(config.stateDir, hostId, path).pipe(
Effect.provideService(Crypto.Crypto, crypto),
);
const configureAgent = (hostId: DeviceHostId, ready: DeviceHost.DeviceHostAgentReady) =>
Effect.gen(function* () {
const file = yield* configPath(hostId);
yield* writeAgentDeviceConfig(file, ready.agentDevice);
return file;
}).pipe(
Effect.provideService(FileSystem.FileSystem, fs),
Effect.provideService(Path.Path, path),
Effect.mapError(
@@ -1011,9 +1021,7 @@ export const make = Effect.gen(function* () {
cause,
}),
),
Effect.as(file),
);
};
const probeContext =
yield* Effect.context<Effect.Services<ReturnType<typeof SshDeviceHost.probe>>>();
const localTargetContext =
@@ -1089,9 +1097,7 @@ export const make = Effect.gen(function* () {
({ id, scope }) =>
Effect.gen(function* () {
yield* Scope.close(scope, Exit.void);
yield* fs
.remove(agentDeviceConfigPath(config.stateDir, id, path), { force: true })
.pipe(Effect.ignore);
yield* fs.remove(yield* configPath(id), { force: true }).pipe(Effect.ignore);
}),
{ concurrency: 4, discard: true },
);
@@ -32,6 +32,7 @@ import { assert, describe, it } from "@effect/vitest";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
@@ -957,6 +958,7 @@ describe("ClaudeAdapterV2 Auto-accept edits", () => {
attachmentsDir,
fileSystem,
path: yield* Path.Path,
crypto: yield* Crypto.Crypto,
idAllocator,
queryRunner: {
allocateSessionId: Effect.succeed("native-thread-claude-accept-edits"),
@@ -1199,6 +1201,7 @@ describe("ClaudeAdapterV2 resume compaction", () => {
attachmentsDir,
fileSystem,
path: yield* Path.Path,
crypto: yield* Crypto.Crypto,
idAllocator,
queryRunner: {
allocateSessionId: Effect.succeed("native-thread-claude-resume"),
@@ -1418,6 +1421,7 @@ describe("ClaudeAdapterV2 attachments", () => {
attachmentsDir,
fileSystem,
path: yield* Path.Path,
crypto: yield* Crypto.Crypto,
idAllocator,
queryRunner: {
allocateSessionId: Effect.succeed("native-thread-claude-attachments"),
@@ -1558,6 +1562,7 @@ describe("ClaudeAdapterV2 attachments", () => {
attachmentsDir,
fileSystem,
path: yield* Path.Path,
crypto: yield* Crypto.Crypto,
idAllocator,
queryRunner: {
allocateSessionId: Effect.succeed("native-thread-claude-unsupported-attachment"),
@@ -1647,6 +1652,7 @@ describe("ClaudeAdapterV2 native fork", () => {
attachmentsDir,
fileSystem,
path: yield* Path.Path,
crypto: yield* Crypto.Crypto,
idAllocator,
queryRunner: {
allocateSessionId: Effect.succeed("source-native-session"),
@@ -1819,6 +1825,7 @@ describe("ClaudeAdapterV2 native session identity", () => {
attachmentsDir,
fileSystem,
path: yield* Path.Path,
crypto: yield* Crypto.Crypto,
idAllocator,
queryRunner: {
allocateSessionId: Effect.succeed("native-session-identity"),
@@ -2108,6 +2115,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
attachmentsDir,
fileSystem,
path: yield* Path.Path,
crypto: yield* Crypto.Crypto,
idAllocator,
continuationRequests: {
offer: (request) =>
@@ -3892,6 +3900,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
attachmentsDir,
fileSystem,
path: yield* Path.Path,
crypto: yield* Crypto.Crypto,
idAllocator,
continuationRequests: {
offer: (request) =>
@@ -4137,6 +4146,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
attachmentsDir,
fileSystem,
path: yield* Path.Path,
crypto: yield* Crypto.Crypto,
idAllocator,
continuationRequests: {
offer: () => Effect.void,
@@ -4389,11 +4399,12 @@ describe("ClaudeAdapterV2 background wake turns", () => {
const continuationAttempt = RunAttemptId.make("attempt-claude-wake-callback-3");
const planToolUseId = "toolu_01WakePlanExitPlanMode";
const planMarkdown = "# Wake plan\n\n1. Report the background result.";
const stamp = (frame: SDKMessage, attemptId: RunAttemptId) =>
claudeSdkFrame({
const stamp = Effect.fnUntraced(function* (frame: SDKMessage, attemptId: RunAttemptId) {
return claudeSdkFrame({
...frame,
user_message_uuid: ClaudeAdapterV2.claudePromptUuid(attemptId),
user_message_uuid: yield* ClaudeAdapterV2.claudePromptUuid(attemptId),
});
});
const runOf = (attemptId: RunAttemptId) => RunId.make(`run-${attemptId}`);
const planToolUse = claudeSdkFrame({
type: "assistant",
@@ -4446,10 +4457,10 @@ describe("ClaudeAdapterV2 background wake turns", () => {
runtimePolicy,
}),
);
yield* Queue.offer(harness.sdkMessages, stamp(wakeTaskStarted, firstAttempt));
yield* Queue.offer(harness.sdkMessages, yield* stamp(wakeTaskStarted, firstAttempt));
yield* Queue.offer(
harness.sdkMessages,
stamp(
yield* stamp(
makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000740", result: "STARTED" }),
firstAttempt,
),
@@ -4508,7 +4519,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
// The prompt's own turn follows and echoes its uuid.
yield* Queue.offer(
harness.sdkMessages,
stamp(
yield* stamp(
makeAssistantTextFrame({
uuid: "00000000-0000-4000-8000-000000000743",
text: "USER_REPLY",
@@ -4518,7 +4529,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
);
yield* Queue.offer(
harness.sdkMessages,
stamp(
yield* stamp(
makeResultFrame({
uuid: "00000000-0000-4000-8000-000000000744",
result: "USER_REPLY",
@@ -4688,11 +4699,12 @@ describe("ClaudeAdapterV2 background wake turns", () => {
const firstAttempt = RunAttemptId.make("attempt-claude-wake-approval-1");
const userAttempt = RunAttemptId.make("attempt-claude-wake-approval-2");
const bashToolUseId = "toolu_01WakeApprovalBash";
const stamp = (frame: SDKMessage, attemptId: RunAttemptId) =>
claudeSdkFrame({
const stamp = Effect.fnUntraced(function* (frame: SDKMessage, attemptId: RunAttemptId) {
return claudeSdkFrame({
...frame,
user_message_uuid: ClaudeAdapterV2.claudePromptUuid(attemptId),
user_message_uuid: yield* ClaudeAdapterV2.claudePromptUuid(attemptId),
});
});
yield* harness.runtime.startTurn(
makeClaudeTestTurnInput({
@@ -4707,14 +4719,14 @@ describe("ClaudeAdapterV2 background wake turns", () => {
);
yield* Queue.offer(
harness.sdkMessages,
stamp(
yield* stamp(
makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000000780", text: "One." }),
firstAttempt,
),
);
yield* Queue.offer(
harness.sdkMessages,
stamp(
yield* stamp(
makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000781", result: "One." }),
firstAttempt,
),
@@ -4811,11 +4823,12 @@ describe("ClaudeAdapterV2 background wake turns", () => {
const now = yield* DateTime.now;
const firstAttempt = RunAttemptId.make("attempt-claude-echo-debris-1");
const secondAttempt = RunAttemptId.make("attempt-claude-echo-debris-2");
const stamp = (frame: SDKMessage, attemptId: RunAttemptId) =>
claudeSdkFrame({
const stamp = Effect.fnUntraced(function* (frame: SDKMessage, attemptId: RunAttemptId) {
return claudeSdkFrame({
...frame,
user_message_uuid: ClaudeAdapterV2.claudePromptUuid(attemptId),
user_message_uuid: yield* ClaudeAdapterV2.claudePromptUuid(attemptId),
});
});
yield* harness.runtime.startTurn(
makeClaudeTestTurnInput({
@@ -4830,14 +4843,14 @@ describe("ClaudeAdapterV2 background wake turns", () => {
// The first turn echoes on its first frame: this process echoes early.
yield* Queue.offer(
harness.sdkMessages,
stamp(
yield* stamp(
makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000000760", text: "One." }),
firstAttempt,
),
);
yield* Queue.offer(
harness.sdkMessages,
stamp(
yield* stamp(
makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000761", result: "One." }),
firstAttempt,
),
@@ -4864,14 +4877,14 @@ describe("ClaudeAdapterV2 background wake turns", () => {
yield* Queue.offer(harness.sdkMessages, staleTaskNotificationResult);
yield* Queue.offer(
harness.sdkMessages,
stamp(
yield* stamp(
makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000000762", text: "Two." }),
secondAttempt,
),
);
yield* Queue.offer(
harness.sdkMessages,
stamp(
yield* stamp(
makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000763", result: "Two." }),
secondAttempt,
),
@@ -4909,11 +4922,12 @@ describe("ClaudeAdapterV2 background wake turns", () => {
const now = yield* DateTime.now;
const firstAttempt = RunAttemptId.make("attempt-claude-echo-1");
const secondAttempt = RunAttemptId.make("attempt-claude-echo-2");
const stamp = (frame: SDKMessage, attemptId: RunAttemptId) =>
claudeSdkFrame({
const stamp = Effect.fnUntraced(function* (frame: SDKMessage, attemptId: RunAttemptId) {
return claudeSdkFrame({
...frame,
user_message_uuid: ClaudeAdapterV2.claudePromptUuid(attemptId),
user_message_uuid: yield* ClaudeAdapterV2.claudePromptUuid(attemptId),
});
});
const assistantTexts = () =>
harness.events.flatMap((event) =>
event.type === "message.updated" && event.message.role === "assistant"
@@ -4935,18 +4949,18 @@ describe("ClaudeAdapterV2 background wake turns", () => {
);
assert.equal(
harness.offeredMessages[0]?.uuid,
ClaudeAdapterV2.claudePromptUuid(firstAttempt),
yield* ClaudeAdapterV2.claudePromptUuid(firstAttempt),
);
yield* Queue.offer(
harness.sdkMessages,
stamp(
yield* stamp(
makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000000701", text: "One." }),
firstAttempt,
),
);
yield* Queue.offer(
harness.sdkMessages,
stamp(
yield* stamp(
makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000702", result: "One." }),
firstAttempt,
),
@@ -5995,11 +6009,12 @@ describe("ClaudeAdapterV2 background wake turns", () => {
const userAttempt = RunAttemptId.make("attempt-claude-wake-subagent-2");
const continuationAttempt = RunAttemptId.make("attempt-claude-wake-subagent-3");
const runOf = (attemptId: RunAttemptId) => RunId.make(`run-${attemptId}`);
const stamp = (frame: SDKMessage, attemptId: RunAttemptId) =>
claudeSdkFrame({
const stamp = Effect.fnUntraced(function* (frame: SDKMessage, attemptId: RunAttemptId) {
return claudeSdkFrame({
...frame,
user_message_uuid: ClaudeAdapterV2.claudePromptUuid(attemptId),
user_message_uuid: yield* ClaudeAdapterV2.claudePromptUuid(attemptId),
});
});
yield* harness.runtime.startTurn(
makeClaudeTestTurnInput({
@@ -6011,10 +6026,10 @@ describe("ClaudeAdapterV2 background wake turns", () => {
attachments: [],
}),
);
yield* Queue.offer(harness.sdkMessages, stamp(wakeTaskStarted, firstAttempt));
yield* Queue.offer(harness.sdkMessages, yield* stamp(wakeTaskStarted, firstAttempt));
yield* Queue.offer(
harness.sdkMessages,
stamp(
yield* stamp(
makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000770", result: "STARTED" }),
firstAttempt,
),
@@ -6083,14 +6098,14 @@ describe("ClaudeAdapterV2 background wake turns", () => {
session_id: WAKE_NATIVE_SESSION,
}),
wakeResult,
stamp(
yield* stamp(
makeAssistantTextFrame({
uuid: "00000000-0000-4000-8000-000000000776",
text: "USER_REPLY",
}),
userAttempt,
),
stamp(
yield* stamp(
makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000777", result: "USER_REPLY" }),
userAttempt,
),
@@ -7018,6 +7033,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
attachmentsDir,
fileSystem,
path: yield* Path.Path,
crypto: yield* Crypto.Crypto,
idAllocator,
continuationRequests: {
offer: (request) =>
@@ -7201,6 +7217,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
attachmentsDir,
fileSystem,
path: yield* Path.Path,
crypto: yield* Crypto.Crypto,
idAllocator,
continuationRequests: {
offer: (request) =>
@@ -7436,6 +7453,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
attachmentsDir,
fileSystem,
path: yield* Path.Path,
crypto: yield* Crypto.Crypto,
idAllocator,
continuationRequests: {
offer: (request) =>
@@ -7628,6 +7646,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
attachmentsDir,
fileSystem,
path: yield* Path.Path,
crypto: yield* Crypto.Crypto,
idAllocator,
continuationRequests: { offer: () => Effect.void },
queryRunner: {
@@ -7794,6 +7813,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
attachmentsDir,
fileSystem,
path: yield* Path.Path,
crypto: yield* Crypto.Crypto,
idAllocator,
continuationRequests: {
offer: () => Effect.void,
@@ -7923,6 +7943,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
attachmentsDir,
fileSystem,
path: yield* Path.Path,
crypto: yield* Crypto.Crypto,
idAllocator,
continuationRequests: {
offer: (request) =>
@@ -8117,6 +8138,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
attachmentsDir,
fileSystem,
path: yield* Path.Path,
crypto: yield* Crypto.Crypto,
idAllocator,
continuationRequests: {
offer: () => Effect.void,
@@ -1580,7 +1580,11 @@ async function recordClaudeStreamingQuery(input: {
// Like the adapter, give each prompt a uuid Claude echoes on its turn.
const message = ClaudeAdapterV2.makeClaudeUserMessage({
text: prompt,
uuid: ClaudeAdapterV2.claudePromptUuid(`${input.sessionId}:prompt:${index + 1}`),
uuid: await Effect.runPromise(
ClaudeAdapterV2.claudePromptUuid(`${input.sessionId}:prompt:${index + 1}`).pipe(
Effect.provide(NodeServices.layer),
),
),
});
input.entries.push({
type: "expect_outbound",
@@ -1,5 +1,3 @@
import * as NodeCrypto from "node:crypto";
import { makeProviderTextDeltaCoalescer } from "./ProviderTextDeltaCoalescer.ts";
import {
dynamicToolTitle,
@@ -73,6 +71,7 @@ import {
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Hex from "effect/encoding/Hex";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
@@ -1420,11 +1419,17 @@ const makeClaudeUserMessageWithAttachments = Effect.fnUntraced(function* (input:
// Stable per run attempt, so a replayed prompt offer matches its recording.
// Claude echoes it back as user_message_uuid on the turn that answers it.
export function claudePromptUuid(attemptId: string): NonNullable<SDKUserMessage["uuid"]> {
const hex = NodeCrypto.createHash("sha256").update(`t3-claude-prompt:${attemptId}`).digest("hex");
export const claudePromptUuid = Effect.fn("claudePromptUuid")(function* (attemptId: string) {
const crypto = yield* Crypto.Crypto;
const digest = yield* crypto
.digest("SHA-256", new TextEncoder().encode(`t3-claude-prompt:${attemptId}`))
.pipe(Effect.orDie);
const hex = Hex.encode(digest);
const variant = ((Number.parseInt(hex[16]!, 16) & 0x3) | 0x8).toString(16);
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-${variant}${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
}
const uuid: NonNullable<SDKUserMessage["uuid"]> =
`${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-${variant}${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
return uuid;
});
type ClaudeAssistantContentBlock = SDKAssistantMessage["message"]["content"][number];
type ClaudeToolUseContentBlock = Extract<
@@ -2998,6 +3003,7 @@ export interface ClaudeAdapterV2Options {
readonly attachmentsDir: string;
readonly fileSystem: FileSystem.FileSystem;
readonly path: Path.Path;
readonly crypto: Crypto.Crypto;
readonly idAllocator: IdAllocator.IdAllocatorV2Shape;
readonly queryRunner: ClaudeAgentSdkQueryRunnerShape;
readonly scopedLimitNames?: Ref.Ref<ClaudeScopedLimitNames>;
@@ -3013,7 +3019,7 @@ export interface ClaudeAdapterV2Options {
export function makeClaudeAdapterV2(
adapterOptions: ClaudeAdapterV2Options,
): ProviderAdapter.ProviderAdapterV2Shape {
const { attachmentsDir, fileSystem, path, idAllocator, queryRunner } = adapterOptions;
const { attachmentsDir, fileSystem, path, crypto, idAllocator, queryRunner } = adapterOptions;
const continuationRequests = adapterOptions.continuationRequests ?? {
offer: () => Effect.void,
};
@@ -7242,6 +7248,11 @@ export function makeClaudeAdapterV2(
const startedAt = yield* DateTime.now;
const nativeThreadId = yield* getNativeThreadId(turnInput.providerThread);
const nativeTurnId = `turn:${turnInput.attemptId}`;
const promptUuid = isClaudeProviderContinuationTurn(turnInput)
? null
: yield* claudePromptUuid(turnInput.attemptId).pipe(
Effect.provideService(Crypto.Crypto, crypto),
);
const providerTurnId = idAllocator.derive.providerTurn({
driver: CLAUDE_PROVIDER,
nativeTurnId,
@@ -7298,9 +7309,7 @@ export function makeClaudeAdapterV2(
subagentsByToolUseId: new Map(),
subagentNodesByTaskId: new Map(),
pendingSubagentLaunchesByToolUseId: new Map(),
promptUuid: isClaudeProviderContinuationTurn(turnInput)
? null
: claudePromptUuid(turnInput.attemptId),
promptUuid,
promptEcho: isClaudeProviderContinuationTurn(turnInput) ? "confirmed" : "pending",
gatedFramesBeforeEcho: 0,
heldRootFrames: [],
@@ -7309,20 +7318,20 @@ export function makeClaudeAdapterV2(
// produced instead of prompting it again: drain the buffered wake
// messages into this turn and let any still-streaming messages
// follow live. The continuation prompt text never reaches the CLI.
const isContinuationTurn = context.promptUuid === null;
const userMessage = isContinuationTurn
? null
: yield* makeClaudeUserMessageWithAttachments({
text: applyClaudePromptEffortPrefix(
turnInput.message.text,
compileClaudeModelSelection(turnInput.modelSelection).promptEffort,
),
attachments: turnInput.message.attachments,
attachmentsDir,
fileSystem,
skillNames: yield* userInvocableSkillNames(turnInput.runtimePolicy.cwd),
uuid: claudePromptUuid(turnInput.attemptId),
});
const userMessage =
promptUuid === null
? null
: yield* makeClaudeUserMessageWithAttachments({
text: applyClaudePromptEffortPrefix(
turnInput.message.text,
compileClaudeModelSelection(turnInput.modelSelection).promptEffort,
),
attachments: turnInput.message.attachments,
attachmentsDir,
fileSystem,
skillNames: yield* userInvocableSkillNames(turnInput.runtimePolicy.cwd),
uuid: promptUuid,
});
const querySession = yield* openQuery(turnInput, nativeThreadId);
yield* Ref.set(activeTurn, context);
yield* emitProviderEvent({
@@ -7906,6 +7915,7 @@ export function makeClaudeAdapterV2(
export type ClaudeAdapterV2DriverEnv =
| ClaudeAgentSdkQueryRunner
| Crypto.Crypto
| FileSystem.FileSystem
| IdAllocator.IdAllocatorV2
| Path.Path
@@ -7926,6 +7936,7 @@ export const createClaudeAdapterV2 = Effect.fn("ClaudeAdapterV2Driver.create")(
const baseEnvironment = mergeProviderInstanceEnvironment(environment, hostEnvironment);
const claudeEnvironment = yield* makeClaudeEnvironment(config, baseEnvironment);
const path = yield* Path.Path;
const crypto = yield* Crypto.Crypto;
const binaryPath = yield* resolveClaudeSdkExecutablePath(
expandHomePath(config.binaryPath),
claudeEnvironment,
@@ -7937,6 +7948,7 @@ export const createClaudeAdapterV2 = Effect.fn("ClaudeAdapterV2Driver.create")(
attachmentsDir: serverConfig.attachmentsDir,
fileSystem,
path,
crypto,
idAllocator,
queryRunner,
continuationRequests,
@@ -7970,6 +7982,7 @@ export const ClaudeAdapterV2Driver: ProviderAdapterDriver<
const makeDefaultClaudeAdapterV2 = Effect.fn("ClaudeAdapterV2.layer")(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const crypto = yield* Crypto.Crypto;
const hostEnvironment = yield* HostProcessEnvironment;
const idAllocator = yield* IdAllocator.IdAllocatorV2;
const queryRunner = yield* ClaudeAgentSdkQueryRunner;
@@ -7983,6 +7996,7 @@ const makeDefaultClaudeAdapterV2 = Effect.fn("ClaudeAdapterV2.layer")(function*
attachmentsDir: serverConfig.attachmentsDir,
fileSystem,
path,
crypto,
idAllocator,
queryRunner,
continuationRequests,
@@ -7993,6 +8007,7 @@ const layer: Layer.Layer<
ProviderAdapter.ProviderAdapterV2,
never,
| ClaudeAgentSdkQueryRunner
| Crypto.Crypto
| FileSystem.FileSystem
| IdAllocator.IdAllocatorV2
| Path.Path
@@ -35,6 +35,7 @@ import * as CodexClient from "effect-codex-app-server/client";
import * as CodexReplay from "effect-codex-app-server/replay";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Predicate from "effect/Predicate";
import * as FileSystem from "effect/FileSystem";
@@ -801,183 +802,195 @@ describe("CodexAdapterV2 process spawning", () => {
});
describe("CodexAdapterV2 dynamic tool projection", () => {
it("uses the CUA call title while leaving other MCP titles as tool arguments", () => {
const call = {
type: "mcpToolCall" as const,
id: "inspect",
server: "cua_repl",
tool: "js",
status: "completed" as const,
arguments: {
code: "await game.getAXStateAndScreenshot();",
title: "Inspect Saga music screen",
},
result: { content: [] },
};
assert.equal(
CodexAdapterV2.projectCodexDynamicToolItem(call).title,
"Inspect Saga music screen",
);
assert.equal(
CodexAdapterV2.projectCodexDynamicToolItem({ ...call, arguments: { title: " " } }).title,
"js",
);
assert.equal(
CodexAdapterV2.projectCodexDynamicToolItem({ ...call, server: "github" }).title,
"js",
);
});
it.each(["inProgress", "completed", "failed"] as const)(
"presents ordinary MCP calls when %s",
(status) => {
const projection = CodexAdapterV2.projectCodexDynamicToolItem({
type: "mcpToolCall",
id: "weather-call",
server: "weather",
tool: "get_weather",
status,
arguments: { city: "Berlin" },
});
assert.equal(projection.title, "get weather");
assert.deepEqual(projection.toolSource, {
key: "mcp:weather",
name: "weather",
kind: "integration",
});
assert.deepEqual(projection.input, { city: "Berlin" });
},
it.effect("uses the CUA call title while leaving other MCP titles as tool arguments", () =>
Effect.gen(function* () {
const call = {
type: "mcpToolCall" as const,
id: "inspect",
server: "cua_repl",
tool: "js",
status: "completed" as const,
arguments: {
code: "await game.getAXStateAndScreenshot();",
title: "Inspect Saga music screen",
},
result: { content: [] },
};
assert.equal(
(yield* CodexAdapterV2.projectCodexDynamicToolItem(call)).title,
"Inspect Saga music screen",
);
assert.equal(
(yield* CodexAdapterV2.projectCodexDynamicToolItem({ ...call, arguments: { title: " " } }))
.title,
"js",
);
assert.equal(
(yield* CodexAdapterV2.projectCodexDynamicToolItem({ ...call, server: "github" })).title,
"js",
);
}).pipe(Effect.provide(NodeServices.layer)),
);
it("uses Codex connector names without reading a display title from arguments", () => {
const projection = CodexAdapterV2.projectCodexDynamicToolItem({
type: "mcpToolCall",
id: "connector-call",
server: "_apps",
tool: "connector_get_weather",
status: "completed",
arguments: { title: "Argument, not display metadata" },
appContext: {
connectorId: "weather-app",
appName: "Weather",
actionName: "Check weather",
},
result: {
content: [],
_meta: { source: { logoUrl: "https://example.com/weather.png" } },
},
});
assert.equal(projection.title, "Check weather");
assert.equal(projection.toolSource?.name, "Weather");
assert.deepEqual(projection.toolIcon, {
_tag: "themed-logo",
logoUrl: "https://example.com/weather.png",
});
assert.deepEqual(projection.toolSource?.icon, projection.toolIcon);
});
it.effect.each(["inProgress", "completed", "failed"] as const)(
"presents ordinary MCP calls when %s",
(status) =>
Effect.gen(function* () {
const projection = yield* CodexAdapterV2.projectCodexDynamicToolItem({
type: "mcpToolCall",
id: "weather-call",
server: "weather",
tool: "get_weather",
status,
arguments: { city: "Berlin" },
});
assert.equal(projection.title, "get weather");
assert.deepEqual(projection.toolSource, {
key: "mcp:weather",
name: "weather",
kind: "integration",
});
assert.deepEqual(projection.input, { city: "Berlin" });
}).pipe(Effect.provide(NodeServices.layer)),
);
it("preserves native browser and app icons alongside MCP tool output", () => {
const browser = CodexAdapterV2.projectCodexDynamicToolItem({
type: "mcpToolCall",
id: "browser",
server: "browser",
tool: "open",
status: "completed",
arguments: {},
result: {
content: [],
_meta: {
"codex/toolSurface": {
kind: "browserUse",
browserFamily: "Chrome",
screenshot: {
pageUrl: "https://example.com/docs",
faviconUrl: "https://example.com/icon.png",
it.effect("uses Codex connector names without reading a display title from arguments", () =>
Effect.gen(function* () {
const projection = yield* CodexAdapterV2.projectCodexDynamicToolItem({
type: "mcpToolCall",
id: "connector-call",
server: "_apps",
tool: "connector_get_weather",
status: "completed",
arguments: { title: "Argument, not display metadata" },
appContext: {
connectorId: "weather-app",
appName: "Weather",
actionName: "Check weather",
},
result: {
content: [],
_meta: { source: { logoUrl: "https://example.com/weather.png" } },
},
});
assert.equal(projection.title, "Check weather");
assert.equal(projection.toolSource?.name, "Weather");
assert.deepEqual(projection.toolIcon, {
_tag: "themed-logo",
logoUrl: "https://example.com/weather.png",
});
assert.deepEqual(projection.toolSource?.icon, projection.toolIcon);
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("preserves native browser and app icons alongside MCP tool output", () =>
Effect.gen(function* () {
const browser = yield* CodexAdapterV2.projectCodexDynamicToolItem({
type: "mcpToolCall",
id: "browser",
server: "browser",
tool: "open",
status: "completed",
arguments: {},
result: {
content: [],
_meta: {
"codex/toolSurface": {
kind: "browserUse",
browserFamily: "Chrome",
screenshot: {
pageUrl: "https://example.com/docs",
faviconUrl: "https://example.com/icon.png",
},
},
},
},
},
});
assert.equal(browser.toolSurface, "browser");
assert.deepEqual(browser.toolIcon, {
_tag: "website",
pageUrl: "https://example.com/docs",
faviconUrl: "https://example.com/icon.png",
});
assert.equal(browser.toolSource?.name, "Chrome");
const app = CodexAdapterV2.projectCodexDynamicToolItem({
type: "mcpToolCall",
id: "app",
server: "computer",
tool: "click",
status: "completed",
arguments: {},
result: {
content: [],
_meta: {
"codex/toolSurface": {
kind: "computerUse",
app: { kind: "appId", appId: "com.apple.finder" },
});
assert.equal(browser.toolSurface, "browser");
assert.deepEqual(browser.toolIcon, {
_tag: "website",
pageUrl: "https://example.com/docs",
faviconUrl: "https://example.com/icon.png",
});
assert.equal(browser.toolSource?.name, "Chrome");
const app = yield* CodexAdapterV2.projectCodexDynamicToolItem({
type: "mcpToolCall",
id: "app",
server: "computer",
tool: "click",
status: "completed",
arguments: {},
result: {
content: [],
_meta: {
"codex/toolSurface": {
kind: "computerUse",
app: { kind: "appId", appId: "com.apple.finder" },
},
},
},
},
});
assert.deepEqual(app.toolIcon, {
_tag: "native-app",
app: { _tag: "app-id", appId: "com.apple.finder" },
});
assert.equal(app.toolSource?.name, "Finder");
});
});
assert.deepEqual(app.toolIcon, {
_tag: "native-app",
app: { _tag: "app-id", appId: "com.apple.finder" },
});
assert.equal(app.toolSource?.name, "Finder");
}).pipe(Effect.provide(NodeServices.layer)),
);
it("preserves MCP arguments and prefers structured output", () => {
const projection = CodexAdapterV2.projectCodexDynamicToolItem({
type: "mcpToolCall",
id: "call-create-threads",
server: "t3-code",
tool: "create_threads",
status: "completed",
arguments: {
threads: [{ title: "Fixture child", prompt: "fixture child prompt" }],
},
result: {
content: [{ type: "text", text: '{"threads":[{"threadId":"thread:mcp:fixture:0"}]}' }],
structuredContent: {
it.effect("preserves MCP arguments and prefers structured output", () =>
Effect.gen(function* () {
const projection = yield* CodexAdapterV2.projectCodexDynamicToolItem({
type: "mcpToolCall",
id: "call-create-threads",
server: "t3-code",
tool: "create_threads",
status: "completed",
arguments: {
threads: [{ title: "Fixture child", prompt: "fixture child prompt" }],
},
result: {
content: [{ type: "text", text: '{"threads":[{"threadId":"thread:mcp:fixture:0"}]}' }],
structuredContent: {
threads: [{ threadId: "thread:mcp:fixture:0" }],
},
},
});
assert.deepEqual(projection, {
toolName: "t3-code.create_threads",
input: {
threads: [{ title: "Fixture child", prompt: "fixture child prompt" }],
},
output: {
threads: [{ threadId: "thread:mcp:fixture:0" }],
},
},
});
status: "completed",
});
}).pipe(Effect.provide(NodeServices.layer)),
);
assert.deepEqual(projection, {
toolName: "t3-code.create_threads",
input: {
threads: [{ title: "Fixture child", prompt: "fixture child prompt" }],
},
output: {
threads: [{ threadId: "thread:mcp:fixture:0" }],
},
status: "completed",
});
});
it.effect("preserves namespaced dynamic tool output", () =>
Effect.gen(function* () {
const projection = yield* CodexAdapterV2.projectCodexDynamicToolItem({
type: "dynamicToolCall",
id: "call-dynamic",
namespace: "workspace",
tool: "inspect",
status: "failed",
arguments: { path: "package.json" },
contentItems: [{ type: "inputText", text: "inspection failed" }],
success: false,
});
it("preserves namespaced dynamic tool output", () => {
const projection = CodexAdapterV2.projectCodexDynamicToolItem({
type: "dynamicToolCall",
id: "call-dynamic",
namespace: "workspace",
tool: "inspect",
status: "failed",
arguments: { path: "package.json" },
contentItems: [{ type: "inputText", text: "inspection failed" }],
success: false,
});
assert.deepEqual(projection, {
toolName: "workspace.inspect",
input: { path: "package.json" },
output: [{ type: "inputText", text: "inspection failed" }],
status: "failed",
});
});
assert.deepEqual(projection, {
toolName: "workspace.inspect",
input: { path: "package.json" },
output: [{ type: "inputText", text: "inspection failed" }],
status: "failed",
});
}).pipe(Effect.provide(NodeServices.layer)),
);
});
describe("CodexAdapterV2 native protocol logging", () => {
@@ -1703,6 +1716,7 @@ describe("CodexAdapterV2 session initialize", () => {
),
),
},
crypto: yield* Crypto.Crypto,
fileSystem: yield* FileSystem.FileSystem,
idAllocator: yield* IdAllocator.IdAllocatorV2,
serverConfig: yield* makeReplayServerConfig(transcript.scenario).pipe(Effect.orDie),
@@ -1899,6 +1913,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
settings: DEFAULT_CODEX_SETTINGS,
environment: {},
clientFactory,
crypto: yield* Crypto.Crypto,
fileSystem,
idAllocator,
serverConfig,
@@ -66,6 +66,7 @@ import * as CodexClient from "effect-codex-app-server/client";
import * as CodexErrors from "effect-codex-app-server/errors";
import * as CodexSchema from "effect-codex-app-server/schema";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
@@ -479,26 +480,29 @@ function codexDynamicToolOutput(
return item.success === false ? { success: false } : undefined;
}
export function projectCodexDynamicToolItem(
item: CodexDynamicToolItem,
): CodexDynamicToolProjection {
const output =
item.type === "mcpToolCall" ? codexMcpToolOutput(item) : codexDynamicToolOutput(item);
const toolName =
item.type === "mcpToolCall"
? `${item.server}.${item.tool}`
: [trimText(item.namespace), item.tool].filter(Boolean).join(".");
const presentation = item.type === "mcpToolCall" ? mcpToolPresentation(item) : {};
const title = dynamicToolTitle(toolName, item.arguments) ?? presentation.title;
const projection: CodexDynamicToolProjection = {
...presentation,
toolName,
...(title ? { title } : {}),
input: item.arguments,
status: codexItemStatus(item.status).turnItem,
};
return output === undefined ? projection : { ...projection, output };
}
export const projectCodexDynamicToolItem = Effect.fn("CodexAdapterV2.projectDynamicToolItem")(
function* (
item: CodexDynamicToolItem,
): Effect.fn.Return<CodexDynamicToolProjection, never, Crypto.Crypto> {
const output =
item.type === "mcpToolCall" ? codexMcpToolOutput(item) : codexDynamicToolOutput(item);
const toolName =
item.type === "mcpToolCall"
? `${item.server}.${item.tool}`
: [trimText(item.namespace), item.tool].filter(Boolean).join(".");
const presentation: McpToolPresentation =
item.type === "mcpToolCall" ? yield* mcpToolPresentation(item) : {};
const title = dynamicToolTitle(toolName, item.arguments) ?? presentation.title;
const projection: CodexDynamicToolProjection = {
...presentation,
toolName,
...(title ? { title } : {}),
input: item.arguments,
status: codexItemStatus(item.status).turnItem,
};
return output === undefined ? projection : { ...projection, output };
},
);
function codexNativeItemRef(nativeItemId: string) {
return {
@@ -1513,6 +1517,7 @@ export const layerAppServerClientFactory: Layer.Layer<
export type CodexAdapterV2DriverEnv =
| CodexAppServerClientFactory
| Crypto.Crypto
| FileSystem.FileSystem
| IdAllocatorV2
| Path.Path
@@ -1525,6 +1530,7 @@ export const createCodexAdapterV2 = (
Effect.gen(function* () {
const clientFactory = yield* CodexAppServerClientFactory;
const continuationRequests = yield* ProviderContinuationRequests;
const crypto = yield* Crypto.Crypto;
const fileSystem = yield* FileSystem.FileSystem;
const hostEnvironment = yield* HostProcessEnvironment;
const idAllocator = yield* IdAllocatorV2;
@@ -1555,6 +1561,7 @@ export const createCodexAdapterV2 = (
settings,
environment: mergeProviderInstanceEnvironment(environment, hostEnvironment),
clientFactory,
crypto,
fileSystem,
idAllocator,
serverConfig,
@@ -1573,12 +1580,13 @@ export const CodexAdapterV2Driver: ProviderAdapterDriver<CodexSettings, CodexAda
const layer: Layer.Layer<
ProviderAdapterV2,
never,
CodexAppServerClientFactory | FileSystem.FileSystem | IdAllocatorV2 | ServerConfig
CodexAppServerClientFactory | Crypto.Crypto | FileSystem.FileSystem | IdAllocatorV2 | ServerConfig
> = Layer.effect(
ProviderAdapterV2,
Effect.gen(function* () {
const clientFactory = yield* CodexAppServerClientFactory;
const continuationRequests = yield* ProviderContinuationRequests;
const crypto = yield* Crypto.Crypto;
const fileSystem = yield* FileSystem.FileSystem;
const hostEnvironment = yield* HostProcessEnvironment;
const idAllocator = yield* IdAllocatorV2;
@@ -1589,6 +1597,7 @@ const layer: Layer.Layer<
settings: DEFAULT_CODEX_SETTINGS,
environment: hostEnvironment,
clientFactory,
crypto,
fileSystem,
idAllocator,
serverConfig,
@@ -1609,6 +1618,7 @@ export interface CodexAdapterV2Options {
* Codex with a current access token.
*/
readonly resolveRuntime?: Effect.Effect<CodexEffectiveRuntime, ProviderSetupError, Scope.Scope>;
readonly crypto: Crypto.Crypto;
readonly fileSystem: FileSystem.FileSystem;
readonly idAllocator: IdAllocatorV2Shape;
readonly serverConfig: ServerConfig["Service"];
@@ -1623,7 +1633,7 @@ export interface CodexAdapterV2Options {
}
export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): ProviderAdapterV2Shape {
const { clientFactory, fileSystem, idAllocator, serverConfig } = adapterOptions;
const { clientFactory, crypto, fileSystem, idAllocator, serverConfig } = adapterOptions;
const continuationRequests = adapterOptions.continuationRequests;
return ProviderAdapterV2.of({
@@ -3480,7 +3490,9 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
nativeItemId: item.id,
});
const { ordinal, startedAt } = yield* resolveItemPosition(context, item.id);
const projection = projectCodexDynamicToolItem(item);
const projection = yield* projectCodexDynamicToolItem(item).pipe(
Effect.provideService(Crypto.Crypto, crypto),
);
const node: OrchestrationV2ExecutionNode = {
id: nodeId,
threadId: context.projectionThreadId,
@@ -3,6 +3,7 @@
* driven through the real adapter and `@opencode/client` against a replayed
* HTTP server. Frames reuse the shapes recorded against 2.0.18.
*/
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import { assert, it } from "@effect/vitest";
import {
CheckpointId,
@@ -2766,21 +2767,25 @@ describe("OpenCode2 adapter", () => {
}).pipe(Effect.scoped),
);
it("names each thread's MCP server within OpenCode's limits, one name per thread", () => {
const project = "thread:project:ce04e4e2-6c29-4ff0-a1d7-b089dd63e258";
const ids = [
`${project}:d3b2d715-c4a1-4b63-bb65-1634c3a3a8c4`,
`${project}:d3b2d715-c4a1-4b63-bb65-1634c3a3a8c5`,
"thread:delegated-task:command%3Amcp%3A48bef2bf-6d0e-4f7a-9c3b-2e5d8a1f7c40%3Adelegate-task%3Around1",
"thread:delegated-task:command%3Amcp%3A48bef2bf-6d0e-4f7a-9c3b-2e5d8a1f7c40%3Adelegate-task%3Around2",
];
const names = ids.map(t3McpServerName);
for (const name of names) assert.match(name, /^t3-code-[A-Za-z0-9_-]{1,56}$/);
assert.equal(new Set(names).size, ids.length);
assert.deepEqual(ids.map(t3McpServerName), names);
// A name that already fits stays readable.
assert.equal(t3McpServerName(threadId), "t3-code-thread_opencode2-adapter");
});
it.effect("names each thread's MCP server within OpenCode's limits, one name per thread", () =>
Effect.gen(function* () {
const project = "thread:project:ce04e4e2-6c29-4ff0-a1d7-b089dd63e258";
const ids = [
`${project}:d3b2d715-c4a1-4b63-bb65-1634c3a3a8c4`,
`${project}:d3b2d715-c4a1-4b63-bb65-1634c3a3a8c5`,
"thread:delegated-task:command%3Amcp%3A48bef2bf-6d0e-4f7a-9c3b-2e5d8a1f7c40%3Adelegate-task%3Around1",
"thread:delegated-task:command%3Amcp%3A48bef2bf-6d0e-4f7a-9c3b-2e5d8a1f7c40%3Adelegate-task%3Around2",
];
const names = yield* Effect.forEach(ids, t3McpServerName);
for (const name of names) assert.match(name, /^t3-code-[A-Za-z0-9_-]{1,56}$/);
assert.equal(new Set(names).size, ids.length);
assert.deepEqual(yield* Effect.forEach(ids, t3McpServerName), names);
// A digested name is the one the synchronous node:crypto version produced.
assert.equal(names[0], "t3-code-63abb5df2b188bdd");
// A name that already fits stays readable.
assert.equal(yield* t3McpServerName(threadId), "t3-code-thread_opencode2-adapter");
}).pipe(Effect.provide(NodeCrypto.layer)),
);
it.effect("reads user and assistant text from the session's message list", () =>
Effect.gen(function* () {
@@ -284,7 +284,13 @@ function layerRegistry(
Effect.map((adapter) => ProviderAdapterRegistry.layerFromAdapters([adapter])),
),
).pipe(
Layer.provide(Layer.mergeAll(layerReplayServerConfig(transcript.scenario), IdAllocator.layer)),
Layer.provide(
Layer.mergeAll(
layerReplayServerConfig(transcript.scenario),
IdAllocator.layer,
NodeServices.layer,
),
),
);
}
@@ -322,7 +328,13 @@ export const openCode2ReplayRuntime = (
},
});
}).pipe(
Effect.provide(Layer.mergeAll(layerReplayServerConfig("opencode2_adapter"), IdAllocator.layer)),
Effect.provide(
Layer.mergeAll(
layerReplayServerConfig("opencode2_adapter"),
IdAllocator.layer,
NodeServices.layer,
),
),
);
export const OpenCode2OrchestratorReplayHarness: OrchestratorV2ProviderReplayHarness<
@@ -21,7 +21,6 @@
*
* @module orchestration-v2/Adapters/OpenCode2AdapterV2
*/
import * as NodeCrypto from "node:crypto";
import {
AbsolutePath,
@@ -59,7 +58,9 @@ import {
import type * as Cause from "effect/Cause";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Hex from "effect/encoding/Hex";
import * as Exit from "effect/Exit";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
@@ -453,12 +454,15 @@ const rule = (action: string, effect: Rule["effect"]): Rule => ({ action, resour
* tool namespace limit), and its router rejects adding one over 100, so a
* thread id that does not fit is replaced by a digest of it.
*/
export const t3McpServerName = (threadId: string) => {
export const t3McpServerName = Effect.fn("t3McpServerName")(function* (threadId: string) {
const name = `t3-code-${threadId.replaceAll(/[^a-zA-Z0-9_-]/g, "_")}`;
if (name.length <= 64) return name;
const digest = NodeCrypto.createHash("sha256").update(threadId).digest("hex");
return `t3-code-${digest.slice(0, 16)}`;
};
const crypto = yield* Crypto.Crypto;
const digest = yield* crypto
.digest("SHA-256", new TextEncoder().encode(threadId))
.pipe(Effect.orDie);
return `t3-code-${Hex.encode(digest).slice(0, 16)}`;
});
/**
* The rules that keep T3's MCP servers to their own thread, after the mode's:
@@ -466,19 +470,19 @@ export const t3McpServerName = (threadId: string) => {
* this thread's own is allowed again, in every mode. A subagent's session
* inherits the thread's.
*/
const mcpRules = (threadId: string | null): ReadonlyArray<Rule> =>
threadId === null
const mcpRules = (mcpServerName: string | null): ReadonlyArray<Rule> =>
mcpServerName === null
? []
: [
{ action: "t3-code-*", resource: "*", effect: "deny" },
{ action: `${t3McpServerName(threadId)}_*`, resource: "*", effect: "allow" },
{ action: `${mcpServerName}_*`, resource: "*", effect: "allow" },
];
const sessionRules = (
policy: RulesPolicy,
paths: ReadonlyArray<Rule>,
grants: ReadonlyArray<Rule>,
threadId: string | null,
mcpServerName: string | null,
): ReadonlyArray<Rule> => [
...(policy.runtimeMode === "full-access"
? [rule("*", "allow")]
@@ -492,7 +496,7 @@ const sessionRules = (
// are never denied: the free tier refuses sessions whose rules deny them.
...(policy.interactionMode === "plan" ? [rule("edit", "deny")] : []),
...paths,
...mcpRules(threadId),
...mcpRules(mcpServerName),
];
const sameRules = (left: ReadonlyArray<Rule> | undefined, right: ReadonlyArray<Rule>) =>
@@ -828,7 +832,10 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
const idAllocator = yield* IdAllocator.IdAllocatorV2;
const serverConfig = yield* ServerConfig.ServerConfig;
const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
const crypto = yield* Crypto.Crypto;
const driver = OPENCODE_PROVIDER;
const mcpServerNameFor = (threadId: string) =>
t3McpServerName(threadId).pipe(Effect.provideService(Crypto.Crypto, crypto));
/**
* Lends the instance's server to a session until its scope closes. A spawned
@@ -2977,7 +2984,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
policy,
paths,
policy.runtimeMode === "full-access" ? [] : thread.grants,
appThreadId,
appThreadId === null ? null : yield* mcpServerNameFor(appThreadId),
);
});
@@ -3234,7 +3241,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
) {
const mcpSession = McpProviderSession.readMcpProviderSession(turnInput.threadId);
const directory = turnInput.runtimePolicy.cwd ?? serverConfig.cwd;
const name = t3McpServerName(turnInput.threadId);
const name = yield* mcpServerNameFor(turnInput.threadId);
// An external server may not reach T3's MCP endpoint, as with 1.x.
const wanted =
mcpSession === undefined || connection.external
@@ -1,3 +1,4 @@
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import { assert, it } from "@effect/vitest";
import {
CheckpointId,
@@ -274,6 +275,7 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => {
Layer.provide(
Layer.mergeAll(
IdAllocator.layer,
NodeCrypto.layer,
Layer.mock(CheckpointStore.CheckpointStore)({
isGitRepository: () => Effect.succeed(true),
captureCheckpoint: () => Effect.void,
@@ -1,3 +1,4 @@
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import { assert, it } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
@@ -24,6 +25,7 @@ const layerProjection = Layer.mergeAll(
ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMemory)),
SqlitePersistence.layerMemory,
IdAllocator.layer,
NodeCrypto.layer,
);
it.effect("resolves the thread baseline after a second root run replaces scope ownership", () =>
Effect.gen(function* () {
@@ -38,6 +40,11 @@ it.effect("resolves the thread baseline after a second root run replaces scope o
const providerThreadId = ProviderThreadId.make("provider-thread:audit-root-scope");
const providerInstanceId = ProviderInstanceId.make("codex");
const scopeId = yield* ids.allocate.checkpointScope({ threadId, name: "root" });
const checkpointRefs = [
yield* checkpointRefForScopeOrdinal({ scopeId, ordinalWithinScope: 0 }),
yield* checkpointRefForScopeOrdinal({ scopeId, ordinalWithinScope: 1 }),
yield* checkpointRefForScopeOrdinal({ scopeId, ordinalWithinScope: 2 }),
];
const baselineId = CheckpointId.make("checkpoint:audit-root-scope:0");
const firstCheckpointId = CheckpointId.make("checkpoint:audit-root-scope:1");
const secondCheckpointId = CheckpointId.make("checkpoint:audit-root-scope:2");
@@ -154,7 +161,7 @@ it.effect("resolves the thread baseline after a second root run replaces scope o
input.ordinal === 0 ? null : input.ordinal === 1 ? baselineId : firstCheckpointId,
ordinalWithinScope: input.ordinal,
appRunOrdinal: input.appRunOrdinal,
ref: checkpointRefForScopeOrdinal({ scopeId, ordinalWithinScope: input.ordinal }),
ref: checkpointRefs[input.ordinal]!,
status: "ready" as const,
files: [],
capturedAt: now,
@@ -214,14 +221,8 @@ it.effect("resolves the thread baseline after a second root run replaces scope o
Layer.mock(CheckpointStore.CheckpointStore)({
diffCheckpoints: (input) => {
assert.equal(input.cwd, "/prepared-repo");
assert.equal(
input.fromCheckpointRef,
checkpointRefForScopeOrdinal({ scopeId, ordinalWithinScope: 0 }),
);
assert.equal(
input.toCheckpointRef,
checkpointRefForScopeOrdinal({ scopeId, ordinalWithinScope: 2 }),
);
assert.equal(input.fromCheckpointRef, checkpointRefs[0]);
assert.equal(input.toCheckpointRef, checkpointRefs[2]);
return Effect.succeed("two-run diff");
},
}),
@@ -1,3 +1,4 @@
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import { assert, it, vi } from "@effect/vitest";
import {
CheckpointScopeId,
@@ -58,6 +59,7 @@ it.effect.each([false, true, "interrupt"] as const)(
}),
),
),
Layer.provideMerge(NodeCrypto.layer),
);
return Effect.gen(function* () {
@@ -88,7 +90,7 @@ it.effect.each([false, true, "interrupt"] as const)(
assert.equal(baseline.ordinalWithinScope, 2);
assert.equal(
baseline.ref,
CheckpointService.checkpointRefForScopeOrdinal({
yield* CheckpointService.checkpointRefForScopeOrdinal({
scopeId: scope.id,
ordinalWithinScope: 2,
}),
@@ -9,11 +9,12 @@ import {
RunId,
ThreadId,
} from "@t3tools/contracts";
import * as NodeCrypto from "node:crypto";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Base64Url from "effect/encoding/Base64Url";
import * as Hex from "effect/encoding/Hex";
import * as KeyedLock from "@t3tools/shared/KeyedLock";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
@@ -157,15 +158,18 @@ export class CheckpointServiceV2 extends Context.Service<
CheckpointServiceV2Shape
>()("t3/orchestration-v2/CheckpointService/CheckpointServiceV2") {}
export function checkpointRefForScopeOrdinal(input: {
readonly scopeId: CheckpointScopeId;
readonly ordinalWithinScope: number;
}): CheckpointRef {
const scopeKey = NodeCrypto.createHash("sha256").update(input.scopeId).digest("hex").slice(0, 32);
return CheckpointRef.make(
`${CHECKPOINT_REFS_PREFIX}/${Base64Url.encode(scopeKey)}/ordinal/${input.ordinalWithinScope}`,
);
}
export const checkpointRefForScopeOrdinal = Effect.fn("checkpointRefForScopeOrdinal")(
function* (input: { readonly scopeId: CheckpointScopeId; readonly ordinalWithinScope: number }) {
const crypto = yield* Crypto.Crypto;
const digest = yield* crypto
.digest("SHA-256", new TextEncoder().encode(input.scopeId))
.pipe(Effect.orDie);
const scopeKey = Hex.encode(digest).slice(0, 32);
return CheckpointRef.make(
`${CHECKPOINT_REFS_PREFIX}/${Base64Url.encode(scopeKey)}/ordinal/${input.ordinalWithinScope}`,
);
},
);
function checkpointIdForScopeOrdinal(
idAllocator: IdAllocator.IdAllocatorV2Shape,
@@ -242,11 +246,14 @@ function makeCheckpoint(input: {
export const layer: Layer.Layer<
CheckpointServiceV2,
never,
CheckpointStore.CheckpointStore | IdAllocator.IdAllocatorV2
CheckpointStore.CheckpointStore | Crypto.Crypto | IdAllocator.IdAllocatorV2
> = Layer.effect(
CheckpointServiceV2,
Effect.gen(function* () {
const checkpointStore = yield* CheckpointStore.CheckpointStore;
const crypto = yield* Crypto.Crypto;
const checkpointRefFor = (input: Parameters<typeof checkpointRefForScopeOrdinal>[0]) =>
checkpointRefForScopeOrdinal(input).pipe(Effect.provideService(Crypto.Crypto, crypto));
const idAllocator = yield* IdAllocator.IdAllocatorV2;
const workspaceLocks = yield* KeyedLock.make<string>();
const withWorkspaceLock = <A, E, R>(cwd: string, effect: Effect.Effect<A, E, R>) =>
@@ -265,7 +272,7 @@ export const layer: Layer.Layer<
return;
}
const checkpointRef = checkpointRefForScopeOrdinal({
const checkpointRef = yield* checkpointRefFor({
scopeId: input.scope.id,
ordinalWithinScope: input.ordinalWithinScope,
});
@@ -298,7 +305,7 @@ export const layer: Layer.Layer<
withWorkspaceLock(
input.scope.cwd,
Effect.gen(function* () {
const checkpointRef = checkpointRefForScopeOrdinal({
const checkpointRef = yield* checkpointRefFor({
scopeId: input.scope.id,
ordinalWithinScope: input.ordinalWithinScope,
});
@@ -362,11 +369,11 @@ export const layer: Layer.Layer<
ordinalWithinScope: input.ordinalWithinScope - 1,
})
: null;
const checkpointRef = checkpointRefForScopeOrdinal({
const checkpointRef = yield* checkpointRefFor({
scopeId: input.scope.id,
ordinalWithinScope: input.ordinalWithinScope,
});
const previousCheckpointRef = checkpointRefForScopeOrdinal({
const previousCheckpointRef = yield* checkpointRefFor({
scopeId: input.scope.id,
ordinalWithinScope: Math.max(0, input.ordinalWithinScope - 1),
});
@@ -15,6 +15,7 @@ import {
type OrchestrationV2DomainEvent,
} 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";
@@ -137,6 +138,7 @@ it.effect.each(["child completion", "scheduled message", "user steering"] as con
attachmentsDir: cwd,
fileSystem: yield* FileSystem.FileSystem,
path: yield* Path.Path,
crypto: yield* Crypto.Crypto,
idAllocator: yield* IdAllocator.IdAllocatorV2,
queryRunner: {
allocateSessionId: Effect.succeed(sessionId),
@@ -7,12 +7,12 @@ import {
RunAttemptId,
ThreadId,
} from "@t3tools/contracts";
import * as Clock from "effect/Clock";
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 Schema from "effect/Schema";
import * as NodeTimersPromises from "node:timers/promises";
import * as ProjectionStore from "./ProjectionStore.ts";
import * as ProviderSessionManager from "./ProviderSessionManager.ts";
@@ -188,17 +188,24 @@ export const layer: Layer.Layer<
});
// Give native terminal ingestion time to finish before the Stop
// follow-up repairs a run whose provider no longer reports on it.
const deadline = performance.now() + 2_000;
while (loaded.providerTurn.status === "running" && performance.now() < deadline) {
const current = yield* projections.getProviderControlContext(input.threadId, input);
if (
current.providerTurn?.status !== "running" &&
current.attempt?.status !== "running"
// The wait is real time: ingestion runs on other fibers and never
// advances a test clock, so a test clock would hold Stop forever.
yield* Effect.gen(function* () {
const deadline = (yield* Clock.currentTimeMillis) + 2_000;
while (
loaded.providerTurn.status === "running" &&
(yield* Clock.currentTimeMillis) < deadline
) {
break;
const current = yield* projections.getProviderControlContext(input.threadId, input);
if (
current.providerTurn?.status !== "running" &&
current.attempt?.status !== "running"
) {
return;
}
yield* Effect.sleep("10 millis");
}
yield* Effect.promise(() => NodeTimersPromises.setTimeout(10));
}
}).pipe(Effect.provideService(Clock.Clock, Clock.Clock.defaultValue()));
}).pipe(
Effect.mapError((cause) =>
isProviderTurnControlError(cause)
@@ -2,9 +2,11 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Deferred from "effect/Deferred";
import * as Crypto from "effect/Crypto";
import type * as Duration from "effect/Duration";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Hex from "effect/encoding/Hex";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
@@ -12,7 +14,6 @@ import * as Path from "effect/Path";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
import { HttpClient, HttpClientResponse } from "effect/http";
import * as NodeCrypto from "node:crypto";
import * as NodeZlib from "node:zlib";
import * as PreviewBrowser from "./PreviewBrowser.ts";
@@ -87,6 +88,9 @@ const makeHarness = Effect.fn("test.makePreviewBrowser")(function* (
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-preview-browser-test-" });
const archive = options.archive ?? browserArchive;
const crypto = yield* Crypto.Crypto;
const sha256 =
options.sha256 ?? Hex.encode(yield* crypto.digest("SHA-256", archive).pipe(Effect.orDie));
const requests: Array<string> = [];
const browser = yield* PreviewBrowser.makePreviewBrowser({
baseDir,
@@ -97,7 +101,7 @@ const makeHarness = Effect.fn("test.makePreviewBrowser")(function* (
platform: "fixture",
url: "https://storage.googleapis.com/chrome-headless-shell-fixture.zip",
bytes: archive.byteLength,
sha256: options.sha256 ?? NodeCrypto.createHash("sha256").update(archive).digest("hex"),
sha256,
},
...(options.wait === undefined ? {} : { wait: options.wait }),
}).pipe(
@@ -6,8 +6,10 @@ import {
HostProcessIsExecutable,
HostProcessPlatform,
} from "@t3tools/shared/hostProcess";
import * as Crypto from "effect/Crypto";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Hex from "effect/encoding/Hex";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
@@ -21,7 +23,6 @@ import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { HttpClient, HttpClientResponse } from "effect/http";
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
import * as NodeCrypto from "node:crypto";
import * as AntigravityInstallation from "./AntigravityInstallation.ts";
import { ANTIGRAVITY_AUTH_BROWSER_MARKER } from "./antigravityAuthSupport.ts";
@@ -70,14 +71,15 @@ const executableName = hostPlatform === "win32" ? "agy_acp_server.exe" : "agy_ac
const harnessName =
hostPlatform === "win32" ? "localharness_external.exe" : "localharness_external";
function releaseAsset(
const releaseAsset = Effect.fn("test.antigravityReleaseAsset")(function* (
archive: Uint8Array = completeArchive,
platform: NodeJS.Platform = hostPlatform,
) {
const crypto = yield* Crypto.Crypto;
return {
version: "fixture-new",
url: "https://dl.google.com/antigravity-test.zip",
sha256: NodeCrypto.createHash("sha256").update(archive).digest("hex"),
sha256: Hex.encode(yield* crypto.digest("SHA-256", archive).pipe(Effect.orDie)),
archiveBytes: archive.byteLength,
executable: {
name: platform === "win32" ? "agy_acp_server.exe" : "agy_acp_server.par",
@@ -88,7 +90,7 @@ function releaseAsset(
bytes: Buffer.byteLength(harnessContents),
},
} satisfies AntigravityReleaseAsset;
}
});
const writeRelease = Effect.fn("test.writeAntigravityRelease")(function* (
managedDirectory: string,
@@ -146,11 +148,12 @@ const makeHarness = Effect.fn("test.makeAntigravityInstallation")(function* (
options.baseDir ?? (yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-test-" }));
const platform = options.platform ?? hostPlatform;
const archive = options.archive ?? completeArchive;
const asset = options.asset === undefined ? releaseAsset(archive, platform) : options.asset;
const asset =
options.asset === undefined ? yield* releaseAsset(archive, platform) : options.asset;
const managedDirectory = path.join(baseDir, "tools", "antigravity-acp", `${platform}-x64`);
if (options.previous) {
yield* writeRelease(managedDirectory, {
...releaseAsset(archive, platform),
...(yield* releaseAsset(archive, platform)),
sha256: previousReleaseId,
version: previousVersion,
});
@@ -301,9 +304,9 @@ it.layer(NodeServices.layer)("Antigravity installation", (it) => {
expect(yield* fs.readFileString(selected.executablePath)).toBe(serverContents);
expect(yield* fs.readFileString(selected.harnessPath)).toBe(harnessContents);
expect(yield* fs.readDirectory(path.join(installation.managedDirectory, "versions"))).toEqual(
expect.arrayContaining([previousReleaseId, releaseAsset().sha256]),
expect.arrayContaining([previousReleaseId, (yield* releaseAsset()).sha256]),
);
expect(requests).toEqual([releaseAsset().url]);
expect(requests).toEqual([(yield* releaseAsset()).url]);
}),
);
@@ -469,12 +472,12 @@ it.layer(NodeServices.layer)("Antigravity installation", (it) => {
);
it.effect.each([
{ name: "checksum mismatch", asset: { ...releaseAsset(), sha256: "2".repeat(64) } },
{ name: "short download", archive: completeArchive.subarray(0, -1), asset: releaseAsset() },
{ name: "checksum mismatch", completeAsset: { sha256: "2".repeat(64) } },
{ name: "short download", archive: completeArchive.subarray(0, -1), completeAsset: {} },
{
name: "oversized download",
archive: Buffer.concat([completeArchive, Buffer.from("extra")]),
asset: releaseAsset(),
completeAsset: {},
},
{ name: "wrong Content-Length", contentLength: completeArchive.byteLength + 1 },
{ name: "missing harness", archive: Buffer.from(zipFixtures.missingHarness, "base64") },
@@ -482,10 +485,14 @@ it.layer(NodeServices.layer)("Antigravity installation", (it) => {
{ name: "path traversal", archive: Buffer.from(zipFixtures.traversal, "base64") },
{ name: "symbolic link", archive: Buffer.from(zipFixtures.symlink, "base64") },
{ name: "oversized member", archive: Buffer.from(zipFixtures.oversizedMember, "base64") },
])("rejects $name before runtime validation", (options) =>
])("rejects $name before runtime validation", ({ completeAsset, ...options }) =>
Effect.gen(function* () {
// Pin the asset to the complete archive so the download itself is what disagrees.
const asset =
completeAsset === undefined ? undefined : { ...(yield* releaseAsset()), ...completeAsset };
const { installation, validations, stagingReleased, fs, path } = yield* makeHarness({
...options,
...(asset === undefined ? {} : { asset }),
previous: true,
});
yield* installation.start;
@@ -893,7 +900,7 @@ it.layer(NodeServices.layer)("Antigravity installation", (it) => {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const archive = Buffer.from(zipFixtures.windows, "base64");
const asset = releaseAsset(archive, "win32");
const asset = yield* releaseAsset(archive, "win32");
let denyPointerRename = true;
const renameTargets: string[] = [];
const { installation, requests, validations } = yield* makeHarness({
@@ -6,15 +6,16 @@ import {
HostProcessEnvironment,
HostProcessPlatform,
} from "@t3tools/shared/hostProcess";
import * as Crypto from "effect/Crypto";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Hex from "effect/encoding/Hex";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Exit from "effect/Exit";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import { HttpClient, HttpClientResponse } from "effect/http";
import * as NodeCrypto from "node:crypto";
import * as CodexInstallation from "./CodexInstallation.ts";
const archive = Buffer.from(
@@ -25,7 +26,6 @@ const asset = {
version: "0.156.1",
target: "aarch64-apple-darwin",
url: "https://github.com/openai/codex/releases/download/test/package.tar.gz",
sha256: NodeCrypto.createHash("sha256").update(archive).digest("hex"),
archiveBytes: archive.length,
};
const makeHarness = Effect.fn("test.makeCodexInstallation")(function* (
@@ -52,9 +52,11 @@ const makeHarness = Effect.fn("test.makeCodexInstallation")(function* (
);
}
let downloads = 0;
const crypto = yield* Crypto.Crypto;
const sha256 = Hex.encode(yield* crypto.digest("SHA-256", archive).pipe(Effect.orDie));
const installation = yield* CodexInstallation.makeCodexInstallation({
baseDir,
releaseAsset: asset,
releaseAsset: { ...asset, sha256 },
validate: () => Effect.void,
...input.options,
}).pipe(
+114 -105
View File
@@ -1,9 +1,11 @@
import * as NodeCrypto from "node:crypto";
import type {
ToolActivityIcon,
ToolActivityNativeAppReference,
ToolActivitySource,
} from "@t3tools/contracts";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Hex from "effect/encoding/Hex";
import type * as EffectCodexSchema from "effect-codex-app-server/schema";
import {
@@ -42,12 +44,17 @@ function normalizedSourceKeyPart(value: string): string {
return value.trim().toLowerCase();
}
function nativeAppSourceKey(appId: string): string {
const nativeAppSourceKey = Effect.fn("CodexToolPresentation.nativeAppSourceKey")(function* (
appId: string,
) {
const key = `native-app:${appId.toLowerCase()}`;
if (key.length <= 512) return key;
const digest = NodeCrypto.createHash("sha256").update(key).digest("hex");
const crypto = yield* Crypto.Crypto;
const digest = Hex.encode(
yield* crypto.digest("SHA-256", new TextEncoder().encode(key)).pipe(Effect.orDie),
);
return `${key.slice(0, 512 - digest.length - 1)}:${digest}`;
}
});
function browserDisplayName(value: unknown): string | undefined {
const normalized = normalizedDisplayName(value)?.toLowerCase();
@@ -123,105 +130,107 @@ export interface McpToolPresentation {
readonly toolSource?: ToolActivitySource;
}
export function mcpToolPresentation(
item: Extract<CodexLifecycleItem, { readonly type: "mcpToolCall" }>,
): McpToolPresentation {
const result = asUnknownRecord(item.result);
const metadata = asUnknownRecord(result?._meta);
const surface = asUnknownRecord(metadata?.["codex/toolSurface"]);
const sourceMetadata = asUnknownRecord(metadata?.source);
const appContext = asUnknownRecord(item.appContext);
const sourceLogo = themedLogoIcon(surface, sourceMetadata, appContext);
if (surface?.kind === "browserUse") {
const screenshot = asUnknownRecord(surface.screenshot);
const browserUse = asUnknownRecord(metadata?.browser_use);
const openTabs = Array.isArray(surface.openTabs) ? surface.openTabs : [];
const latestOpenTab = openTabs
.toReversed()
.map(asUnknownRecord)
.find((tab) => normalizedHttpUrl(tab?.url) !== undefined);
const selectedPage = [
{ record: screenshot, url: screenshot?.pageUrl },
{ record: browserUse, url: browserUse?.url },
{ record: latestOpenTab, url: latestOpenTab?.url },
]
.map((candidate) => ({ ...candidate, pageUrl: normalizedHttpUrl(candidate.url) }))
.find((candidate) => candidate.pageUrl !== undefined);
const pageUrl = selectedPage?.pageUrl;
const faviconUrl = normalizedImageUrl(
selectedPage?.record?.faviconUrl ?? selectedPage?.record?.favIconUrl,
);
const faviconUrlDark = normalizedImageUrl(
selectedPage?.record?.faviconUrlDark ?? selectedPage?.record?.favIconUrlDark,
);
const name =
browserDisplayName(appContext?.appName) ??
browserDisplayName(surface.browserFamily) ??
browserDisplayName(surface.backend) ??
"Browser";
const nativeBrowserIcon = browserNativeAppReference(name);
const sourceIcon =
sourceLogo ??
(nativeBrowserIcon ? ({ _tag: "native-app", app: nativeBrowserIcon } as const) : undefined);
const sourceKeyPart = normalizedSourceKeyPart(name) || "browser";
return {
toolSurface: "browser",
...(pageUrl
? {
toolIcon: {
_tag: "website",
pageUrl,
...(faviconUrl ? { faviconUrl } : {}),
...(faviconUrlDark ? { faviconUrlDark } : {}),
} as const,
}
: {}),
toolSource: {
key: `browser-use:${sourceKeyPart}`,
name,
kind: name === "Browser" ? "browser" : "integration",
...(sourceIcon ? { icon: sourceIcon } : {}),
},
};
}
if (surface?.kind === "computerUse") {
const app = nativeAppReference(surface.app);
const args = asUnknownRecord(item.arguments);
const argumentAppName =
normalizedDisplayName(args?.appName) ??
normalizedDisplayName(args?.application) ??
normalizedDisplayName(typeof args?.app === "string" ? args.app : undefined);
const name =
normalizedDisplayName(appContext?.appName) ??
argumentAppName ??
(app?._tag === "display-name" ? app.displayName : undefined) ??
(app?._tag === "app-id" ? appDisplayNameFromId(app.appId) : undefined) ??
"Computer Use";
const sourceIcon = sourceLogo ?? (app ? ({ _tag: "native-app", app } as const) : undefined);
const sourceKey = app
? app._tag === "app-id"
? nativeAppSourceKey(app.appId)
: `native-app-name:${normalizedSourceKeyPart(app.displayName)}`
: "computer-use";
return {
toolSurface: "computer",
...(app ? { toolIcon: { _tag: "native-app", app } as const } : {}),
toolSource: {
key: sourceKey,
name,
kind: "computer",
...(sourceIcon ? { icon: sourceIcon } : {}),
},
};
}
export const mcpToolPresentation = Effect.fn("CodexToolPresentation.mcpToolPresentation")(
function* (
item: Extract<CodexLifecycleItem, { readonly type: "mcpToolCall" }>,
): Effect.fn.Return<McpToolPresentation, never, Crypto.Crypto> {
const result = asUnknownRecord(item.result);
const metadata = asUnknownRecord(result?._meta);
const surface = asUnknownRecord(metadata?.["codex/toolSurface"]);
const sourceMetadata = asUnknownRecord(metadata?.source);
const appContext = asUnknownRecord(item.appContext);
const sourceLogo = themedLogoIcon(surface, sourceMetadata, appContext);
if (surface?.kind === "browserUse") {
const screenshot = asUnknownRecord(surface.screenshot);
const browserUse = asUnknownRecord(metadata?.browser_use);
const openTabs = Array.isArray(surface.openTabs) ? surface.openTabs : [];
const latestOpenTab = openTabs
.toReversed()
.map(asUnknownRecord)
.find((tab) => normalizedHttpUrl(tab?.url) !== undefined);
const selectedPage = [
{ record: screenshot, url: screenshot?.pageUrl },
{ record: browserUse, url: browserUse?.url },
{ record: latestOpenTab, url: latestOpenTab?.url },
]
.map((candidate) => ({ ...candidate, pageUrl: normalizedHttpUrl(candidate.url) }))
.find((candidate) => candidate.pageUrl !== undefined);
const pageUrl = selectedPage?.pageUrl;
const faviconUrl = normalizedImageUrl(
selectedPage?.record?.faviconUrl ?? selectedPage?.record?.favIconUrl,
);
const faviconUrlDark = normalizedImageUrl(
selectedPage?.record?.faviconUrlDark ?? selectedPage?.record?.favIconUrlDark,
);
const name =
browserDisplayName(appContext?.appName) ??
browserDisplayName(surface.browserFamily) ??
browserDisplayName(surface.backend) ??
"Browser";
const nativeBrowserIcon = browserNativeAppReference(name);
const sourceIcon =
sourceLogo ??
(nativeBrowserIcon ? ({ _tag: "native-app", app: nativeBrowserIcon } as const) : undefined);
const sourceKeyPart = normalizedSourceKeyPart(name) || "browser";
return {
toolSurface: "browser",
...(pageUrl
? {
toolIcon: {
_tag: "website",
pageUrl,
...(faviconUrl ? { faviconUrl } : {}),
...(faviconUrlDark ? { faviconUrlDark } : {}),
} as const,
}
: {}),
toolSource: {
key: `browser-use:${sourceKeyPart}`,
name,
kind: name === "Browser" ? "browser" : "integration",
...(sourceIcon ? { icon: sourceIcon } : {}),
},
};
}
if (surface?.kind === "computerUse") {
const app = nativeAppReference(surface.app);
const args = asUnknownRecord(item.arguments);
const argumentAppName =
normalizedDisplayName(args?.appName) ??
normalizedDisplayName(args?.application) ??
normalizedDisplayName(typeof args?.app === "string" ? args.app : undefined);
const name =
normalizedDisplayName(appContext?.appName) ??
argumentAppName ??
(app?._tag === "display-name" ? app.displayName : undefined) ??
(app?._tag === "app-id" ? appDisplayNameFromId(app.appId) : undefined) ??
"Computer Use";
const sourceIcon = sourceLogo ?? (app ? ({ _tag: "native-app", app } as const) : undefined);
const sourceKey = app
? app._tag === "app-id"
? yield* nativeAppSourceKey(app.appId)
: `native-app-name:${normalizedSourceKeyPart(app.displayName)}`
: "computer-use";
return {
toolSurface: "computer",
...(app ? { toolIcon: { _tag: "native-app", app } as const } : {}),
toolSource: {
key: sourceKey,
name,
kind: "computer",
...(sourceIcon ? { icon: sourceIcon } : {}),
},
};
}
return integrationToolPresentation({
serverName: appContext?.connectorId ?? item.server,
toolName: item.tool,
title: appContext?.actionName,
serverDisplayName: appContext?.appName,
source: sourceMetadata,
iconUrl: sourceLogo?._tag === "themed-logo" ? sourceLogo.logoUrl : undefined,
iconUrlDark: sourceLogo?._tag === "themed-logo" ? sourceLogo.logoUrlDark : undefined,
});
}
return integrationToolPresentation({
serverName: appContext?.connectorId ?? item.server,
toolName: item.tool,
title: appContext?.actionName,
serverDisplayName: appContext?.appName,
source: sourceMetadata,
iconUrl: sourceLogo?._tag === "themed-logo" ? sourceLogo.logoUrl : undefined,
iconUrlDark: sourceLogo?._tag === "themed-logo" ? sourceLogo.logoUrlDark : undefined,
});
},
);
@@ -1,5 +1,4 @@
import * as NodeAssert from "node:assert/strict";
import * as NodeCrypto from "node:crypto";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
@@ -81,7 +80,8 @@ it.effect("reads Go limits with the instance's XDG credentials and preserves res
NodeAssert.equal(limits.unavailable, undefined);
NodeAssert.equal(
limits.credentialFingerprint,
NodeCrypto.createHash("sha256").update("opencode-go\0instance-key").digest("hex"),
// SHA-256 of "opencode-go\0instance-key".
"aba48e85c981a8edc1c9fb4575121accc7235fa55d0f8689f66f153de5566a37",
);
NodeAssert.deepEqual(
limits.windows.map(({ kind, usedPercent, resetsAt: reset }) => ({
@@ -1,10 +1,11 @@
import * as NodeCrypto from "node:crypto";
import type {
AcpRegistrySettings,
ProviderInstanceEnvironment,
ProviderInstanceId,
} from "@t3tools/contracts";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Hex from "effect/encoding/Hex";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Ref from "effect/Ref";
@@ -16,8 +17,13 @@ import { writeFileStringAtomically } from "../../atomicWrite.ts";
const decodeState = Schema.decodeUnknownEffect(
Schema.fromJsonString(Schema.Struct({ binding: Schema.String, authenticated: Schema.Boolean })),
);
const hash = (value: unknown) =>
NodeCrypto.createHash("sha256").update(JSON.stringify(value)).digest("hex");
const encodeJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
const hash = Effect.fn("AcpRegistryAuthenticationState.hash")(function* (value: unknown) {
const crypto = yield* Crypto.Crypto;
const json = yield* encodeJson(value).pipe(Effect.orDie);
const digest = yield* crypto.digest("SHA-256", new TextEncoder().encode(json)).pipe(Effect.orDie);
return Hex.encode(digest);
});
/** Remember explicit sign-in success, never discovery success or the agent's credentials. */
export const makeAcpRegistryAuthenticationState = Effect.fn("makeAcpRegistryAuthenticationState")(
@@ -30,10 +36,10 @@ export const makeAcpRegistryAuthenticationState = Effect.fn("makeAcpRegistryAuth
}) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const filePath = path.join(input.cacheDir, `acp-auth-${hash(input.instanceId)}.json`);
const filePath = path.join(input.cacheDir, `acp-auth-${yield* hash(input.instanceId)}.json`);
// Cosmetic settings and model discovery can rebuild the driver without
// changing the account. Credential overrides and profile paths cannot.
const binding = hash({
const binding = yield* hash({
...(input.settings.source === "local"
? { source: "local", commandArgs: input.settings.commandArgs }
: {}),
@@ -16,7 +16,6 @@ import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import { HttpClient, HttpClientResponse } from "effect/http";
import * as TestClock from "effect/testing/TestClock";
import * as NodeCrypto from "node:crypto";
import { ChildProcess, ChildProcessSpawner } from "effect/process";
import * as AcpRegistrySupport from "./AcpRegistrySupport.ts";
@@ -587,7 +586,8 @@ describe("AcpRegistrySupport", () => {
archive: archiveUrl,
cmd: "./bin/example-agent",
args: ["acp"],
sha256: NodeCrypto.createHash("sha256").update(binaryBytes).digest("hex"),
// SHA-256 of binaryBytes.
sha256: "97b29a636d7ddf7bf3567ae4d48c0f2a9b03943fd808b6efbf74f1dd3db131b7",
},
},
});
@@ -646,7 +646,8 @@ describe("AcpRegistrySupport", () => {
archive: archiveUrl,
cmd: "./bin/example-agent",
args: ["acp"],
sha256: NodeCrypto.createHash("sha256").update(binaryBytes).digest("hex"),
// SHA-256 of binaryBytes.
sha256: "e1eb7c905b91c400af2ec858628aec22866bfda1383b93ceb73ae01d9769fb31",
},
},
});
@@ -25,7 +25,9 @@ import {
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as Duration from "effect/Duration";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Hex from "effect/encoding/Hex";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
@@ -35,9 +37,9 @@ import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as Stream from "effect/Stream";
import { sha256 } from "@noble/hashes/sha2";
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
import { ChildProcess, ChildProcessSpawner } from "effect/process";
import * as NodeCrypto from "node:crypto";
import { collectUint8StreamText } from "../../stream/collectUint8StreamText.ts";
import * as ServerSettings from "../../serverSettings.ts";
@@ -597,11 +599,15 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct
AcpRegistryCatalog["Service"],
never,
| ChildProcessSpawner.ChildProcessSpawner
| Crypto.Crypto
| FileSystem.FileSystem
| HttpClient.HttpClient
| Path.Path
| ServerSettings.ServerSettingsService
> {
const crypto = yield* Crypto.Crypto;
const sha256Hex = (data: Uint8Array) =>
crypto.digest("SHA-256", data).pipe(Effect.map(Hex.encode), Effect.orDie);
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const httpClient = yield* HttpClient.HttpClient;
@@ -731,17 +737,20 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct
.readFileString(registryCachePath)
.pipe(Effect.flatMap(decodeRegistryText), Effect.option);
const writeRegistryCache = (text: string) => {
const temporaryPath = `${registryCachePath}.${process.pid}-${NodeCrypto.randomUUID()}.tmp`;
return fileSystem
.makeDirectory(registryDirectory, { recursive: true })
.pipe(
Effect.andThen(fileSystem.writeFileString(temporaryPath, text)),
Effect.andThen(fileSystem.rename(temporaryPath, registryCachePath)),
Effect.ensuring(fileSystem.remove(temporaryPath, { force: true }).pipe(Effect.ignore)),
Effect.ignore,
);
};
const writeRegistryCache = (text: string) =>
crypto.randomUUIDv4.pipe(
Effect.flatMap((id) => {
const temporaryPath = `${registryCachePath}.${process.pid}-${id}.tmp`;
return fileSystem
.makeDirectory(registryDirectory, { recursive: true })
.pipe(
Effect.andThen(fileSystem.writeFileString(temporaryPath, text)),
Effect.andThen(fileSystem.rename(temporaryPath, registryCachePath)),
Effect.ensuring(fileSystem.remove(temporaryPath, { force: true }).pipe(Effect.ignore)),
);
}),
Effect.ignore,
);
const fetchRegistry = Effect.fn("AcpRegistryCatalog.fetchRegistry")(function* () {
yield* assertHttpsUrl(registryUrl, "ACP Registry index URL must use HTTPS.");
@@ -928,17 +937,12 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct
);
});
const packageReceiptPath = (
agentId: string,
distribution: "npx" | "uvx",
managerPath: string,
) => {
const managerId = NodeCrypto.createHash("sha256")
.update(`${distribution}\0${managerPath}`)
.digest("hex")
.slice(0, 16);
return path.join(packageReceiptsDirectory, `${agentId}-${managerId}.json`);
};
const packageReceiptPath = (agentId: string, distribution: "npx" | "uvx", managerPath: string) =>
sha256Hex(new TextEncoder().encode(`${distribution}\0${managerPath}`)).pipe(
Effect.map((digest) =>
path.join(packageReceiptsDirectory, `${agentId}-${digest.slice(0, 16)}.json`),
),
);
const readPackageReceipt = Effect.fn("AcpRegistryCatalog.readPackageReceipt")(function* (
agent: AcpRegistryAgent,
@@ -947,7 +951,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct
managerPath: string,
) {
const receipt = yield* fileSystem
.readFileString(packageReceiptPath(agent.id, distribution, managerPath))
.readFileString(yield* packageReceiptPath(agent.id, distribution, managerPath))
.pipe(
Effect.map(decodePackageInstallReceipt),
Effect.orElseSucceed(() => Option.none()),
@@ -991,7 +995,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct
const writePackageReceipt = Effect.fn("AcpRegistryCatalog.writePackageReceipt")(
function* (receipt: AcpRegistryPackageInstallReceipt) {
const receiptPath = packageReceiptPath(
const receiptPath = yield* packageReceiptPath(
receipt.agentId,
receipt.distribution,
receipt.managerPath,
@@ -1409,7 +1413,9 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct
),
}),
);
const hash = NodeCrypto.createHash("sha256");
// Hash while streaming: archives can be up to MAX_ARCHIVE_BYTES, and
// Effect's Crypto only digests a whole buffer.
const hash = sha256.create();
let downloadedBytes = 0;
yield* response.stream.pipe(
Stream.tap((chunk) => {
@@ -1447,7 +1453,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct
}),
);
if (target.sha256 !== undefined) {
const actual = hash.digest("hex");
const actual = Hex.encode(hash.digest());
if (actual !== target.sha256.toLowerCase()) {
return yield* new AcpRegistryError({
reason: "checksum_mismatch",
@@ -10,6 +10,7 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { AbsolutePath, Location, Model, Provider } from "@opencode/client/effect";
import { assert, it } from "@effect/vitest";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Base64Url from "effect/encoding/Base64Url";
import * as Fiber from "effect/Fiber";
@@ -21,7 +22,6 @@ import * as Path from "effect/Path";
import * as Stream from "effect/Stream";
import { FetchHttpClient } from "effect/http";
import { ChildProcess, ChildProcessSpawner } from "effect/process";
import * as NodeCrypto from "node:crypto";
import { describe } from "vite-plus/test";
import * as OpenCode2Client from "./OpenCode2Client.ts";
@@ -36,7 +36,8 @@ const startServer = Effect.fn("OpenCode2ClientLive.startServer")(function* (bina
const directory = path.join(root, "work");
yield* fs.makeDirectory(directory);
// Non-ASCII on purpose: OpenCode decodes Basic credentials as UTF-8.
const password = `${Base64Url.encode(NodeCrypto.randomBytes(32))}-pässwörd€`;
const crypto = yield* Crypto.Crypto;
const password = `${Base64Url.encode(yield* crypto.randomBytes(32))}-pässwörd€`;
const child = yield* spawner.spawn(
ChildProcess.make(binary, ["serve", "--hostname=127.0.0.1", "--port=0"], {
cwd: directory,
@@ -1,3 +1,4 @@
// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no createHmac.
import * as NodeCrypto from "node:crypto";
import * as NodePlatformCrypto from "@effect/platform-node/NodeCrypto";
@@ -1,4 +1,5 @@
import { describe, expect, it } from "@effect/vitest";
// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no generateKeyPairSync.
import * as NodeCrypto from "node:crypto";
import * as Clock from "effect/Clock";
import * as Effect from "effect/Effect";
@@ -1,3 +1,4 @@
// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no createHmac.
import * as NodeCrypto from "node:crypto";
import { assert, describe, it } from "@effect/vitest";
@@ -1,3 +1,4 @@
// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no createHmac or timingSafeEqual.
import * as NodeCrypto from "node:crypto";
import type { ScheduledTaskWebhookSignature } from "@t3tools/contracts";
@@ -16,6 +16,7 @@ import {
type SecretRequestAnswerInput,
type ThreadId,
} from "@t3tools/contracts";
// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no createHmac.
import * as NodeCrypto from "node:crypto";
import * as Clock from "effect/Clock";
+11 -6
View File
@@ -1,7 +1,8 @@
import * as NodeCrypto from "node:crypto";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Hex from "effect/encoding/Hex";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
@@ -17,8 +18,12 @@ interface CapturedLog {
readonly annotations: Readonly<Record<string, unknown>>;
}
const sha256 = (value: string) =>
NodeCrypto.createHash("sha256").update(value, "utf8").digest("hex");
const sha256 = Effect.fn("test.sha256")(function* (value: string) {
const crypto = yield* Crypto.Crypto;
return Hex.encode(
yield* crypto.digest("SHA-256", new TextEncoder().encode(value)).pipe(Effect.orDie),
);
});
const makeCaptureLogger = (logs: CapturedLog[]) =>
Logger.make(({ fiber, message }) => {
@@ -48,7 +53,7 @@ it.layer(NodeServices.layer)("telemetry identity", (it) => {
path.join(config.baseDir, "home"),
);
assert.equal(identifier, sha256(anonymousId));
assert.equal(identifier, yield* sha256(anonymousId));
}).pipe(
Effect.provide(
ServerConfig.layerTest(process.cwd(), {
@@ -132,7 +137,7 @@ it.layer(NodeServices.layer)("telemetry identity", (it) => {
const identifier = yield* Identify.getTelemetryIdentifierForHome(homeDirectory);
assert.equal(identifier, sha256(anonymousId));
assert.equal(identifier, yield* sha256(anonymousId));
assert.isUndefined(findIdentityLog(logs, "codex", "TelemetryIdentityDecodeError"));
assert.isUndefined(findIdentityLog(logs, "codex", "TelemetryIdentityReadError"));
const allLogs = logs
@@ -175,7 +180,7 @@ it.layer(NodeServices.layer)("telemetry identity", (it) => {
const identifier = yield* Identify.getTelemetryIdentifierForHome(homeDirectory);
assert.equal(identifier, sha256(anonymousId));
assert.equal(identifier, yield* sha256(anonymousId));
const decodeLog = findIdentityLog(logs, "codex", "TelemetryIdentityDecodeError");
assert.isDefined(decodeLog);
assert.equal(
+8 -3
View File
@@ -1,10 +1,11 @@
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as TestClock from "effect/testing/TestClock";
import { HttpClient, HttpClientResponse } from "effect/http";
import { creditRedeemRequestId, makeCliproxyApi } from "./cliproxyApi.ts";
import { makeCliproxyApi } from "./cliproxyApi.ts";
const config = {
kind: "cliproxy",
@@ -106,7 +107,10 @@ function fixture(
);
return {
requests,
api: makeCliproxyApi.pipe(Effect.provideService(HttpClient.HttpClient, http)),
api: makeCliproxyApi.pipe(
Effect.provideService(HttpClient.HttpClient, http),
Effect.provide(NodeCrypto.layer),
),
};
}
@@ -222,7 +226,8 @@ describe("CLIProxyAPI built-in management API", () => {
expect(redemptions[0]?.body?.data).toBe(redemptions[1]?.body?.data);
expect(redemptions[0]?.body?.data).toBe(
encodeJson({
redeem_request_id: creditRedeemRequestId("account-b", "credit-b"),
// UUIDv5 of "account-b:credit-b"; must stay stable so retries deduplicate.
redeem_request_id: "519d5243-011a-5b7b-91f3-44d85f095705",
credit_id: "credit-b",
}),
);
+22 -12
View File
@@ -1,5 +1,3 @@
import * as NodeCrypto from "node:crypto";
import {
ProviderDriverKind,
UsageLimitSourceError,
@@ -7,8 +5,10 @@ import {
type UsageLimitSourceAccount,
type UsageLimitSourceConfig,
} from "@t3tools/contracts";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Hex from "effect/encoding/Hex";
import * as Schema from "effect/Schema";
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
@@ -99,21 +99,31 @@ const decodeConsumeResponse = Schema.decodeUnknownEffect(
const CODEX_BASE = "https://chatgpt.com/backend-api/wham";
const CREDIT_URL = `${CODEX_BASE}/rate-limit-reset-credits`;
// 6f1c2a9e-2d4b-4c1e-9a7f-3b8d5e0c1a42
const CREDIT_REDEEM_NAMESPACE = new Uint8Array([
0x6f, 0x1c, 0x2a, 0x9e, 0x2d, 0x4b, 0x4c, 0x1e, 0x9a, 0x7f, 0x3b, 0x8d, 0x5e, 0x0c, 0x1a, 0x42,
]);
// UUIDv5 per account and credit also deduplicates retries across T3 environments.
export function creditRedeemRequestId(accountId: string, creditId: string): string {
const bytes = NodeCrypto.createHash("sha1")
.update(Buffer.from("6f1c2a9e2d4b4c1e9a7f3b8d5e0c1a42", "hex"))
.update(`${accountId}:${creditId}`)
.digest()
.subarray(0, 16);
const creditRedeemRequestId = Effect.fn("CliproxyApi.creditRedeemRequestId")(function* (
accountId: string,
creditId: string,
) {
const crypto = yield* Crypto.Crypto;
const name = new TextEncoder().encode(`${accountId}:${creditId}`);
const input = new Uint8Array(CREDIT_REDEEM_NAMESPACE.length + name.length);
input.set(CREDIT_REDEEM_NAMESPACE);
input.set(name, CREDIT_REDEEM_NAMESPACE.length);
const bytes = (yield* crypto.digest("SHA-1", input).pipe(Effect.orDie)).slice(0, 16);
bytes[6] = (bytes[6]! & 0x0f) | 0x50;
bytes[8] = (bytes[8]! & 0x3f) | 0x80;
const hex = bytes.toString("hex");
const hex = Hex.encode(bytes);
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}
});
export const makeCliproxyApi = Effect.gen(function* () {
const client = yield* HttpClient.HttpClient;
const crypto = yield* Crypto.Crypto;
const management = Effect.fn("CliproxyApi.management")(function* (
config: UsageLimitSourceConfig,
@@ -323,10 +333,10 @@ export const makeCliproxyApi = Effect.gen(function* () {
});
}
const body = yield* apiCall(config, account, `${CREDIT_URL}/consume`, {
redeem_request_id: creditRedeemRequestId(
redeem_request_id: yield* creditRedeemRequestId(
account.id_token?.chatgpt_account_id ?? account.id,
creditId,
),
).pipe(Effect.provideService(Crypto.Crypto, crypto)),
credit_id: creditId,
});
const response = yield* decodeConsumeResponse(body);
+1
View File
@@ -1,4 +1,5 @@
import * as Effect from "effect/Effect";
// @effect-diagnostics-next-line nodeBuiltinImport:off -- type-only, to adapt a Node Readable into Effect.
import type * as NodeStream from "node:stream";
import * as Yauzl from "yauzl";
@@ -1,3 +1,4 @@
// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no generateKeyPairSync.
import * as NodeCrypto from "node:crypto";
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
@@ -4,6 +4,7 @@ import type {
} from "@t3tools/contracts/relay";
import * as NodeCryptoLayer from "@effect/platform-node/NodeCrypto";
import { describe, expect, it } from "@effect/vitest";
// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no generateKeyPairSync.
import * as NodeCrypto from "node:crypto";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
@@ -1,3 +1,4 @@
// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no generateKeyPairSync.
import * as NodeCrypto from "node:crypto";
import { describe, expect, it } from "@effect/vitest";
@@ -1,3 +1,4 @@
// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no generateKeyPairSync or verify.
import * as NodeCrypto from "node:crypto";
import { describe, expect, it } from "@effect/vitest";
import * as Deferred from "effect/Deferred";
@@ -1,3 +1,4 @@
// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no createHmac or timingSafeEqual.
import * as NodeCrypto from "node:crypto";
import {
+1
View File
@@ -1,3 +1,4 @@
// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no createPrivateKey.
import * as NodeCrypto from "node:crypto";
import { p256 } from "@noble/curves/nist";
@@ -1,3 +1,4 @@
// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no generateKeyPairSync or sign.
import * as NodeCrypto from "node:crypto";
import { describe, expect, it } from "@effect/vitest";
+1
View File
@@ -1,3 +1,4 @@
// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no generateKeyPairSync.
import * as NodeCrypto from "node:crypto";
import { describe, expect, it } from "@effect/vitest";
@@ -1,3 +1,4 @@
// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no generateKeyPairSync or sign.
import * as NodeCrypto from "node:crypto";
import * as NodeCryptoLayer from "@effect/platform-node/NodeCrypto";
@@ -1,3 +1,4 @@
// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no generateKeyPairSync or sign.
import * as NodeCrypto from "node:crypto";
import type {
RelayEnvironmentLinkProofPayload,
@@ -1,3 +1,4 @@
// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no generateKeyPairSync or sign.
import * as NodeCrypto from "node:crypto";
import * as NodeServices from "@effect/platform-node/NodeServices";
import type {
@@ -1,4 +1,3 @@
import * as NodeCrypto from "node:crypto";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, expect, it } from "@effect/vitest";
@@ -365,20 +364,26 @@ function layerProvider(
);
}
// First 16 hex chars of SHA-256(`dev_julius:${userId}:${environmentId}`), pinned so a
// change to the endpoint naming scheme fails here instead of silently matching.
const MANAGED_ENDPOINT_HASHES: Record<string, string> = {
"user_ABC:env_ABC": "d101ac68108a423e",
"user_ABC:env_shared": "d7e6356aaf8863aa",
"user_DEF:env_shared": "a2fc84ac1b8c1c35",
};
function expectedManagedEndpointHash(environmentId: string, userId: string): string {
const hash = MANAGED_ENDPOINT_HASHES[`${userId}:${environmentId}`];
if (hash === undefined) throw new Error(`No pinned hash for ${userId}:${environmentId}`);
return hash;
}
function expectedManagedHostname(environmentId: string, userId = "user_ABC"): string {
const hash = NodeCrypto.createHash("sha256")
.update(`dev_julius:${userId}:${environmentId}`)
.digest("hex")
.slice(0, 16);
return `dev-julius-${hash}.t3code.test`;
return `dev-julius-${expectedManagedEndpointHash(environmentId, userId)}.t3code.test`;
}
function expectedManagedTunnelName(environmentId: string, userId = "user_ABC"): string {
const hash = NodeCrypto.createHash("sha256")
.update(`dev_julius:${userId}:${environmentId}`)
.digest("hex")
.slice(0, 16);
return `t3coderelay-managedendpoint-dev-julius-${hash}`;
return `t3coderelay-managedendpoint-dev-julius-${expectedManagedEndpointHash(environmentId, userId)}`;
}
describe("ManagedEndpointProvider", () => {
@@ -1,5 +1,6 @@
import * as NodeHttpPlatform from "@effect/platform-node/NodeHttpPlatform";
import * as NodeServices from "@effect/platform-node/NodeServices";
// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no generateKeyPairSync.
import * as NodeCrypto from "node:crypto";
import * as EffectNodeCrypto from "@effect/platform-node/NodeCrypto";
import { describe, expect, it } from "@effect/vitest";
+1
View File
@@ -7,6 +7,7 @@ import {
import * as EnvironmentLinker from "../environments/EnvironmentLinker.ts";
import * as RelayTokens from "../auth/RelayTokens.ts";
import * as Devices from "../agentActivity/Devices.ts";
// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no generateKeyPairSync.
import * as NodeCrypto from "node:crypto";
import { createClerkClient, verifyToken } from "@clerk/backend";
import * as NodeHttpPlatform from "@effect/platform-node/NodeHttpPlatform";
@@ -1,3 +1,4 @@
// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no createHmac or timingSafeEqual.
import * as NodeCrypto from "node:crypto";
/**
+1
View File
@@ -1,3 +1,4 @@
// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no KeyObject, generateKeyPairSync, or sign.
import * as NodeCrypto from "node:crypto";
import { assert, describe, it } from "@effect/vitest";
+1
View File
@@ -1,3 +1,4 @@
// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no generateKeyPairSync.
import * as NodeCrypto from "node:crypto";
import { describe, expect, it } from "@effect/vitest";
+25
View File
@@ -14,6 +14,7 @@ import {
baseSshArgs,
getLastNonEmptyOutputLine,
parseSshResolveOutput,
remoteStateKey,
runSshCommand,
} from "./command.ts";
import { SshCommandError } from "./errors.ts";
@@ -98,6 +99,30 @@ describe("ssh command", () => {
}),
);
// Remote servers store state under this key, so it must not change across releases.
it.effect("derives a stable remote state key", () =>
Effect.gen(function* () {
assert.equal(
yield* remoteStateKey({
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 2222,
}),
"711bc738002d72fd",
);
assert.equal(
yield* remoteStateKey({
alias: "fixture",
hostname: "fixture",
username: null,
port: null,
}),
"326264c4f08c8a0c",
);
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("reads the last non-empty ssh output line", () =>
Effect.sync(() => {
assert.equal(
+12 -8
View File
@@ -1,9 +1,9 @@
import * as NodeCrypto from "node:crypto";
import type { DesktopSshEnvironmentTarget } from "@t3tools/contracts";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Crypto from "effect/Crypto";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Hex from "effect/encoding/Hex";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
@@ -72,12 +72,16 @@ export function targetConnectionKey(target: DesktopSshEnvironmentTarget): string
return `${target.alias}\u0000${target.hostname}\u0000${target.username ?? ""}\u0000${target.port ?? ""}`;
}
export function remoteStateKey(target: DesktopSshEnvironmentTarget): string {
return NodeCrypto.createHash("sha256")
.update(targetConnectionKey(target))
.digest("hex")
.slice(0, 16);
}
/** Names the remote state directory for a target: the first 16 hex chars of its SHA-256 key. */
export const remoteStateKey = Effect.fn("ssh/command.remoteStateKey")(function* (
target: DesktopSshEnvironmentTarget,
): Effect.fn.Return<string, never, Crypto.Crypto> {
const crypto = yield* Crypto.Crypto;
const digest = yield* crypto
.digest("SHA-256", encoder.encode(targetConnectionKey(target)))
.pipe(Effect.orDie);
return Hex.encode(digest).slice(0, 16);
});
function buildSshHostSpec(target: DesktopSshEnvironmentTarget): string {
const destination = target.alias.trim() || target.hostname.trim();
+9 -6
View File
@@ -11,6 +11,7 @@ import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/process";
import * as NodeNet from "node:net";
import { remoteStateKey } from "./command.ts";
import { buildRemoteStopScript, buildRemoteT3RunnerScript } from "./tunnel.ts";
const Started = Schema.Struct({
@@ -186,12 +187,14 @@ server.listen(0, "127.0.0.1", () => {
for (const [name, contents] of Object.entries(savedState)) {
yield* fs.writeFileString(path.join(fixture, name), contents);
}
const script = buildRemoteStopScript({
alias: "fixture",
hostname: "fixture",
username: null,
port: null,
});
const script = buildRemoteStopScript(
yield* remoteStateKey({
alias: "fixture",
hostname: "fixture",
username: null,
port: null,
}),
);
// Redirect only the state directory. Never use the developer's SSH state.
const isolatedScript = script.replace(
/^STATE_DIR=.*$/mu,
+8 -13
View File
@@ -233,12 +233,7 @@ describe("ssh tunnel scripts", () => {
});
it("uses the remote t3 runner for launch and pairing scripts", () => {
const target = {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 2222,
} as const;
const stateKey = "711bc738002d72fd";
const launch = SshTunnel.buildRemoteLaunchScript(ARCHIVE);
const devLaunch = SshTunnel.buildRemoteLaunchScript({
...NODE_SCRIPT,
@@ -265,28 +260,28 @@ describe("ssh tunnel scripts", () => {
assert.include(launch, "It wrote nothing to %s");
assert.include(launch, "T3_ARCHIVE_VERSION='1.2.3-preview.20260911.4'");
assert.include(
SshTunnel.buildRemotePairingScript(target, ARCHIVE),
SshTunnel.buildRemotePairingScript(stateKey, ARCHIVE),
'"$RUNNER_FILE" auth pairing create --base-dir "$PAIRING_BASE_DIR" --json',
);
assert.include(
SshTunnel.buildRemotePairingScript(target, ARCHIVE),
SshTunnel.buildRemotePairingScript(stateKey, ARCHIVE),
'PAIRING_BASE_DIR="$DEFAULT_SERVER_HOME"',
);
assert.notInclude(SshTunnel.buildRemotePairingScript(target, ARCHIVE), "server-home");
assert.notInclude(SshTunnel.buildRemotePairingScript(stateKey, ARCHIVE), "server-home");
assert.include(
SshTunnel.buildRemotePairingScript(target, ARCHIVE),
SshTunnel.buildRemotePairingScript(stateKey, ARCHIVE),
"T3_ARCHIVE_VERSION='1.2.3-preview.20260911.4'",
);
assert.include(
SshTunnel.buildRemoteStopScript(target),
SshTunnel.buildRemoteStopScript(stateKey),
'if [ "$REMOTE_MANAGED" != "external" ] && [ -n "$REMOTE_PID" ]',
);
assert.include(
SshTunnel.buildRemoteStopScript(target),
SshTunnel.buildRemoteStopScript(stateKey),
'kill "$REMOTE_PID" 2>/dev/null || true',
);
assert.include(
SshTunnel.buildRemoteStopScript(target),
SshTunnel.buildRemoteStopScript(stateKey),
'rm -f "$PID_FILE" "$PORT_FILE" "$MANAGED_FILE"',
);
assert.include(
+29 -24
View File
@@ -12,6 +12,7 @@ import * as NetService from "@t3tools/shared/Net";
import { extractJsonObject, fromLenientJson } from "@t3tools/shared/schemaJson";
import { satisfiesSemverRange } from "@t3tools/shared/semver";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
@@ -98,6 +99,7 @@ interface SshTunnelEntry {
type SshEnvironmentEffectContext =
| ChildProcessSpawner.ChildProcessSpawner
| Crypto.Crypto
| FileSystem.FileSystem
| Path.Path
| HttpClient.HttpClient
@@ -837,25 +839,22 @@ export function buildRemoteLaunchScript(input?: RemoteT3RunnerOptions): string {
});
}
export function buildRemotePairingScript(
target: DesktopSshEnvironmentTarget,
input?: RemoteT3RunnerOptions,
): string {
export function buildRemotePairingScript(stateKey: string, input?: RemoteT3RunnerOptions): string {
return applyScriptPlaceholders(REMOTE_PAIRING_SCRIPT, {
T3_STATE_KEY: remoteStateKey(target),
T3_STATE_KEY: stateKey,
T3_RUNNER_SCRIPT: stripTrailingNewlines(buildRemoteT3RunnerScript(input)),
});
}
export function buildRemoteStopScript(target: DesktopSshEnvironmentTarget): string {
export function buildRemoteStopScript(stateKey: string): string {
return applyScriptPlaceholders(REMOTE_STOP_SCRIPT, {
T3_STATE_KEY: remoteStateKey(target),
T3_STATE_KEY: stateKey,
});
}
function buildRemoteLogTailScript(target: DesktopSshEnvironmentTarget): string {
function buildRemoteLogTailScript(stateKey: string): string {
return applyScriptPlaceholders(REMOTE_LOG_TAIL_SCRIPT, {
T3_STATE_KEY: remoteStateKey(target),
T3_STATE_KEY: stateKey,
});
}
@@ -867,15 +866,16 @@ export const launchOrReuseRemoteServer = Effect.fn("ssh/tunnel.launchOrReuseRemo
): Effect.fn.Return<
{ readonly remotePort: number; readonly remoteServerKind: "external" | "managed" | null },
SshCommandError | SshInvalidTargetError | SshLaunchError,
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | FileSystem.FileSystem | Path.Path
> {
const stateKey = yield* remoteStateKey(target);
yield* Effect.logInfo("ssh.remoteServer.launch.start", {
...sshTargetLogFields(target),
...sshRunnerLogFields(runner),
stateKey: remoteStateKey(target),
stateKey,
});
const result = yield* runSshCommand(target, {
remoteCommandArgs: ["sh", "-l", "-s", "--", remoteStateKey(target)],
remoteCommandArgs: ["sh", "-l", "-s", "--", stateKey],
stdin: buildRemoteLaunchScript(runner),
timeoutMs: isNodeScriptRunner(runner)
? REMOTE_LAUNCH_TIMEOUT_MS
@@ -910,7 +910,7 @@ export const launchOrReuseRemoteServer = Effect.fn("ssh/tunnel.launchOrReuseRemo
...sshTargetLogFields(target),
remotePort: parsed.remotePort,
remoteServerKind: parsed.serverKind ?? null,
stateKey: remoteStateKey(target),
stateKey,
});
return {
remotePort: parsed.remotePort,
@@ -928,15 +928,16 @@ export const issueRemotePairingToken = Effect.fn("ssh/tunnel.issueRemotePairingT
readonly credential: string;
},
SshCommandError | SshInvalidTargetError | SshPairingError,
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | FileSystem.FileSystem | Path.Path
> {
const stateKey = yield* remoteStateKey(target);
yield* Effect.logDebug("ssh.remoteServer.pairingToken.start", {
...sshTargetLogFields(target),
stateKey: remoteStateKey(target),
stateKey,
});
const result = yield* runSshCommand(target, {
remoteCommandArgs: ["sh", "-s"],
stdin: buildRemotePairingScript(target, runner),
stdin: buildRemotePairingScript(stateKey, runner),
// Pairing may be the first command on a cold remote, so it can install
// the archive on the way.
...(isNodeScriptRunner(runner) ? {} : { timeoutMs: REMOTE_ARCHIVE_LAUNCH_TIMEOUT_MS }),
@@ -968,7 +969,7 @@ export const issueRemotePairingToken = Effect.fn("ssh/tunnel.issueRemotePairingT
}
yield* Effect.logDebug("ssh.remoteServer.pairingToken.created", {
...sshTargetLogFields(target),
stateKey: remoteStateKey(target),
stateKey,
});
return {
credential: parsed.credential,
@@ -981,22 +982,23 @@ const stopRemoteServer = Effect.fn("ssh/tunnel.stopRemoteServer")(function* (
): Effect.fn.Return<
void,
SshCommandError | SshInvalidTargetError,
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | FileSystem.FileSystem | Path.Path
> {
const stateKey = yield* remoteStateKey(target);
yield* Effect.logInfo("ssh.remoteServer.stop.start", {
...sshTargetLogFields(target),
stateKey: remoteStateKey(target),
stateKey,
});
yield* runSshCommand(target, {
remoteCommandArgs: ["sh", "-s"],
stdin: buildRemoteStopScript(target),
stdin: buildRemoteStopScript(stateKey),
...(input?.authSecret === undefined ? {} : { authSecret: input.authSecret }),
...(input?.batchMode === undefined ? {} : { batchMode: input.batchMode }),
...(input?.interactiveAuth === undefined ? {} : { interactiveAuth: input.interactiveAuth }),
});
yield* Effect.logInfo("ssh.remoteServer.stop.succeeded", {
...sshTargetLogFields(target),
stateKey: remoteStateKey(target),
stateKey,
});
});
@@ -1006,11 +1008,11 @@ const readRemoteServerLogTail = Effect.fn("ssh/tunnel.readRemoteServerLogTail")(
): Effect.fn.Return<
string,
SshCommandError | SshInvalidTargetError,
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | FileSystem.FileSystem | Path.Path
> {
const result = yield* runSshCommand(target, {
remoteCommandArgs: ["sh", "-s"],
stdin: buildRemoteLogTailScript(target),
stdin: buildRemoteLogTailScript(yield* remoteStateKey(target)),
timeoutMs: 10_000,
...(input?.authSecret === undefined ? {} : { authSecret: input.authSecret }),
...(input?.batchMode === undefined ? {} : { batchMode: input.batchMode }),
@@ -1109,6 +1111,7 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input:
SshTunnelEntry,
SshCommandError | SshInvalidTargetError | SshReadinessError,
| ChildProcessSpawner.ChildProcessSpawner
| Crypto.Crypto
| FileSystem.FileSystem
| Path.Path
| HttpClient.HttpClient
@@ -1538,6 +1541,7 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
);
tunnels.set(input.key, tunnelEntry);
const spawnerService = yield* ChildProcessSpawner.ChildProcessSpawner;
const cryptoService = yield* Crypto.Crypto;
const fileSystemService = yield* FileSystem.FileSystem;
const pathService = yield* Path.Path;
yield* Scope.addFinalizer(
@@ -1577,6 +1581,7 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
},
).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawnerService),
Effect.provideService(Crypto.Crypto, cryptoService),
Effect.provideService(FileSystem.FileSystem, fileSystemService),
Effect.provideService(Path.Path, pathService),
);
@@ -1757,7 +1762,7 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
});
/**
* @effect-expect-leaking ChildProcessSpawner | FileSystem | HttpClient | NetService | Path | SshPasswordPrompt
* @effect-expect-leaking ChildProcessSpawner | Crypto | FileSystem | HttpClient | NetService | Path | SshPasswordPrompt
*/
export class SshEnvironmentManager extends Context.Service<
SshEnvironmentManager,
+37 -34
View File
@@ -13,8 +13,8 @@ catalogs:
specifier: 4.0.1
version: 4.0.1
'@effect/tsgo':
specifier: 0.41.0
version: 0.41.0
specifier: 0.46.1
version: 0.46.1
'@legendapp/list':
specifier: 3.3.5
version: 3.3.5
@@ -131,7 +131,7 @@ importers:
version: 1.1.0
'@effect/tsgo':
specifier: 'catalog:'
version: 0.41.0
version: 0.46.1
'@shadcn/lint':
specifier: 0.1.5
version: 0.1.5
@@ -540,6 +540,9 @@ importers:
'@napi-rs/keyring':
specifier: ^1.3.0
version: 1.3.0
'@noble/hashes':
specifier: 'catalog:'
version: 1.8.0
'@opencode-ai/sdk':
specifier: ^1.3.15
version: 1.15.13
@@ -2384,43 +2387,43 @@ packages:
peerDependencies:
effect: 4.0.1
'@effect/[email protected]1.0':
resolution: {integrity: sha512-3iEPtcHF72yDjv7T5YpnX+Io1LDLywJb1oGG3Fp/Fth4xmqiT1Vacyz5wnPCfEWGQ6CyrlyCZSSjUxPyJ70+DQ==}
'@effect/[email protected]6.1':
resolution: {integrity: sha512-ErehNqI9p8me4XKO8N4bzdDWgBbSNlJ3CIZGfXoAW6Fo4Oo7x4ZbZV7KNsMSn9aJSiUUOQUoXjGBdslU5OYMdw==}
cpu: [arm64]
os: [darwin]
'@effect/[email protected]1.0':
resolution: {integrity: sha512-rrVVNacJ/Qh8DfdfgNJDuzcVmR3xPnqes3z+F1kio99umJwPIRB8iPWRAY0SrO+Y84A/y2SSb0AjMGqA5V3Aiw==}
'@effect/[email protected]6.1':
resolution: {integrity: sha512-zsQI1gjGMYF/C2FWDUwbStBAf0tJDVgXeWwTAZ+VUiNY06fR1SrZHK0L+22PE49Nim3biWK2h+XXRFVzql+ojg==}
cpu: [x64]
os: [darwin]
'@effect/[email protected]1.0':
resolution: {integrity: sha512-RVI+7pG3tP56LfH06a2aq4KLp2RQ0HohW8mmoGmrBPyNEL9DnzFEGB98ZoMJ+ERYUJoIp74Jy3nKRVbnzVhxFw==}
'@effect/[email protected]6.1':
resolution: {integrity: sha512-e283BZEQC3mJpk1N7vdUhoF/aYHc4YwCE/fwz/80d11OSvG35U+c49grxS7V7+dAl2ld6QiT8D1rcL8PYu8DLQ==}
cpu: [arm64]
os: [linux]
'@effect/[email protected]1.0':
resolution: {integrity: sha512-JddS91IaupLa22oc4YQiYppe7iAZAEyx/2iR9sAAAhpVanWACsIAcyUy4RJrs8sPLLoLsZQaKQa+9rbQO1FLsg==}
'@effect/[email protected]6.1':
resolution: {integrity: sha512-Y12wOcJ6HgwiCgg/oDQH4tdRQKRsWnul/KjCOwMxzVT4kO+ndczu1sKUZT+qIxV7qNk4Sq+uSWKEnFBA3ETI8w==}
cpu: [arm]
os: [linux]
'@effect/[email protected]1.0':
resolution: {integrity: sha512-U3+kMDVe2Opa5mxbN4B6PgOizWx5B4LXLN98CZDUl2vYtRGfwrRRhKQiB+de3ELaZ0MuDjPlCvU7S2mXQ8UiuQ==}
'@effect/[email protected]6.1':
resolution: {integrity: sha512-NYGBC3Scfo9yZJfs7cg0KMcHgtukJ4+xff18nqIrON9Zzc/qD6w1AwEwYKYCsbai5hTQBb3VLIWmHM8BJ54WJg==}
cpu: [x64]
os: [linux]
'@effect/[email protected]1.0':
resolution: {integrity: sha512-H6/xkn+B4B63OPKc0UAzQQFvLs0MXKigiD9dtvQeCU7czWGztOQILuLkyHnM1Dlc+uy4cJ5eXHiMXd+lwl+E8g==}
'@effect/[email protected]6.1':
resolution: {integrity: sha512-MK93SN9qjowrCjch+2wGGncd6Y7KgDyJvLKVVFCJV8cPpHoL3xDCpxFCGqQWe120mVpLmnzbM2evKdh0M5l5PA==}
cpu: [arm64]
os: [win32]
'@effect/[email protected]1.0':
resolution: {integrity: sha512-vRN/Mhi381xEGrvV68IN/VO4Lc0pnlVQzHSVmNCJXLwGLmJUvuvPoyZ7Lv4wwHRX9iZe8Rch21xUGu5jSQtUSw==}
'@effect/[email protected]6.1':
resolution: {integrity: sha512-hlRbeNlp0N/dfZZFl+xVzT3XfHYqPmkXzCadR6e5yoe/vyA3O9RnO5UrOBHsXvL2RTE6hrh8bRfx2Uu6g3LL5w==}
cpu: [x64]
os: [win32]
'@effect/[email protected]1.0':
resolution: {integrity: sha512-C/U7lFM0AXsfpqRilDOgwu+llBhAo8bcdIlzgbRWf1LWlU4KZKB2UsUvBPL3qPnm+wmbCvQLeTQc4BjV9oJrcg==}
'@effect/[email protected]6.1':
resolution: {integrity: sha512-DMcBCg5nWLufejRlyqFEkXmbtaLUJ56NKny6L1LTtimvz0U3VNj9H6ZUXV4WeeWvJzVyL0y7G2wsCBAFUgy1jw==}
hasBin: true
'@effect/[email protected]':
@@ -13055,36 +13058,36 @@ snapshots:
dependencies:
effect: 4.0.1(patch_hash=a33cba07c41f32374c2aaa86ea4a84d3ab9a872a78c94b65e929b19f8361856f)
'@effect/[email protected]1.0':
'@effect/[email protected]6.1':
optional: true
'@effect/[email protected]1.0':
'@effect/[email protected]6.1':
optional: true
'@effect/[email protected]1.0':
'@effect/[email protected]6.1':
optional: true
'@effect/[email protected]1.0':
'@effect/[email protected]6.1':
optional: true
'@effect/[email protected]1.0':
'@effect/[email protected]6.1':
optional: true
'@effect/[email protected]1.0':
'@effect/[email protected]6.1':
optional: true
'@effect/[email protected]1.0':
'@effect/[email protected]6.1':
optional: true
'@effect/[email protected]1.0':
'@effect/[email protected]6.1':
optionalDependencies:
'@effect/tsgo-darwin-arm64': 0.41.0
'@effect/tsgo-darwin-x64': 0.41.0
'@effect/tsgo-linux-arm': 0.41.0
'@effect/tsgo-linux-arm64': 0.41.0
'@effect/tsgo-linux-x64': 0.41.0
'@effect/tsgo-win32-arm64': 0.41.0
'@effect/tsgo-win32-x64': 0.41.0
'@effect/tsgo-darwin-arm64': 0.46.1
'@effect/tsgo-darwin-x64': 0.46.1
'@effect/tsgo-linux-arm': 0.46.1
'@effect/tsgo-linux-arm64': 0.46.1
'@effect/tsgo-linux-x64': 0.46.1
'@effect/tsgo-win32-arm64': 0.46.1
'@effect/tsgo-win32-x64': 0.46.1
'@effect/[email protected](patch_hash=359f6fb2f7b3ec145bb72208edb9034f02489791aa2491a55cdbd69bd56ee0d2)(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](patch_hash=a33cba07c41f32374c2aaa86ea4a84d3ab9a872a78c94b65e929b19f8361856f))([email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])':
dependencies:
+1 -1
View File
@@ -36,7 +36,7 @@ catalog:
"@effect/platform-node-shared": 4.0.1
"@effect/sql-pg": 4.0.1
"@effect/sql-sqlite-do": 4.0.1
"@effect/tsgo": 0.41.0
"@effect/tsgo": 0.46.1
"@effect/vitest": 4.0.1
"@legendapp/list": 3.3.5
"@noble/curves": 1.9.1
-1
View File
@@ -23,7 +23,6 @@
"name": "@effect/language-service",
"namespaceImportPackages": ["@effect/platform-node", "effect"],
"diagnosticSeverity": {
"importFromBarrel": "error",
"anyUnknownInErrorContext": "error",
"unsafeEffectTypeAssertion": "error",
"instanceOfSchema": "error",