diff --git a/.github/fork/carried-prs.json b/.github/fork/carried-prs.json index a399712b2eb36..bc7256800173d 100644 --- a/.github/fork/carried-prs.json +++ b/.github/fork/carried-prs.json @@ -3,7 +3,7 @@ "prs": [ { "number": 15030, - "takenSha": "a2d855c9f602d50da63fea6c07d3ca6c7db36655", + "takenSha": "10a559eb78969c6b4338baa550a8383506ffb0a2", "reason": "iOS race fixes and Android keyboard parity" }, { @@ -25,31 +25,25 @@ }, { "number": 17890, - "takenSha": "0a5d3e0083e43946b180dc4cc89568af111c645c", + "takenSha": "8f5b0434d7404ca8d1cfa0f60c62b79a7b719b1a", "reason": "Android subscription usage widgets", + "note": "8f5b0434d7 only merges upstream main into the PR; the fork resolved the same merge itself.", "closedUpstream": true }, { "number": 18634, - "takenSha": "6485555d5d7c365849dd6def5a335c8171238ccf", + "takenSha": "dc6f194db92178418f6aa34ceeb2bc4577ab0b17", "reason": "Android tablets launched in landscape open full screen" }, { "number": 18839, - "takenSha": "457acb425c5fa5d5248bc0ed646b5ccb68f8f256", + "takenSha": "9d3aac8a0ee60a1883f067185ca1a9705e385360", "reason": "Android PR viewer keeps the chat back stack" }, { "number": 19273, - "takenSha": "c983c522ad9c2e3ffd5735cdbfca6c073f9cde95", + "takenSha": "b8d5c37cf59f7989edaf14dea2822f28ae841fdb", "reason": "Local-model composer dictation" - }, - { - "number": 19424, - "takenSha": "9e5e520f786566b3004a004efc9e21817ad49e9c", - "reason": "Android foldables use the sidebar header", - "note": "Took only the first two commits. Upstream superseded it with merged #21071, #20812 and #20813.", - "closedUpstream": true } ] } diff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.yml index 5a16a9b4c170f..3af4e6abeafe9 100644 --- a/.github/workflows/release-desktop.yml +++ b/.github/workflows/release-desktop.yml @@ -203,6 +203,14 @@ jobs: native/hyprland-snap-shot/target/${{ inputs.rust_target }}/release/t3-hyprland-snap-shot key: linux-capture-helpers-${{ inputs.rust_target }}-${{ hashFiles('native/kde-snap-shot/Cargo.lock', 'native/kde-snap-shot/Cargo.toml', 'native/kde-snap-shot/src/**', 'native/hyprland-snap-shot/Cargo.lock', 'native/hyprland-snap-shot/Cargo.toml', 'native/hyprland-snap-shot/src/**', 'native/hyprland-snap-shot/protocols/**') }} + - name: Ensure Rosetta for macOS x64 bytecode generation + if: inputs.platform == 'mac' && inputs.arch == 'x64' + shell: bash + run: | + if [[ "$(uname -m)" == "arm64" ]] && ! /usr/bin/arch -x86_64 /usr/bin/true; then + sudo /usr/sbin/softwareupdate --install-rosetta --agree-to-license + fi + - name: Setup Rust if: steps.resource_monitor_cache.outputs.cache-hit != 'true' || (inputs.platform == 'linux' && steps.capture_helper_cache.outputs.cache-hit != 'true') uses: dtolnay/rust-toolchain@6bed0761d98439e5a578e2877258200ad565ba87 # stable diff --git a/AGENTS.md b/AGENTS.md index d99f1b5fa96a7..be566b9822055 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,6 +1,6 @@ # T3 Code -T3 Code is a minimal GUI for coding agents. A Node WebSocket server wraps provider CLIs and agents (Codex, Claude Code, Cursor, Grok, OpenCode, Antigravity) and serves web, desktop, and mobile clients. +T3 Code is a minimal GUI for coding agents. A Node WebSocket server wraps provider CLIs and agents (Codex, Claude Code, Cursor, Grok, OpenCode, Antigravity, Kiro) and serves web, desktop, and mobile clients. You can think of T3 Code as an open source "bring-your-own-subscription" alternative to apps like Claude Desktop, Codex App, Cursor Glass and Conductor. @@ -68,7 +68,7 @@ The most common defect in this repo is a change that works on the path you teste - **Entry points.** A behavior reachable from the chat view is usually also reachable from Settings, the command palette, and a keybinding. Fixing one is not fixing the feature. - **Clients.** Web, desktop (wraps web, adds Electron shell/IPC), and mobile (React Native, separate navigation). Shared logic lives in `packages/client-runtime` -- **Providers.** Codex, Claude, Cursor, Grok, OpenCode, and Antigravity each have an adapter. Provider-shaped features need a decision per adapter, even if the decision is "not supported here". +- **Providers.** Codex, Claude, Cursor, Grok, OpenCode, Antigravity, and Kiro each have an adapter. Provider-shaped features need a decision per adapter, even if the decision is "not supported here". - **Agents.** A capability a user can trigger is usually one an agent should reach through MCP tools, and scheduled tasks run the same paths. That only works when it is a service method, not handler code. - **Contracts.** Anything crossing the wire is typed in `packages/contracts`. Change the schema and the server, web, mobile, and desktop all follow. - **Reverse states.** If you added a way in, add the way out and the way to see it. Snooze needs unsnooze. Close needs reopen. A one-way door is a bug. diff --git a/apps/desktop/src/app/DesktopApp.test.ts b/apps/desktop/src/app/DesktopApp.test.ts new file mode 100644 index 0000000000000..66fc83adae194 --- /dev/null +++ b/apps/desktop/src/app/DesktopApp.test.ts @@ -0,0 +1,233 @@ +import { assert, it } from "@effect/vitest"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import * as HttpClient from "effect/http/HttpClient"; +import * as NetService from "@t3tools/shared/Net"; +import * as Fiber from "effect/Fiber"; +import * as Option from "effect/Option"; +import * as Ref from "effect/Ref"; +import * as Stream from "effect/Stream"; +import { vi } from "vite-plus/test"; + +vi.mock("electron", () => ({})); +vi.mock("@clerk/electron", () => ({ createClerkBridge: vi.fn() })); +vi.mock("@clerk/electron/storage", () => ({ storage: vi.fn() })); +vi.mock("../ipc/DesktopIpcHandlers.ts", () => ({ + installDesktopIpcHandlers: () => Effect.void, +})); +vi.mock("../updates/DesktopRemoteUpdates.ts", () => ({ listen: Effect.void })); +vi.mock("./DesktopStartupRecovery.ts", () => ({ listen: Effect.void })); + +import * as DesktopApp from "./DesktopApp.ts"; +import * as DesktopAppActivation from "./DesktopAppActivation.ts"; +import * as DesktopAppIdentity from "./DesktopAppIdentity.ts"; +import * as DesktopClerk from "./DesktopClerk.ts"; +import * as DesktopEnvironment from "./DesktopEnvironment.ts"; +import * as DesktopLegacyLocalStorage from "./DesktopLegacyLocalStorage.ts"; +import * as DesktopLifecycle from "./DesktopLifecycle.ts"; +import * as DesktopLinuxUrlHandler from "./DesktopLinuxUrlHandler.ts"; +import * as DesktopPreReadyPlatform from "./DesktopPreReadyPlatform.ts"; +import * as DesktopShutdown from "./DesktopShutdown.ts"; +import * as DesktopState from "./DesktopState.ts"; +import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts"; +import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts"; +import * as ElectronApp from "../electron/ElectronApp.ts"; +import * as ElectronDialog from "../electron/ElectronDialog.ts"; +import * as ElectronProtocol from "../electron/ElectronProtocol.ts"; +import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts"; +import * as PreviewPasskeys from "../preview/Passkeys.ts"; +import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts"; +import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts"; +import * as DesktopSnapShot from "../snapShot/DesktopSnapShot.ts"; +import * as DesktopRendererHistory from "../telemetry/DesktopRendererHistory.ts"; +import * as DesktopUpdates from "../updates/DesktopUpdates.ts"; +import * as DesktopApplicationMenu from "../window/DesktopApplicationMenu.ts"; +import * as DesktopWindow from "../window/DesktopWindow.ts"; +import * as DesktopWslBackend from "../wsl/DesktopWslBackend.ts"; + +import * as BrowserImport from "../preview/BrowserImport/BrowserImport.ts"; +import * as DesktopBackendConfiguration from "../backend/DesktopBackendConfiguration.ts"; +import * as DesktopCliCommand from "./DesktopCliCommand.ts"; +import * as DesktopClientSettings from "../settings/DesktopClientSettings.ts"; +import * as DesktopConnectionCatalogStore from "./DesktopConnectionCatalogStore.ts"; +import * as DesktopIpc from "../ipc/DesktopIpc.ts"; +import * as DesktopLocalEnvironmentAuth from "../backend/DesktopLocalEnvironmentAuth.ts"; +import * as DesktopManagedPolicy from "./DesktopManagedPolicy.ts"; +import * as DesktopSshEnvironment from "../ssh/DesktopSshEnvironment.ts"; +import * as DesktopSshPasswordPrompts from "../ssh/DesktopSshPasswordPrompts.ts"; +import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts"; +import * as DesktopWebLinks from "./DesktopWebLinks.ts"; +import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts"; +import * as ElectronMenu from "../electron/ElectronMenu.ts"; +import * as ElectronShell from "../electron/ElectronShell.ts"; +import * as ElectronTheme from "../electron/ElectronTheme.ts"; +import * as ElectronWindow from "../electron/ElectronWindow.ts"; +import * as MacPermissions from "../permissions/MacPermissions.ts"; +import * as PreviewManager from "../preview/Manager.ts"; + +it.effect( + "starts the backend and window while Linux registration is stalled and cancels it on shutdown", + () => + Effect.gen(function* () { + const registrationStarted = yield* Deferred.make(); + const releaseRegistration = yield* Deferred.make(); + const registrationStopped = yield* Deferred.make(); + const windowStarted = yield* Deferred.make(); + const quitting = yield* Ref.make(false); + const events: string[] = []; + const record = (event: string) => + Effect.sync(() => { + events.push(event); + }); + const runApp = DesktopApp.program + .pipe( + Effect.provide(NodeCrypto.layer), + Effect.provideService(DesktopAppIdentity.DesktopAppIdentity, { + resolveUserDataPath: Effect.succeed("/isolated/userdata"), + configure: record("identity"), + } as DesktopAppIdentity.DesktopAppIdentity["Service"]), + Effect.provideService(ElectronApp.ElectronApp, { + setPath: () => Effect.void, + whenReady: record("ready"), + } as unknown as ElectronApp.ElectronApp["Service"]), + Effect.provideService(ElectronDialog.ElectronDialog, { + showErrorBox: () => Effect.die("unexpected fatal startup error"), + } as unknown as ElectronDialog.ElectronDialog["Service"]), + Effect.provideService(DesktopEnvironment.DesktopEnvironment, { + platform: "linux", + isDevelopment: false, + isPackaged: true, + configuredBackendPort: Option.some(3773), + defaultDesktopSettings: { serverExposureMode: "local-only" }, + } as unknown as DesktopEnvironment.DesktopEnvironment["Service"]), + Effect.provideService(DesktopPreReadyPlatform.DesktopPreReadyElectronOptions, { + linux: null, + linuxPasswordStoreCommandLine: "basic", + }), + Effect.provideService(DesktopShellEnvironment.DesktopShellEnvironment, { + installIntoProcess: Effect.succeed(true), + awaitDiscovery: Effect.succeed(true), + updates: Stream.empty, + }), + Effect.provideService(DesktopAppSettings.DesktopAppSettings, { + load: Effect.void, + get: Effect.succeed({ + localEnvironmentEnabled: true, + serverExposureMode: "local-only", + }), + } as unknown as DesktopAppSettings.DesktopAppSettings["Service"]), + Effect.provideService(DesktopLifecycle.DesktopLifecycle, { + register: Effect.void, + relaunch: () => Effect.void, + }), + Effect.provideService(DesktopClerk.DesktopClerk, { + configure: Effect.void, + } as DesktopClerk.DesktopClerk["Service"]), + Effect.provideService(ElectronSafeStorage.ElectronSafeStorage, { + selectedStorageBackend: Effect.succeedNone, + } as unknown as ElectronSafeStorage.ElectronSafeStorage["Service"]), + Effect.provideService(PreviewPasskeys.PreviewPasskeys, { + configure: Effect.void, + } as PreviewPasskeys.PreviewPasskeys["Service"]), + Effect.provideService(DesktopApplicationMenu.DesktopApplicationMenu, { + configure: Effect.void, + }), + Effect.provideService(DesktopUpdates.DesktopUpdates, { + configure: Effect.void, + } as unknown as DesktopUpdates.DesktopUpdates["Service"]), + Effect.provideService(DesktopLinuxUrlHandler.DesktopLinuxUrlHandler, { + register: Deferred.succeed(registrationStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseRegistration)), + Effect.ensuring(Deferred.succeed(registrationStopped, undefined)), + ), + }), + ) + .pipe( + Effect.provideService(ElectronProtocol.ElectronProtocol, { + registerDesktopProtocol: () => Effect.void, + } as unknown as ElectronProtocol.ElectronProtocol["Service"]), + Effect.provideService(DesktopLegacyLocalStorage.DesktopLegacyLocalStorage, { + load: () => Effect.void, + } as unknown as DesktopLegacyLocalStorage.DesktopLegacyLocalStorage["Service"]), + Effect.provideService(DesktopSnapShot.DesktopSnapShot, { + initialize: Effect.void, + } as DesktopSnapShot.DesktopSnapShot["Service"]), + Effect.provideService(DesktopState.DesktopState, { + quitting, + } as DesktopState.DesktopState["Service"]), + Effect.provideService(DesktopWindow.DesktopWindow, { + ensureMain: record("window").pipe( + Effect.andThen(Deferred.succeed(windowStarted, undefined)), + ), + } as unknown as DesktopWindow.DesktopWindow["Service"]), + Effect.provideService(DesktopBackendPool.DesktopBackendPool, { + primary: Effect.succeed({ + start: record("backend"), + currentConfig: Effect.succeedSome({ preflightFailure: Option.none() }), + }), + list: Effect.succeed([]), + } as unknown as DesktopBackendPool.DesktopBackendPool["Service"]), + Effect.provideService(DesktopServerExposure.DesktopServerExposure, { + configureFromSettings: () => Effect.succeed({ mode: "local-only" }), + backendConfig: Effect.succeed({ httpBaseUrl: new URL("http://127.0.0.1:3773") }), + } as unknown as DesktopServerExposure.DesktopServerExposure["Service"]), + Effect.provideService(DesktopWslBackend.DesktopWslBackend, { + reconcile: Effect.void, + } as DesktopWslBackend.DesktopWslBackend["Service"]), + Effect.provideService(DesktopAppActivation.DesktopAppActivation, { + start: Effect.void, + } as unknown as DesktopAppActivation.DesktopAppActivation["Service"]), + Effect.provideService(DesktopRendererHistory.DesktopRendererHistory, { + shutdown: Effect.void, + } as DesktopRendererHistory.DesktopRendererHistory["Service"]), + ); + const app = yield* runApp.pipe( + Effect.provide( + Layer.mergeAll( + Layer.mock(BrowserImport.BrowserImport, {}), + Layer.mock(DesktopBackendConfiguration.DesktopBackendConfiguration, {}), + Layer.mock(DesktopCliCommand.DesktopCliCommand, {}), + Layer.mock(DesktopClientSettings.DesktopClientSettings, {}), + Layer.mock(DesktopConnectionCatalogStore.DesktopConnectionCatalogStore, {}), + Layer.mock(DesktopIpc.DesktopIpc, {}), + Layer.mock(DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth, {}), + Layer.mock(DesktopManagedPolicy.DesktopManagedPolicy, {}), + Layer.mock(DesktopSshEnvironment.DesktopSshEnvironment, {}), + Layer.mock(DesktopSshPasswordPrompts.DesktopSshPasswordPrompts, {}), + Layer.mock(DesktopTelemetryPublisher.DesktopTelemetryPublisher, {}), + Layer.mock(DesktopWebLinks.DesktopWebLinks, {}), + Layer.mock(DesktopWslEnvironment.DesktopWslEnvironment, {}), + Layer.mock(ElectronMenu.ElectronMenu, {}), + Layer.mock(ElectronShell.ElectronShell, {}), + Layer.mock(ElectronTheme.ElectronTheme, {}), + Layer.mock(ElectronWindow.ElectronWindow, {}), + Layer.mock(MacPermissions.MacPermissions, {}), + Layer.mock(PreviewManager.PreviewManager, { + isBrowserPartition: () => { + throw new Error("unexpected browser partition lookup"); + }, + }), + FileSystem.layerNoop({}), + Layer.mock(NetService.NetService, {}), + Path.layer, + Layer.succeed( + HttpClient.HttpClient, + HttpClient.make(() => Effect.die("unexpected HTTP request")), + ), + ), + ), + Effect.forkScoped, + ); + yield* Deferred.await(registrationStarted); + yield* Deferred.await(windowStarted); + assert.deepEqual(events, ["identity", "ready", "identity", "backend", "window"]); + assert.isFalse(yield* Deferred.isDone(registrationStopped)); + yield* (yield* DesktopShutdown.DesktopShutdown).request; + yield* Fiber.join(app); + assert.isTrue(yield* Deferred.isDone(registrationStopped)); + }).pipe(Effect.provide(DesktopShutdown.layer)), +); diff --git a/apps/desktop/src/app/DesktopApp.ts b/apps/desktop/src/app/DesktopApp.ts index 3442a54d60c4a..8bdd1957cbfb7 100644 --- a/apps/desktop/src/app/DesktopApp.ts +++ b/apps/desktop/src/app/DesktopApp.ts @@ -6,7 +6,7 @@ import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as NetService from "@t3tools/shared/Net"; -import * as Crypto from "effect/Crypto"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as ElectronApp from "../electron/ElectronApp.ts"; import * as ElectronDialog from "../electron/ElectronDialog.ts"; import * as ElectronProtocol from "../electron/ElectronProtocol.ts"; @@ -42,8 +42,8 @@ const DEFAULT_DESKTOP_BACKEND_PORT = 3773; const MAX_TCP_PORT = 65_535; const DESKTOP_BACKEND_PORT_PROBE_HOSTS = ["127.0.0.1", "0.0.0.0", "::"] as const; -const makeDesktopRunId = Crypto.Crypto.pipe( - Effect.flatMap((crypto) => crypto.randomUUIDv4()), +const makeDesktopRunId = SecureRandom.SecureRandom.pipe( + Effect.flatMap((random) => random.uuidV4()), Effect.map((value) => value.replaceAll("-", "").slice(0, 12)), ); @@ -337,7 +337,8 @@ const startup = Effect.gen(function* () { yield* updates.configure; yield* DesktopRemoteUpdates.listen; yield* DesktopStartupRecovery.listen; - yield* linuxUrlHandler.register; + // Portal identity is prepared pre-ready; MIME helpers must not gate the backend or window. + yield* linuxUrlHandler.register.pipe(Effect.forkScoped); yield* bootstrap.pipe(Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause))); }).pipe(Effect.withSpan("desktop.startup")); diff --git a/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts b/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts index 8b4fc23a99335..98c75385afc51 100644 --- a/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts +++ b/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts @@ -1,3 +1,4 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; import { ConnectionCatalogDocument } from "@t3tools/client-runtime/platform"; @@ -75,6 +76,7 @@ function layerFor( layerEnvironment, layerSafeStorage, NodeServices.layer, + NodeCrypto.layer, fileSystemLayer, ); const layerSavedEnvironments = DesktopSavedEnvironments.layer.pipe( diff --git a/apps/desktop/src/app/DesktopConnectionCatalogStore.ts b/apps/desktop/src/app/DesktopConnectionCatalogStore.ts index ceb3f293550bf..3240df3636e38 100644 --- a/apps/desktop/src/app/DesktopConnectionCatalogStore.ts +++ b/apps/desktop/src/app/DesktopConnectionCatalogStore.ts @@ -13,7 +13,7 @@ import { import type { PersistedSavedEnvironmentRecord } from "@t3tools/contracts"; import { fromLenientJson } from "@t3tools/shared/schemaJson"; import * as Context from "effect/Context"; -import * as Crypto from "effect/Crypto"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as Base64 from "effect/encoding/Base64"; import * as FileSystem from "effect/FileSystem"; @@ -381,7 +381,7 @@ export const make = Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage; - const crypto = yield* Crypto.Crypto; + const random = yield* SecureRandom.SecureRandom; const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments; const catalogPath = path.join(environment.stateDir, "connection-catalog.json"); const encryptionAvailable = safeStorage.isEncryptionAvailable.pipe( @@ -410,16 +410,7 @@ export const make = Effect.gen(function* () { ), ), ); - const suffix = (yield* crypto.randomUUIDv4().pipe( - Effect.mapError( - (cause) => - new DesktopConnectionCatalogStoreWriteError({ - operation: "create-temporary-file-name", - path: catalogPath, - cause, - }), - ), - )).replace(/-/g, ""); + const suffix = (yield* random.uuidV4()).replace(/-/g, ""); yield* writeDocument({ fileSystem, path, diff --git a/apps/desktop/src/app/DesktopLinuxUrlHandler.test.ts b/apps/desktop/src/app/DesktopLinuxUrlHandler.test.ts index f7b65dabea3f6..16d2f8e241d2f 100644 --- a/apps/desktop/src/app/DesktopLinuxUrlHandler.test.ts +++ b/apps/desktop/src/app/DesktopLinuxUrlHandler.test.ts @@ -381,7 +381,7 @@ describe("DesktopLinuxUrlHandler", () => { if (!ChildProcess.isStandardCommand(command)) { return yield* Effect.die("expected a single registration command"); } - recorded.commands.push({ command: command.command, args: command.args }); + recorded.commands.push({ command: command.command, args: command.args.map(String) }); if (command.command !== stalledHelper) return mockProcess(0); const child = yield* realSpawner.spawn( ChildProcess.make( diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts index b973f8177c9d0..aabc374798f24 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts @@ -1,3 +1,4 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; import { currentDesktopBootstrapToken } from "@t3tools/shared/desktopBootstrapToken"; @@ -76,6 +77,7 @@ function layerEnvironment( Layer.provide( Layer.mergeAll( NodeServices.layer, + NodeCrypto.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir, T3CODE_PORT: "9999", @@ -127,7 +129,7 @@ const withHarness = ( ), ), ); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))); interface PackagedWslHarnessContext { readonly baseDir: string; @@ -219,7 +221,7 @@ const withPackagedWslHarness = ( ), ), ); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))); describe("DesktopBackendConfiguration", () => { it.effect("resolvePrimary produces a stable scoped bootstrap token", () => @@ -316,7 +318,7 @@ describe("DesktopBackendConfiguration", () => { path.join(resourcesPath, "server.asar/apps/server/dist/bin.mjs"), ); assert.equal(config.env.ELECTRON_RUN_AS_NODE, "1"); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect("resolveWsl pins a default-tracking run to the concrete default distro", () => @@ -376,7 +378,7 @@ describe("DesktopBackendConfiguration", () => { assert.deepEqual(config.args.slice(0, 2), ["-d", "Ubuntu"]); assert.deepEqual(observedDistros, ["Ubuntu", "Ubuntu", "Ubuntu"]); assert.isTrue(Option.isNone(config.preflightFailure)); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect("resolveWsl launches a packaged backend from the WSL-local runtime cache", () => { @@ -665,7 +667,7 @@ describe("DesktopBackendConfiguration", () => { assert.notInclude(config.args, "/bin/sh"); assert.notInclude(config.args, "-c"); assert.isTrue(Option.isNone(config.preflightFailure)); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect("resolvePrimary and resolveWsl share one token under concurrent resolution", () => @@ -733,7 +735,7 @@ describe("DesktopBackendConfiguration", () => { restoreEnv("T3CODE_TELEMETRY_ENABLED", previousTelemetry); restoreEnv("OTEL_RESOURCE_ATTRIBUTES", previousResourceAttributes); } - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect("resolveWsl preserves existing WSLENV entries when forwarding backend secrets", () => @@ -800,7 +802,7 @@ describe("DesktopBackendConfiguration", () => { restoreEnv("T3CODE_OTLP_PROTOCOL", previousOtlpProtocol); for (const [name, value] of ambientOtel) restoreEnv(name, value); } - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect( @@ -837,7 +839,7 @@ describe("DesktopBackendConfiguration", () => { ), ), ); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect( @@ -880,7 +882,7 @@ describe("DesktopBackendConfiguration", () => { ), ), ); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect("resolveWsl marks a missing packaged server entry as fatal", () => @@ -913,7 +915,7 @@ describe("DesktopBackendConfiguration", () => { ), ), ); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect("prefers the external packaged resource monitor over the copy inside the asar", () => @@ -962,7 +964,7 @@ describe("DesktopBackendConfiguration", () => { ), ), ); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it("resolvePrimaryLabel is runSync-safe against the real WSL availability probe", async () => { @@ -983,7 +985,7 @@ describe("DesktopBackendConfiguration", () => { ), ), Layer.provideMerge(layerEnvironment("/tmp/t3-wsl-isavailable", { platform: "win32" })), - Layer.provide(NodeServices.layer), + Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), ), ); try { diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.ts index 9c8186711f6ec..69a70b68a4b3d 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts @@ -4,7 +4,7 @@ import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serve import { currentDesktopBootstrapToken } from "@t3tools/shared/desktopBootstrapToken"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; -import * as Crypto from "effect/Crypto"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as Hex from "effect/encoding/Hex"; import * as FileSystem from "effect/FileSystem"; @@ -723,14 +723,14 @@ export const make = Effect.gen(function* () { const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment; const wslServerTree = yield* DesktopWslServerTree.DesktopWslServerTree; const settings = yield* DesktopAppSettings.DesktopAppSettings; - const crypto = yield* Crypto.Crypto; + const random = yield* SecureRandom.SecureRandom; // Random generation yields; serialize it so concurrent backends cannot capture distinct bootstrap secrets. const secretRef = yield* SynchronizedRef.make(Option.none()); const getOrCreateBootstrapSecret = SynchronizedRef.modifyEffect(secretRef, (current) => Option.match(current, { onSome: (secret) => Effect.succeed([secret, current] as const), onNone: () => - crypto.randomBytes(32).pipe( + random.randomBytes(32).pipe( Effect.map((bytes) => { const secret = Hex.encode(bytes); return [secret, Option.some(secret)] as const; diff --git a/apps/desktop/src/backend/DesktopServerExposure.test.ts b/apps/desktop/src/backend/DesktopServerExposure.test.ts index 23732860e05cd..c222237dffa7b 100644 --- a/apps/desktop/src/backend/DesktopServerExposure.test.ts +++ b/apps/desktop/src/backend/DesktopServerExposure.test.ts @@ -1,5 +1,6 @@ import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem"; import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; import * as Deferred from "effect/Deferred"; @@ -81,7 +82,11 @@ function layerEnvironmentFor(baseDir: string, env: Record( }), ), ); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped); + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), Effect.scoped); describe("DesktopServerExposure", () => { it.effect("uses cached Tailscale identity to exclude another VPN's pairing address", () => { diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index 2fcb8d968c5a4..d109518be15e4 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -7,6 +7,7 @@ for (const stream of [process.stdout, process.stderr]) { import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient"; import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; // @effect-diagnostics-next-line nodeBuiltinImport:off - Version output must flush before Electron exits, without acquiring the runtime. import * as NodeFS from "node:fs"; @@ -230,12 +231,12 @@ const layerDesktopClerk = DesktopClerk.layer.pipe( Layer.provide(DesktopPreReadyFileSystem.layer), Layer.provideMerge(ElectronShell.layer), Layer.provideMerge(layerDesktopEnvironment), - Layer.provideMerge(NodeServices.layer), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), Layer.provideMerge(ElectronApp.layer), ); const layerDesktopApplicationRuntime = layerDesktopApplication.pipe( - Layer.provideMerge(NodeServices.layer), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), Layer.provideMerge(NodeHttpClient.layerUndici), Layer.provideMerge(NetService.layer), Layer.provideMerge(layerElectron), diff --git a/apps/desktop/src/preview/BrowserSession.test.ts b/apps/desktop/src/preview/BrowserSession.test.ts index 6ee471c211324..7a339102f19a6 100644 --- a/apps/desktop/src/preview/BrowserSession.test.ts +++ b/apps/desktop/src/preview/BrowserSession.test.ts @@ -1,4 +1,5 @@ import { assert, describe, it } from "@effect/vitest"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -46,7 +47,7 @@ const layerDialog = Layer.succeed(ElectronDialog.ElectronDialog, { showErrorBox: () => Effect.void, }); const layer = BrowserSession.layer.pipe( - Layer.provide(Layer.merge(NodeServices.layer, layerDialog)), + Layer.provide(Layer.merge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer), layerDialog)), ); describe("BrowserSession", () => { diff --git a/apps/desktop/src/preview/BrowserSession.ts b/apps/desktop/src/preview/BrowserSession.ts index a427708a37080..a780cacf11ea9 100644 --- a/apps/desktop/src/preview/BrowserSession.ts +++ b/apps/desktop/src/preview/BrowserSession.ts @@ -1,7 +1,7 @@ import type { Session, WebContents } from "electron"; import { BrowserWindow, session } from "electron"; import * as Context from "effect/Context"; -import * as Crypto from "effect/Crypto"; +import * as Digest from "effect/crypto/Digest"; import * as Effect from "effect/Effect"; import * as Hex from "effect/encoding/Hex"; import * as Layer from "effect/Layer"; @@ -186,7 +186,7 @@ const previewHostWindow = (guest: WebContents | null): BrowserWindow | undefined /** @public */ export const make = Effect.gen(function* BrowserSessionMake() { - const crypto = yield* Crypto.Crypto; + const crypto = yield* Digest.Digest; const electronDialog = yield* ElectronDialog.ElectronDialog; const runFork = Effect.runForkWith(yield* Effect.context()); // One prompt at a time, so a page cannot stack dialogs by looping a deep link. @@ -261,7 +261,7 @@ export const make = Effect.gen(function* BrowserSessionMake() { persistent = true, namespace?: BrowserSessionPartitionNamespace, ) { - const digest = yield* crypto.digest("SHA-256", encodeScopeForDigest(scope)).pipe( + const digest = yield* crypto.digest(Digest.sha256, encodeScopeForDigest(scope)).pipe( Effect.mapError( (cause) => new BrowserSessionPartitionDerivationError({ diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.ts index db4a0950364b3..6f4378da6f032 100644 --- a/apps/desktop/src/preview/Manager.ts +++ b/apps/desktop/src/preview/Manager.ts @@ -38,7 +38,7 @@ import { import * as Cause from "effect/Cause"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; -import * as Crypto from "effect/Crypto"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; @@ -526,7 +526,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function const rendererHistory = yield* DesktopRendererHistory.DesktopRendererHistory; const hostPlatform = yield* HostProcess.Platform; const path = yield* Path.Path; - const crypto = yield* Crypto.Crypto; + const random = yield* SecureRandom.SecureRandom; const parentScope = yield* Scope.Scope; const browserHost = yield* DesktopBrowserHost.DesktopBrowserHost; const passkeys = yield* PreviewPasskeys.PreviewPasskeys; @@ -2393,7 +2393,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function wc, ), ]); - const uuid = yield* crypto.randomUUIDv4().pipe(Effect.orDie); + const uuid = yield* random.uuidV4(); const id = `browser-screenshot-${artifactSiteSlug(wc.getURL())}-${millis.toString(36)}-${uuid.slice(0, 8)}`; const artifactPath = path.join(resolvedArtifactDirectory, `${id}.png`); const data = image.toPNG(); diff --git a/apps/desktop/src/settings/DesktopAppSettings.test.ts b/apps/desktop/src/settings/DesktopAppSettings.test.ts index 0135225f90c48..ab3e2e4cd0755 100644 --- a/apps/desktop/src/settings/DesktopAppSettings.test.ts +++ b/apps/desktop/src/settings/DesktopAppSettings.test.ts @@ -1,3 +1,4 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; @@ -52,7 +53,11 @@ function layerEnvironment(baseDir: string, appVersion = "0.0.17") { runningUnderArm64Translation: false, }).pipe( Layer.provide( - Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir })), + Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + DesktopConfig.layerTest({ T3CODE_HOME: baseDir }), + ), ), ); } @@ -74,11 +79,11 @@ const withSettings = ( Effect.provide( DesktopAppSettings.layer.pipe( Layer.provideMerge(layerEnvironment(baseDir, options?.appVersion)), - Layer.provideMerge(NodeServices.layer), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), ), ), ); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped); + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), Effect.scoped); function writeSettingsPatch(patch: typeof DesktopSettingsPatch.Type) { return Effect.gen(function* () { diff --git a/apps/desktop/src/settings/DesktopAppSettings.ts b/apps/desktop/src/settings/DesktopAppSettings.ts index a0624ced669ea..aa16502a16585 100644 --- a/apps/desktop/src/settings/DesktopAppSettings.ts +++ b/apps/desktop/src/settings/DesktopAppSettings.ts @@ -7,7 +7,7 @@ import { import { fromLenientJson } from "@t3tools/shared/schemaJson"; import { resolveSymlinkTarget } from "@t3tools/shared/symlink"; import * as Context from "effect/Context"; -import * as Crypto from "effect/Crypto"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -469,7 +469,7 @@ export const make = Effect.gen(function* () { const environment = yield* DesktopEnvironment.DesktopEnvironment; const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; - const crypto = yield* Crypto.Crypto; + const random = yield* SecureRandom.SecureRandom; const settingsRef = yield* SynchronizedRef.make(environment.defaultDesktopSettings); const updateInMemory = (update: (settings: DesktopSettings) => DesktopSettings) => @@ -487,16 +487,8 @@ export const make = Effect.gen(function* () { return Effect.succeed([settingsChange(settings, false), settings] as const); } - return crypto.randomUUIDv4().pipe( + return random.uuidV4().pipe( Effect.map((uuid) => uuid.replace(/-/g, "")), - Effect.mapError( - (cause) => - new DesktopSettingsWriteError({ - operation: "create-temporary-file-name", - path: environment.desktopSettingsPath, - cause, - }), - ), Effect.flatMap((suffix) => writeSettings({ fileSystem, diff --git a/apps/desktop/src/settings/DesktopClientSettings.test.ts b/apps/desktop/src/settings/DesktopClientSettings.test.ts index ec5062f9105bf..2d89754ac1150 100644 --- a/apps/desktop/src/settings/DesktopClientSettings.test.ts +++ b/apps/desktop/src/settings/DesktopClientSettings.test.ts @@ -1,3 +1,4 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; import { @@ -89,13 +90,17 @@ function layer(baseDir: string) { runningUnderArm64Translation: false, }).pipe( Layer.provide( - Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir })), + Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + DesktopConfig.layerTest({ T3CODE_HOME: baseDir }), + ), ), ); return DesktopClientSettings.layer.pipe( Layer.provideMerge(layerEnvironment), - Layer.provideMerge(NodeServices.layer), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), ); } @@ -108,7 +113,7 @@ const withClientSettings = ( prefix: "t3-desktop-client-settings-test-", }); return yield* effect.pipe(Effect.provide(layer(baseDir))); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped); + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), Effect.scoped); describe("DesktopClientSettings", () => { it.effect("saves through a symlinked client settings file without replacing the link", () => diff --git a/apps/desktop/src/settings/DesktopClientSettings.ts b/apps/desktop/src/settings/DesktopClientSettings.ts index 0836db6678226..52b619494626f 100644 --- a/apps/desktop/src/settings/DesktopClientSettings.ts +++ b/apps/desktop/src/settings/DesktopClientSettings.ts @@ -2,7 +2,7 @@ import { ClientSettingsSchema, type ClientSettings } from "@t3tools/contracts"; import { fromLenientJson } from "@t3tools/shared/schemaJson"; import { resolveSymlinkTarget } from "@t3tools/shared/symlink"; import * as Context from "effect/Context"; -import * as Crypto from "effect/Crypto"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -188,23 +188,15 @@ export const make = Effect.gen(function* () { const environment = yield* DesktopEnvironment.DesktopEnvironment; const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; - const crypto = yield* Crypto.Crypto; + const random = yield* SecureRandom.SecureRandom; return DesktopClientSettings.of({ get: readClientSettings(fileSystem, environment.clientSettingsPath).pipe( Effect.withSpan("desktop.clientSettings.get"), ), set: Effect.fn("desktop.clientSettings.set")(function (settings) { - return crypto.randomUUIDv4().pipe( + return random.uuidV4().pipe( Effect.map((uuid) => uuid.replace(/-/g, "")), - Effect.mapError( - (cause) => - new DesktopClientSettingsWriteError({ - operation: "create-temporary-file-name", - path: environment.clientSettingsPath, - cause, - }), - ), Effect.flatMap((suffix) => writeClientSettings({ fileSystem, diff --git a/apps/desktop/src/snapShot/DesktopSnapShot.test.ts b/apps/desktop/src/snapShot/DesktopSnapShot.test.ts index 84fcb4cbf8277..721f130ef5e56 100644 --- a/apps/desktop/src/snapShot/DesktopSnapShot.test.ts +++ b/apps/desktop/src/snapShot/DesktopSnapShot.test.ts @@ -6,7 +6,7 @@ import { type ClientSettings, type DesktopSnapShotEvent, } from "@t3tools/contracts"; -import * as Crypto from "effect/Crypto"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; @@ -519,11 +519,8 @@ const layerTest = ( FileSystem.layerNoop(fileSystemOverrides), Path.layer, Layer.succeed( - Crypto.Crypto, - Crypto.make({ - randomBytes: (size) => new Uint8Array(size), - digest: (_algorithm, data) => Effect.succeed(data), - }), + SecureRandom.SecureRandom, + SecureRandom.make((size) => new Uint8Array(size)), ), ), ), @@ -675,11 +672,8 @@ function concurrentCaptureFixture(platform: NodeJS.Platform, animations: boolean readFileString: (path) => Effect.sync(() => metadata.get(path)!), }), Layer.succeed( - Crypto.Crypto, - Crypto.make({ - randomBytes: (size) => new Uint8Array(size).fill(++randomByte), - digest: (_algorithm, data) => Effect.succeed(data), - }), + SecureRandom.SecureRandom, + SecureRandom.make((size) => new Uint8Array(size).fill(++randomByte)), ), Layer.succeed( DesktopWindow.DesktopWindow, diff --git a/apps/desktop/src/snapShot/DesktopSnapShot.ts b/apps/desktop/src/snapShot/DesktopSnapShot.ts index 9dfcdc2f35a8f..a3d4db0bb4dc2 100644 --- a/apps/desktop/src/snapShot/DesktopSnapShot.ts +++ b/apps/desktop/src/snapShot/DesktopSnapShot.ts @@ -23,7 +23,7 @@ import { } from "@t3tools/contracts"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; -import * as Crypto from "effect/Crypto"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Base64 from "effect/encoding/Base64"; @@ -750,7 +750,7 @@ export const make = Effect.gen(function* () { const desktopWindow = yield* DesktopWindow.DesktopWindow; const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; - const crypto = yield* Crypto.Crypto; + const random = yield* SecureRandom.SecureRandom; const settingsRef = yield* Ref.make(DEFAULT_CLIENT_SETTINGS); const stateRef = yield* Ref.make({ mode: captureMode(environment.platform), @@ -896,7 +896,7 @@ export const make = Effect.gen(function* () { const prepareCapture = Effect.fn("desktop.snapShot.prepareCapture")(function* ( settings: ClientSettings, ) { - const id = yield* crypto.randomUUIDv4().pipe(Effect.mapError((cause) => captureFailure(cause))); + const id = yield* random.uuidV4().pipe(Effect.mapError((cause) => captureFailure(cause))); const mode = captureMode(environment.platform); if (mode === "unavailable") { return yield* new DesktopSnapShotError({ operation: "unsupported", captureId: id }); diff --git a/apps/desktop/src/ssh/DesktopSshEnvironment.ts b/apps/desktop/src/ssh/DesktopSshEnvironment.ts index f6c9ee43d7580..3a3e84e03a9b7 100644 --- a/apps/desktop/src/ssh/DesktopSshEnvironment.ts +++ b/apps/desktop/src/ssh/DesktopSshEnvironment.ts @@ -18,7 +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 type * as Digest from "effect/crypto/Digest"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -30,7 +30,7 @@ import * as DesktopSshPasswordPrompts from "./DesktopSshPasswordPrompts.ts"; export type DesktopSshEnvironmentRuntimeServices = | ChildProcessSpawner.ChildProcessSpawner - | Crypto.Crypto + | Digest.Digest | FileSystem.FileSystem | Path.Path | HttpClient.HttpClient diff --git a/apps/desktop/src/ssh/DesktopSshPasswordPrompts.test.ts b/apps/desktop/src/ssh/DesktopSshPasswordPrompts.test.ts index b86cc275df230..c0f8210f18146 100644 --- a/apps/desktop/src/ssh/DesktopSshPasswordPrompts.test.ts +++ b/apps/desktop/src/ssh/DesktopSshPasswordPrompts.test.ts @@ -1,4 +1,5 @@ import { assert, describe, it } from "@effect/vitest"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; @@ -107,7 +108,7 @@ function layerElectronWindow(window: ReturnType["window"] function layer(window: ReturnType["window"]) { return DesktopSshPasswordPrompts.layer({ passwordPromptTimeoutMs: 1_000 }).pipe( Layer.provide(layerElectronWindow(window)), - Layer.provide(NodeServices.layer), + Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), Layer.provideMerge(TestClock.layer()), ); } diff --git a/apps/desktop/src/ssh/DesktopSshPasswordPrompts.ts b/apps/desktop/src/ssh/DesktopSshPasswordPrompts.ts index 7442282aa15ad..3c16b938331ca 100644 --- a/apps/desktop/src/ssh/DesktopSshPasswordPrompts.ts +++ b/apps/desktop/src/ssh/DesktopSshPasswordPrompts.ts @@ -2,7 +2,7 @@ import type { DesktopSshPasswordPromptRequest } from "@t3tools/contracts"; import { DesktopSshPasswordPromptResolutionInputSchema } from "@t3tools/contracts"; import type { SshPasswordRequest } from "@t3tools/ssh/auth"; import * as Context from "effect/Context"; -import * as Crypto from "effect/Crypto"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; @@ -223,7 +223,7 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* ( options: DesktopSshPasswordPromptsOptions = {}, ) { const electronWindow = yield* ElectronWindow.ElectronWindow; - const crypto = yield* Crypto.Crypto; + const random = yield* SecureRandom.SecureRandom; const pendingRef = yield* Ref.make(new Map()); const passwordPromptTimeoutMs = options.passwordPromptTimeoutMs ?? DEFAULT_SSH_PASSWORD_PROMPT_TIMEOUT_MS; @@ -307,7 +307,7 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* ( }); } - const requestId = yield* crypto.randomUUIDv4().pipe( + const requestId = yield* random.uuidV4().pipe( Effect.mapError( (cause) => new DesktopSshPromptRequestIdGenerationError({ diff --git a/apps/desktop/src/updates/updatesTestHarness.ts b/apps/desktop/src/updates/updatesTestHarness.ts index ec3b1ce9a1d59..226f00f8cba89 100644 --- a/apps/desktop/src/updates/updatesTestHarness.ts +++ b/apps/desktop/src/updates/updatesTestHarness.ts @@ -1,3 +1,4 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import type { DesktopUpdateState } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; @@ -288,7 +289,7 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) { }), ), Layer.provideMerge(layerEnvironment), - Layer.provideMerge(NodeServices.layer), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), ); return { diff --git a/apps/marketing/src/lib/site.ts b/apps/marketing/src/lib/site.ts index 5cd1337d141f4..c4cc8aca59f22 100644 --- a/apps/marketing/src/lib/site.ts +++ b/apps/marketing/src/lib/site.ts @@ -6,7 +6,25 @@ export const IOS_APP_STORE_URL = export const ANDROID_PLAY_STORE_URL = "https://play.google.com/store/apps/details?id=com.t3tools.t3code"; +// Runs at build time, so each deploy picks up the current count. +async function fetchGithubStars(): Promise { + const token = process.env.GITHUB_TOKEN; + try { + const response = await fetch("https://api.github.com/repos/pingdotgg/t3code", { + headers: token ? { Authorization: `Bearer ${token}` } : {}, + }); + if (!response.ok) throw new Error(`GitHub API responded ${response.status}`); + const { stargazers_count: stars } = (await response.json()) as { stargazers_count: number }; + return stars < 1000 ? String(stars) : `${Math.floor(stars / 1000)}k+`; + } catch (error) { + // A deploy must not ship a made-up count; offline dev should still render. + if (import.meta.env.PROD) throw new Error("Could not fetch GitHub stars", { cause: error }); + console.warn("Could not fetch GitHub stars", error); + return "?"; + } +} + export const MARKETING_STATS = { - githubStars: "31k+", + githubStars: await fetchGithubStars(), users: "500,000", } as const; diff --git a/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorModule.kt b/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorModule.kt index e86f45b634392..ed0e989614467 100644 --- a/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorModule.kt +++ b/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorModule.kt @@ -62,7 +62,6 @@ internal object T3ComposerClipboard { } class T3ComposerEditorModule : Module() { - // A flat list of the view's props and events. @Suppress("LongMethod") override fun definition() = ModuleDefinition { Name("T3ComposerEditor") diff --git a/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorView.kt b/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorView.kt index e76f221d8980e..9d7e52c8946fb 100644 --- a/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorView.kt +++ b/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorView.kt @@ -20,10 +20,12 @@ import android.util.TypedValue import android.view.DragEvent import android.view.Gravity import android.view.GestureDetector +import android.view.InputDevice import android.view.KeyCharacterMap import android.view.MotionEvent import android.view.KeyEvent import android.view.ViewGroup +import android.view.inputmethod.BaseInputConnection import android.view.inputmethod.EditorInfo import android.view.inputmethod.InputConnection import android.view.inputmethod.InputConnectionWrapper @@ -599,16 +601,11 @@ internal class SelectionAwareEditText( var pasteContextListener: ((Map) -> Unit)? = null var pasteTextListener: ((String, Int, Int) -> Unit)? = null - /** Called for a hardware-keyboard send chord. The argument is true for the alternate send. */ var submitListener: ((Boolean) -> Unit)? = null var textPasteThresholdBytes = 0 var maxInputChars = Int.MAX_VALUE var clipboardFragment = "" - - /** Whether a hardware Return sends (`enterBehavior` "send") or inserts a newline. */ var returnSends = true - - /** The JS wrapper enables submission only when it has an onSubmit handler. */ var submitEnabled = false /** @@ -661,20 +658,15 @@ internal class SelectionAwareEditText( return spans.isNotEmpty() } - /** - * Maps a hardware Return chord to a send, like the iOS composer. The plainer chord does the - * configured behavior and the Ctrl chord does the other one: with "send", Return sends, - * Ctrl-Return sends the alternate way and Shift-Return inserts a newline; with "newline", - * Ctrl-Return sends and Ctrl-Shift-Return sends the alternate way. Returns whether the send is - * the alternate one, or null to insert a newline. Soft keyboards always insert a newline. - */ + // Match iPad submission chords with Ctrl in place of Command; null leaves normal editing. private fun submitChord(keyCode: Int, event: KeyEvent): Boolean? { val isReturn = keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER val fromSoftKeyboard = event.deviceId == KeyCharacterMap.VIRTUAL_KEYBOARD || (event.flags and KeyEvent.FLAG_SOFT_KEYBOARD) != 0 - val canSubmit = submitEnabled && submitListener != null && !readOnly - if (!isReturn || fromSoftKeyboard || !canSubmit) { + val canSubmit = isEnabled && !readOnly && submitEnabled && submitListener != null + val composing = BaseInputConnection.getComposingSpanStart(text) >= 0 + if (!isReturn || fromSoftKeyboard || !canSubmit || composing) { return null } return when { @@ -710,6 +702,23 @@ internal class SelectionAwareEditText( override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection? { val connection = super.onCreateInputConnection(outAttrs) ?: return null return object : InputConnectionWrapper(connection, false) { + // IMEs can also forward physical keys with their original device ID. + override fun sendKeyEvent(event: KeyEvent): Boolean { + val device = InputDevice.getDevice(event.deviceId) + val fromHardwareKeyboard = device != null && !device.isVirtual && + device.keyboardType == InputDevice.KEYBOARD_TYPE_ALPHABETIC + return super.sendKeyEvent( + if (fromHardwareKeyboard) { + event + } else { + KeyEvent.changeFlags( + event, + event.flags or KeyEvent.FLAG_SOFT_KEYBOARD + ) + } + ) + } + override fun deleteSurroundingText( beforeLength: Int, afterLength: Int diff --git a/apps/mobile/modules/t3-composer-editor/android/src/test/java/expo/modules/t3composereditor/ComposerPasteTest.kt b/apps/mobile/modules/t3-composer-editor/android/src/test/java/expo/modules/t3composereditor/ComposerEditorTest.kt similarity index 63% rename from apps/mobile/modules/t3-composer-editor/android/src/test/java/expo/modules/t3composereditor/ComposerPasteTest.kt rename to apps/mobile/modules/t3-composer-editor/android/src/test/java/expo/modules/t3composereditor/ComposerEditorTest.kt index 441154f3e1b97..81189a99e974e 100644 --- a/apps/mobile/modules/t3-composer-editor/android/src/test/java/expo/modules/t3composereditor/ComposerPasteTest.kt +++ b/apps/mobile/modules/t3-composer-editor/android/src/test/java/expo/modules/t3composereditor/ComposerEditorTest.kt @@ -1,18 +1,26 @@ package expo.modules.t3composereditor import android.app.Activity -import android.content.ContentProvider -import android.content.ContentValues -import android.database.Cursor import android.content.ClipData import android.content.ClipDescription import android.content.ClipboardManager +import android.content.ContentProvider +import android.content.ContentValues import android.content.Context import android.content.pm.ProviderInfo +import android.database.Cursor +import android.hardware.input.InputManager import android.net.Uri +import android.os.Looper +import android.os.SystemClock +import android.text.InputType import android.view.DragEvent -import android.view.View +import android.view.InputDevice +import android.view.KeyCharacterMap import android.view.KeyEvent +import android.view.View +import android.view.inputmethod.BaseInputConnection +import android.view.inputmethod.EditorInfo import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNull @@ -20,15 +28,17 @@ import org.junit.Assert.assertTrue import org.junit.Test import org.junit.runner.RunWith import org.robolectric.Robolectric -import org.robolectric.shadows.DragEventBuilder -import org.robolectric.shadows.ShadowContentResolver import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf import org.robolectric.annotation.Config +import org.robolectric.shadows.DragEventBuilder +import org.robolectric.shadows.InputDeviceBuilder +import org.robolectric.shadows.ShadowContentResolver @RunWith(RobolectricTestRunner::class) @Config(sdk = [36], manifest = Config.NONE) -class ComposerPasteTest { +class ComposerEditorTest { private val context = RuntimeEnvironment.getApplication() private val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager private val editor = SelectionAwareEditText(context).apply { @@ -198,7 +208,7 @@ class ComposerPasteTest { private fun imageClip(vararg names: String): ClipData { val provider = DropImageProvider().apply { - attachInfo(this@ComposerPasteTest.context, ProviderInfo().apply { authority = "images" }) + attachInfo(this@ComposerEditorTest.context, ProviderInfo().apply { authority = "images" }) } ShadowContentResolver.registerProviderInternal("images", provider) return ClipData( @@ -315,4 +325,173 @@ class ComposerPasteTest { selectionArgs: Array? ) = 0 } + + private fun submissionEditor(sends: MutableList) = + SelectionAwareEditText(context).apply { + inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_MULTI_LINE + setText("draft") + setSelection(length()) + submitEnabled = true + submitListener = { sends += it } + } + + private fun SelectionAwareEditText.pressReturn( + modifiers: Int = 0, + repeats: Int = 0, + deviceId: Int = 1, + flags: Int = 0 + ) { + val down = KeyEvent( + 0, 0, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER, + 0, modifiers, deviceId, 0, flags, + ) + dispatchKeyEvent(down) + repeat(repeats) { dispatchKeyEvent(KeyEvent.changeTimeRepeat(down, 0, it + 1)) } + dispatchKeyEvent(KeyEvent.changeAction(down, KeyEvent.ACTION_UP)) + } + + @Test + fun hardwareReturnSendsOnceWithAnAlternateAndANewlineChord() { + val sends = mutableListOf() + val editor = submissionEditor(sends) + + editor.pressReturn(repeats = 2) + editor.pressReturn(KeyEvent.META_CTRL_ON or KeyEvent.META_CTRL_LEFT_ON) + editor.pressReturn(KeyEvent.META_SHIFT_ON or KeyEvent.META_SHIFT_LEFT_ON) + + assertEquals(listOf(false, true), sends) + assertEquals("draft\n", editor.text.toString()) + } + + @Test + fun hardwareReturnWaitsUntilCompositionEndsToSubmit() { + val sends = mutableListOf() + val editor = submissionEditor(sends) + BaseInputConnection.setComposingSpans(editor.text) + assertTrue(BaseInputConnection.getComposingSpanStart(editor.text) >= 0) + + editor.pressReturn() + assertEquals(emptyList(), sends) + + BaseInputConnection.removeComposingSpans(editor.text) + assertEquals(-1, BaseInputConnection.getComposingSpanStart(editor.text)) + + editor.pressReturn() + assertEquals(listOf(false), sends) + } + + @Test + fun newlineSettingKeepsReturnForEditingAndCtrlForSubmission() { + val sends = mutableListOf() + val editor = submissionEditor(sends).apply { returnSends = false } + + editor.pressReturn() + assertEquals(emptyList(), sends) + assertEquals("draft\n", editor.text.toString()) + + editor.pressReturn(KeyEvent.META_CTRL_ON) + editor.pressReturn(KeyEvent.META_CTRL_ON or KeyEvent.META_SHIFT_ON) + assertEquals(listOf(false, true), sends) + assertEquals("draft\n", editor.text.toString()) + } + + @Test + fun imeReturnKeepsSoftEditsAndForwardedHardwareChords() { + val sends = mutableListOf() + val editor = submissionEditor(sends) + + editor.pressReturn(deviceId = KeyCharacterMap.VIRTUAL_KEYBOARD) + editor.pressReturn(flags = KeyEvent.FLAG_SOFT_KEYBOARD) + + assertEquals(emptyList(), sends) + assertEquals("draft\n\n", editor.text.toString()) + + Robolectric.buildActivity(Activity::class.java).use { controller -> + controller.setup().get().setContentView(editor) + editor.requestFocus() + controller.windowFocusChanged(true) + val connection = checkNotNull(editor.onCreateInputConnection(EditorInfo())) + + fun forwardReturn(deviceId: Int, modifiers: Int = 0) { + val now = SystemClock.uptimeMillis() + val down = KeyEvent( + now, now, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER, 0, modifiers, deviceId, 0, 0, + ) + connection.sendKeyEvent(down) + connection.sendKeyEvent(KeyEvent.changeAction(down, KeyEvent.ACTION_UP)) + shadowOf(Looper.getMainLooper()).idle() + } + + assertNull(InputDevice.getDevice(1)) + for (returnSends in listOf(false, true)) { + editor.returnSends = returnSends + editor.setText("draft") + editor.setSelection(editor.length()) + forwardReturn(deviceId = 1) + + assertEquals( + "IME Return must not submit (returnSends=$returnSends)", + emptyList(), + sends, + ) + assertEquals("draft\n", editor.text.toString()) + } + + val keyboard = InputDeviceBuilder.newBuilder() + .setId(42) + .setName("Physical keyboard") + .setExternal(true) + .setSources(InputDevice.SOURCE_KEYBOARD) + .setKeyboardType(InputDevice.KEYBOARD_TYPE_ALPHABETIC) + .build() + shadowOf(context.getSystemService(InputManager::class.java)).addInputDevice(keyboard) + val registered = checkNotNull(InputDevice.getDevice(keyboard.id)) + assertFalse(registered.isVirtual) + assertEquals(InputDevice.KEYBOARD_TYPE_ALPHABETIC, registered.keyboardType) + + for (returnSends in listOf(false, true)) { + editor.returnSends = returnSends + editor.setText("draft") + editor.setSelection(editor.length()) + sends.clear() + + forwardReturn(keyboard.id) + assertEquals(if (returnSends) listOf(false) else emptyList(), sends) + val expectedText = if (returnSends) "draft" else "draft\n" + assertEquals(expectedText, editor.text.toString()) + + forwardReturn(keyboard.id, KeyEvent.META_CTRL_ON) + if (!returnSends) { + forwardReturn(keyboard.id, KeyEvent.META_CTRL_ON or KeyEvent.META_SHIFT_ON) + } + assertEquals( + "Forwarded hardware Return chords must submit (returnSends=$returnSends)", + listOf(false, true), + sends, + ) + assertEquals(expectedText, editor.text.toString()) + } + } + } + + @Test + fun unavailableSubmissionFallsThroughToEditing() { + val sends = mutableListOf() + val editor = submissionEditor(sends).apply { submitEnabled = false } + + editor.pressReturn() + assertEquals(emptyList(), sends) + assertEquals("draft\n", editor.text.toString()) + + editor.submitEnabled = true + editor.submitListener = null + editor.pressReturn() + assertEquals(emptyList(), sends) + assertEquals("draft\n\n", editor.text.toString()) + + editor.submitListener = { sends += it } + editor.readOnly = true + editor.pressReturn() + assertEquals(emptyList(), sends) + } } diff --git a/apps/mobile/modules/t3-composer-editor/android/src/test/java/expo/modules/t3composereditor/ComposerSubmitTest.kt b/apps/mobile/modules/t3-composer-editor/android/src/test/java/expo/modules/t3composereditor/ComposerSubmitTest.kt deleted file mode 100644 index 3745a70269638..0000000000000 --- a/apps/mobile/modules/t3-composer-editor/android/src/test/java/expo/modules/t3composereditor/ComposerSubmitTest.kt +++ /dev/null @@ -1,104 +0,0 @@ -package expo.modules.t3composereditor - -import android.text.InputType -import android.view.KeyCharacterMap -import android.view.KeyEvent -import org.junit.Assert.assertEquals -import org.junit.Test -import org.junit.runner.RunWith -import org.robolectric.RobolectricTestRunner -import org.robolectric.RuntimeEnvironment -import org.robolectric.annotation.Config - -@RunWith(RobolectricTestRunner::class) -@Config(sdk = [36], manifest = Config.NONE) -class ComposerSubmitTest { - private val sends = mutableListOf() - private val editor = SelectionAwareEditText(RuntimeEnvironment.getApplication()).apply { - inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_MULTI_LINE - submitEnabled = true - submitListener = { alternate -> sends += alternate } - } - - private fun pressReturn( - metaState: Int = 0, - deviceId: Int = HARDWARE_KEYBOARD, - repeatCount: Int = 0 - ) { - val event = KeyEvent( - 0, - 0, - KeyEvent.ACTION_DOWN, - KeyEvent.KEYCODE_ENTER, - repeatCount, - metaState, - deviceId, - 0, - ) - editor.onKeyDown(KeyEvent.KEYCODE_ENTER, event) - } - - @Test - fun returnSendsAndCtrlReturnSendsTheAlternateWay() { - pressReturn() - pressReturn(KeyEvent.META_CTRL_ON or KeyEvent.META_CTRL_LEFT_ON) - - assertEquals(listOf(false, true), sends) - assertEquals("", editor.text.toString()) - } - - @Test - fun shiftReturnAndSoftKeyboardReturnInsertNewlines() { - pressReturn(KeyEvent.META_SHIFT_ON or KeyEvent.META_SHIFT_LEFT_ON) - pressReturn(deviceId = KeyCharacterMap.VIRTUAL_KEYBOARD) - - assertEquals(emptyList(), sends) - assertEquals("\n\n", editor.text.toString()) - } - - @Test - fun newlineBehaviorSendsOnlyWithCtrl() { - editor.returnSends = false - - pressReturn() - pressReturn(KeyEvent.META_CTRL_ON) - pressReturn(KeyEvent.META_CTRL_ON or KeyEvent.META_SHIFT_ON) - - assertEquals(listOf(false, true), sends) - assertEquals("\n", editor.text.toString()) - } - - @Test - fun returnInsertsANewlineWhenSubmissionIsUnavailable() { - editor.submitEnabled = false - - pressReturn() - - assertEquals(emptyList(), sends) - assertEquals("\n", editor.text.toString()) - } - - @Test - fun returnInsertsANewlineWithoutASubmitListener() { - editor.submitListener = null - - pressReturn() - - assertEquals(emptyList(), sends) - assertEquals("\n", editor.text.toString()) - } - - @Test - fun heldReturnSendsOnce() { - pressReturn() - pressReturn(repeatCount = 1) - pressReturn(repeatCount = 2) - - assertEquals(listOf(false), sends) - assertEquals("", editor.text.toString()) - } - - private companion object { - const val HARDWARE_KEYBOARD = 1 - } -} diff --git a/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3KeyboardCommandsModule.kt b/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3KeyboardCommandsModule.kt index ac1f2348beb7b..58d193b8e4376 100644 --- a/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3KeyboardCommandsModule.kt +++ b/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3KeyboardCommandsModule.kt @@ -9,7 +9,6 @@ import expo.modules.kotlin.modules.ModuleDefinition import expo.modules.kotlin.viewevent.EventDispatcher import expo.modules.kotlin.views.ExpoView -// Android's tablet breakpoint. Large screens get the iPad-only commands. private const val LARGE_SCREEN_MIN_WIDTH_DP = 600 class T3KeyboardCommandsModule : Module() { @@ -33,9 +32,7 @@ class T3KeyboardCommandsView( var enabledCommands = emptySet() init { - // A key reaches dispatchKeyEvent only while focus is inside this view. With nothing focused, - // Android offers it to unhandled-key listeners instead. That listener needs API 28, so on - // API 24-27 shortcuts work only while something inside this view has focus. + // Without a focused descendant, shortcuts reach only the API 28+ unhandled-key listener. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { addOnUnhandledKeyEventListener { _, event -> val command = enabledCommandFor(event) @@ -82,11 +79,6 @@ private val CTRL_SHIFT_COMMANDS = mapOf( KeyEvent.KEYCODE_H to "cycleHost", ) -/** - * The command for a hardware-keyboard chord. Matches the iOS module with Ctrl in place of - * Command. Like iPad, large screens get the command palette and thread jumps; on phones Ctrl-K - * focuses search. - */ private fun hardwareKeyboardCommand(event: KeyEvent, largeScreen: Boolean): String? { val keyCode = event.keyCode return when { diff --git a/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalView.kt b/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalView.kt index 71ccc6eebe418..bd99b79f4f8c9 100644 --- a/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalView.kt +++ b/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalView.kt @@ -278,14 +278,22 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex inputView.setOnKeyListener { _, keyCode, event -> if (readOnly) return@setOnKeyListener true if (event.action != KeyEvent.ACTION_DOWN) return@setOnKeyListener false + val controlByte = when (keyCode) { + in KeyEvent.KEYCODE_A..KeyEvent.KEYCODE_Z -> keyCode - KeyEvent.KEYCODE_A + 1 + KeyEvent.KEYCODE_LEFT_BRACKET -> 0x1B + KeyEvent.KEYCODE_BACKSLASH -> 0x1C + KeyEvent.KEYCODE_RIGHT_BRACKET -> 0x1D + else -> null + } when { keyCode == KeyEvent.KEYCODE_DEL -> { onInput(mapOf("data" to "\u007F")) true } - event.isCtrlPressed && keyCode in KeyEvent.KEYCODE_A..KeyEvent.KEYCODE_Z -> { + // The terminal owns control chords before the app's navigation shortcuts. + event.isCtrlPressed && controlByte != null -> { onInput( - mapOf("data" to (keyCode - KeyEvent.KEYCODE_A + 1).toChar().toString()), + mapOf("data" to controlByte.toChar().toString()), ) true } diff --git a/apps/mobile/plugins/withAndroidTabletOrientation.cjs b/apps/mobile/plugins/withAndroidTabletOrientation.cjs index 81e37a728f14a..81a184cc9ed82 100644 --- a/apps/mobile/plugins/withAndroidTabletOrientation.cjs +++ b/apps/mobile/plugins/withAndroidTabletOrientation.cjs @@ -22,65 +22,56 @@ const ORIENTATION_METHODS = ` } `; -const ORIENTATION_ON_CREATE_CALL = `applyTabletOrientation() - `; +const ORIENTATION_ON_CREATE_CALL = ` + applyTabletOrientation()`; -function findAnchor(contents, anchor, description) { +function insertAfter(contents, anchor, insertion, description) { const index = contents.indexOf(anchor); if (index === -1) { throw new Error( `withAndroidTabletOrientation: could not find ${description} in MainActivity — the Expo template changed; update the plugin anchors.`, ); } - return index; -} - -function insertBefore(contents, anchor, insertion, description) { - const index = findAnchor(contents, anchor, description); - return contents.slice(0, index) + insertion + contents.slice(index); -} - -function insertAfter(contents, anchor, insertion, description) { - const end = findAnchor(contents, anchor, description) + anchor.length; + const end = index + anchor.length; return contents.slice(0, end) + insertion + contents.slice(end); } -function withUnlockedManifestOrientation(config) { - return withAndroidManifest(config, (nextConfig) => { +module.exports = function withAndroidTabletOrientation(config) { + config = withAndroidManifest(config, (nextConfig) => { const mainActivity = AndroidConfig.Manifest.getMainActivityOrThrow(nextConfig.modResults); delete mainActivity.$["android:screenOrientation"]; return nextConfig; }); -} - -module.exports = function withAndroidTabletOrientation(config) { - config = withUnlockedManifestOrientation(config); return withMainActivity(config, (nextConfig) => { let contents = nextConfig.modResults.contents; if (nextConfig.modResults.language !== "kt") { throw new Error("withAndroidTabletOrientation: MainActivity must be Kotlin."); } - if (contents.includes("SCREEN_ORIENTATION_FULL_USER")) { - return nextConfig; + if (!contents.includes("SCREEN_ORIENTATION_FULL_USER")) { + contents = insertAfter( + contents, + "import android.os.Bundle", + "\nimport android.content.pm.ActivityInfo\nimport android.content.res.Configuration", + "the android.os.Bundle import", + ); + contents = insertAfter( + contents, + "class MainActivity : ReactActivity() {", + ORIENTATION_METHODS, + "the MainActivity class declaration", + ); } - contents = insertAfter( - contents, - "import android.os.Bundle", - "\nimport android.content.pm.ActivityInfo\nimport android.content.res.Configuration", - "the android.os.Bundle import", + // Relocate the call in existing native projects too, before splash setup and React content. + contents = contents.replace( + /override fun onCreate\(savedInstanceState: Bundle\?\) \{[\s\S]*?\n \}/, + (onCreate) => onCreate.replace(/\n[ \t]*applyTabletOrientation\(\)/g, ""), ); contents = insertAfter( contents, - "class MainActivity : ReactActivity() {", - ORIENTATION_METHODS, - "the MainActivity class declaration", - ); - contents = insertBefore( - contents, - "super.onCreate(null)", + "override fun onCreate(savedInstanceState: Bundle?) {", ORIENTATION_ON_CREATE_CALL, - "the super.onCreate call", + "the onCreate declaration", ); nextConfig.modResults.contents = contents; diff --git a/apps/mobile/plugins/withAndroidTabletOrientation.test.ts b/apps/mobile/plugins/withAndroidTabletOrientation.test.ts index a2eab6b1db35a..9b381a86f347a 100644 --- a/apps/mobile/plugins/withAndroidTabletOrientation.test.ts +++ b/apps/mobile/plugins/withAndroidTabletOrientation.test.ts @@ -1,5 +1,8 @@ -import { AndroidConfig, XML, type ExportedConfig } from "expo/config-plugins"; -import { describe, expect, it } from "vite-plus/test"; +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; +import { AndroidConfig, compileModsAsync, XML } from "expo/config-plugins"; +import { afterEach, describe, expect, it } from "vite-plus/test"; import withAndroidTabletOrientation from "./withAndroidTabletOrientation.cjs"; @@ -32,91 +35,61 @@ class MainActivity : ReactActivity() { } `; -function modRequest(modName: string) { - return { - platform: "android" as const, - modName, - projectRoot: "/project", - platformProjectRoot: "/project/android", - introspect: false, - }; -} +const projectRoots: string[] = []; + +afterEach(() => { + for (const root of projectRoots.splice(0)) NodeFS.rmSync(root, { recursive: true, force: true }); +}); + +async function prebuildAndroid(input = { manifest: MANIFEST, mainActivity: MAIN_ACTIVITY }) { + const projectRoot = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "tablet-orientation-")); + projectRoots.push(projectRoot); + const sourceRoot = NodePath.join(projectRoot, "android/app/src/main"); + const activityPath = NodePath.join(sourceRoot, "java/com/t3tools/t3code/MainActivity.kt"); + const manifestPath = NodePath.join(sourceRoot, "AndroidManifest.xml"); + NodeFS.mkdirSync(NodePath.dirname(activityPath), { recursive: true }); + NodeFS.writeFileSync(manifestPath, input.manifest); + NodeFS.writeFileSync(activityPath, input.mainActivity); -// Registers Expo's built-in orientation plugin after this one, as prebuild does -// for every app plugin. Same-type mods run last-registered-first, so the -// manifest mod sees the lock that `orientation: "portrait"` writes. -function prebuildConfig(): ExportedConfig { const config = withAndroidTabletOrientation({ name: "T3 Code", slug: "t3code", orientation: "portrait", }); - return AndroidConfig.Orientation.withOrientation(config); -} - -async function runManifestMod(config: ExportedConfig) { - const result = await config.mods!.android!.manifest!({ - ...config, - modResults: (await XML.parseXMLAsync(MANIFEST)) as AndroidConfig.Manifest.AndroidManifest, - modRequest: modRequest("manifest"), - modRawConfig: config, - }); - return AndroidConfig.Manifest.getMainActivityOrThrow(result.modResults); -} - -async function runMainActivityMod(config: ExportedConfig, contents: string) { - const result = await config.mods!.android!.mainActivity!({ - ...config, - modResults: { contents, language: "kt", path: "/project/MainActivity.kt" }, - modRequest: modRequest("mainActivity"), - modRawConfig: config, + // Prebuild registers Expo's orientation mod after app plugins. Mods run in + // reverse order, so our plugin must remove the portrait lock Expo writes. + await compileModsAsync(AndroidConfig.Orientation.withOrientation(config), { + projectRoot, + platforms: ["android"], }); - return result.modResults.contents; -} - -function count(haystack: string, needle: string) { - return haystack.split(needle).length - 1; + return { + manifest: NodeFS.readFileSync(manifestPath, "utf8"), + mainActivity: NodeFS.readFileSync(activityPath, "utf8"), + }; } describe("withAndroidTabletOrientation", () => { - it("leaves MainActivity without a manifest orientation lock", async () => { - const mainActivity = await runManifestMod(prebuildConfig()); + it("generates an unlocked launcher manifest while preserving rotation and fold handling", async () => { + const { manifest } = await prebuildAndroid(); + const mainActivity = AndroidConfig.Manifest.getMainActivityOrThrow( + (await XML.parseXMLAsync(manifest)) as AndroidConfig.Manifest.AndroidManifest, + ); expect(mainActivity.$["android:screenOrientation"]).toBeUndefined(); - // Rotation and fold/unfold must keep reaching onConfigurationChanged - // instead of recreating the activity. expect(mainActivity.$["android:configChanges"]?.split("|")).toEqual( expect.arrayContaining(["orientation", "screenSize", "smallestScreenSize"]), ); }); - it("requests the orientation before super.onCreate", async () => { - const contents = await runMainActivityMod(prebuildConfig(), MAIN_ACTIVITY); + it("generates the phone/tablet policy before activity creation and stays stable on repeated prebuild", async () => { + const once = await prebuildAndroid(); - const onCreate = contents.slice(contents.indexOf("override fun onCreate")); - expect(onCreate.indexOf("applyTabletOrientation()")).toBeLessThan( - onCreate.indexOf("super.onCreate(null)"), + expect(once.mainActivity).toMatch( + /override fun onCreate\(savedInstanceState: Bundle\?\)\s*\{[^}]*applyTabletOrientation\(\)[^}]*super\.onCreate\(null\)/, ); - expect(contents).toContain(" applyTabletOrientation()\n super.onCreate(null)"); - expect(count(contents, "import android.content.pm.ActivityInfo")).toBe(1); - expect(count(contents, "import android.content.res.Configuration")).toBe(1); - expect(count(contents, "override fun onConfigurationChanged")).toBe(1); - expect(count(contents, "private fun applyTabletOrientation")).toBe(1); - }); - - it("leaves an already patched MainActivity unchanged", async () => { - const once = await runMainActivityMod(prebuildConfig(), MAIN_ACTIVITY); - const twice = await runMainActivityMod(prebuildConfig(), once); - - expect(twice).toBe(once); - }); - - it("fails loudly when the template no longer calls super.onCreate(null)", async () => { - await expect( - runMainActivityMod( - prebuildConfig(), - MAIN_ACTIVITY.replace("super.onCreate(null)", "super.onCreate(savedInstanceState)"), - ), - ).rejects.toThrow("could not find the super.onCreate call"); + expect(once.mainActivity).toMatch( + /private fun applyTabletOrientation\(\)\s*\{\s*requestedOrientation = if \(resources\.configuration\.smallestScreenWidthDp >= 600\)\s*\{\s*ActivityInfo\.SCREEN_ORIENTATION_FULL_USER\s*\} else \{\s*ActivityInfo\.SCREEN_ORIENTATION_PORTRAIT\s*\}/, + ); + expect(await prebuildAndroid(once)).toEqual(once); }); }); diff --git a/apps/mobile/scripts/fixtures/NotificationCenterManagerRegression.swift b/apps/mobile/scripts/fixtures/NotificationCenterManagerRegression.swift index b5caad2e996cf..f6ee08fddd6bf 100644 --- a/apps/mobile/scripts/fixtures/NotificationCenterManagerRegression.swift +++ b/apps/mobile/scripts/fixtures/NotificationCenterManagerRegression.swift @@ -186,14 +186,16 @@ private func partiallyHandledReplay() throws { let manager = NotificationCenterManager.shared deliver("handled") deliver("unhandled") - let original = TestDelegate() - original.onResponse = { $0.identifier == "handled" } - manager.addDelegate(original) + let selective = TestDelegate() + selective.onResponse = { $0.identifier == "handled" } + manager.addDelegate(selective) + try require(selective.events == ["handled", "unhandled"], "Replay must offer every pending response to the delegate") + manager.removeDelegate(selective) + let receiver = TestDelegate() receiver.onResponse = { _ in true } manager.addDelegate(receiver) - try require(receiver.events == ["unhandled"], "Replay must retain each response that the delegate did not handle") - manager.removeDelegate(original) + try require(receiver.events == ["unhandled"], "Replay must retain only responses the previous delegate did not handle") manager.removeDelegate(receiver) } diff --git a/apps/mobile/scripts/measure-renders.mts b/apps/mobile/scripts/measure-renders.mts index 2e517f1f7bbd0..f49938fff8601 100644 --- a/apps/mobile/scripts/measure-renders.mts +++ b/apps/mobile/scripts/measure-renders.mts @@ -1,8 +1,9 @@ // See docs/internals/mobile-development.md#measuring-renders. import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient"; import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; -import * as NodeSocket from "@effect/platform-node/NodeSocket"; +import * as NodeWS from "@effect/platform-node/NodeWS"; import { CommandId, EnvironmentId, @@ -17,7 +18,7 @@ import { type OrchestrationV2ThreadProjection, } from "@t3tools/contracts"; import * as Console from "effect/Console"; -import * as Crypto from "effect/Crypto"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -71,7 +72,7 @@ interface Options { readonly projectRoot: string; } -const uuid = Effect.flatMap(Crypto.Crypto, (crypto) => crypto.randomUUIDv4()); +const uuid = Effect.flatMap(SecureRandom.SecureRandom, (random) => random.uuidV4()); const median = (values: ReadonlyArray) => { const sorted = [...values].sort((a, b) => a - b); @@ -398,8 +399,9 @@ Command.run(command, { version: "0.0.0" }).pipe( Effect.provide( Layer.mergeAll( NodeServices.layer, + NodeCrypto.layer, NodeHttpClient.layerUndici, - NodeSocket.layerWebSocketConstructorWS, + NodeWS.layerWebSocketConstructor, ), ), NodeRuntime.runMain, diff --git a/apps/mobile/src/components/ScrollComposeButton.android.tsx b/apps/mobile/src/components/ScrollComposeButton.android.tsx index d107d9be5d8a0..13aeb462bdf5f 100644 --- a/apps/mobile/src/components/ScrollComposeButton.android.tsx +++ b/apps/mobile/src/components/ScrollComposeButton.android.tsx @@ -17,12 +17,14 @@ import { resolveScaledTextRole } from "../lib/appearancePreferences"; export function ScrollComposeButton(props: { readonly expanded: boolean; readonly onPress: () => void; + readonly size?: number; readonly className?: string; readonly style?: StyleProp; }) { const { appearance, themeVariables: colors } = useAppearancePreferences(); const typography = resolveScaledTextRole("footnote", appearance.baseFontSize); - const { iconSize, fabSize } = useAndroidControlSizing(); + const { iconSize, fabSize: scaledFabSize } = useAndroidControlSizing(); + const fabSize = props.size ?? scaledFabSize; const nativeSize = Math.max(56, fabSize); const scale = fabSize / nativeSize; const nativeIconSize = Math.round(iconSize / scale); diff --git a/apps/mobile/src/components/ui/Button.tsx b/apps/mobile/src/components/ui/Button.tsx index 05c6e0085245f..bb187f66713d3 100644 --- a/apps/mobile/src/components/ui/Button.tsx +++ b/apps/mobile/src/components/ui/Button.tsx @@ -14,6 +14,7 @@ export interface ButtonProps { readonly loading?: boolean; readonly tone?: "primary" | "secondary" | "danger" | "text" | "contrast"; readonly fullWidth?: boolean; + readonly size?: "default" | "compact"; } const TONE_CLASS_NAMES = { @@ -36,7 +37,8 @@ export function Button(props: ButtonProps) { disabled={disabled} onPress={props.onPress} className={cn( - "min-h-12 flex-row items-center justify-center gap-2 rounded-full px-6 active:opacity-70", + "flex-row items-center justify-center gap-2 rounded-full active:opacity-70", + props.size === "compact" ? "min-h-10 px-5" : "min-h-12 px-6", props.fullWidth ? "w-full" : "self-start", disabled ? "bg-subtle-strong" : containerClassName, )} diff --git a/apps/mobile/src/components/ui/Toast.tsx b/apps/mobile/src/components/ui/Toast.tsx index 2483ac9fa1285..49efbdf5203d8 100644 --- a/apps/mobile/src/components/ui/Toast.tsx +++ b/apps/mobile/src/components/ui/Toast.tsx @@ -1,3 +1,4 @@ +import { cn } from "../../lib/cn"; import { MOBILE_MOTION, MOBILE_SHAPE } from "../../lib/designTokens"; import { useCallback, useEffect, useLayoutEffect, useState } from "react"; import { AccessibilityInfo, Platform, StyleSheet, View, useWindowDimensions } from "react-native"; @@ -45,7 +46,7 @@ export function Toast(props: ToastProps) { function ToastContent(props: ToastProps & { readonly glassReady?: boolean }) { const { fontScale } = useWindowDimensions(); const { colorScheme } = useControlTheme(); - const borderRadius = Platform.OS === "ios" ? 31 : MOBILE_SHAPE.toast; + const borderRadius = Platform.OS === "ios" ? 28 : MOBILE_SHAPE.toast; // Explicit single-line notices reserve the action's width and truncate the text. const inlineAction = props.singleLine || (!props.description && fontScale < 1.5); const message = @@ -53,7 +54,11 @@ function ToastContent(props: ToastProps & { readonly glassReady?: boolean }) { ? `${props.message}: ${props.description}` : props.message; const action = props.action ? ( - )} - +
{item.type === "video" ? ( diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index e32a7eb485fc6..4c7eba620b5d1 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -1528,60 +1528,6 @@ describe("deriveMessagesTimelineRows", () => { expect(rows.at(-1)).toMatchObject({ kind: "thinking" }); }); - it("keeps the latest finished reply's timestamp while a command is still running", () => { - const reply = (streaming: boolean) => ({ - id: "assistant-reply-entry", - kind: "message" as const, - createdAt: "2026-01-01T00:00:10Z", - message: { - id: "assistant-reply" as never, - role: "assistant" as const, - text: "Training finished, checking memory next.", - runId: "turn-1" as never, - createdAt: "2026-01-01T00:00:10Z", - updatedAt: "2026-01-01T00:00:12Z", - streaming, - }, - }); - const rowsWith = (streaming: boolean) => - deriveMessagesTimelineRows({ - timelineEntries: [ - reply(streaming), - { - id: "command-entry", - kind: "work", - createdAt: "2026-01-01T00:00:15Z", - entry: { - id: "command", - createdAt: "2026-01-01T00:00:15Z", - runId: "turn-1" as never, - label: "Running command", - command: "nvidia-smi", - tone: "tool" as const, - toolLifecycleStatus: "inProgress" as const, - }, - }, - ], - latestRun: { - runId: "turn-1" as never, - status: "running", - startedAt: "2026-01-01T00:00:00Z", - completedAt: null, - }, - isWorking: true, - activeTurnStartedAt: "2026-01-01T00:00:00Z", - turnDiffSummaries: [], - supportsConversationRollback: false, - }).find((row) => row.id === "assistant-reply-entry"); - - expect(rowsWith(false)).toMatchObject({ - showAssistantMeta: false, - showAssistantTimestamp: true, - showAssistantCopyButton: false, - }); - expect(rowsWith(true)).toMatchObject({ showAssistantTimestamp: false }); - }); - it("does not show Thinking once the open run's provider turn has ended", () => { const input = { timelineEntries: [ diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index 5f4f850908e41..60c70548b9149 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -592,8 +592,6 @@ type MessagesTimelineRowContent = message: ChatMessage; projectedItem?: OrchestrationV2ProjectedTurnItem; showAssistantMeta: boolean; - /** The latest finished reply of a still-running response shows only its timestamp. */ - showAssistantTimestamp: boolean; showAssistantCopyButton: boolean; assistantCopyStreaming: boolean; assistantTurnDiffSummary?: TurnDiffSummary | undefined; @@ -2039,10 +2037,10 @@ export function deriveMessagesTimelineRows(input: { timelineEntry.message.role === "assistant" && runIdIsActiveResponse(timelineEntry.message.runId); - const isTerminalAssistantMessage = + const showAssistantMeta = timelineEntry.message.role === "assistant" && - terminalAssistantMessageIds.has(timelineEntry.message.id); - const showAssistantMeta = isTerminalAssistantMessage && !assistantResponseStillInProgress; + terminalAssistantMessageIds.has(timelineEntry.message.id) && + !assistantResponseStillInProgress; nextRows.push({ kind: "message", @@ -2053,10 +2051,6 @@ export function deriveMessagesTimelineRows(input: { ? {} : { projectedItem: timelineEntry.projectedItem }), showAssistantMeta, - showAssistantTimestamp: - isTerminalAssistantMessage && - assistantResponseStillInProgress && - !timelineEntry.message.streaming, showAssistantCopyButton: showAssistantMeta, assistantCopyStreaming: timelineEntry.message.streaming || assistantResponseStillInProgress, assistantTurnDiffSummary: @@ -2520,7 +2514,6 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean a.message === bm.message && a.projectedItem === bm.projectedItem && a.showAssistantMeta === bm.showAssistantMeta && - a.showAssistantTimestamp === bm.showAssistantTimestamp && a.showAssistantCopyButton === bm.showAssistantCopyButton && a.assistantCopyStreaming === bm.assistantCopyStreaming && a.assistantTurnDiffSummary === bm.assistantTurnDiffSummary && diff --git a/apps/web/src/components/chat/TimelineAssistantRows.tsx b/apps/web/src/components/chat/TimelineAssistantRows.tsx index b425e1009d1b1..458d84b9e982b 100644 --- a/apps/web/src/components/chat/TimelineAssistantRows.tsx +++ b/apps/web/src/components/chat/TimelineAssistantRows.tsx @@ -76,13 +76,6 @@ export function AssistantTimelineRow({ row }: { row: Extract - ) : row.showAssistantTimestamp ? ( - ) : null}
diff --git a/apps/web/src/components/chat/timelineMinimapItems.test.ts b/apps/web/src/components/chat/timelineMinimapItems.test.ts index a72813d8f755b..776cd39096a8a 100644 --- a/apps/web/src/components/chat/timelineMinimapItems.test.ts +++ b/apps/web/src/components/chat/timelineMinimapItems.test.ts @@ -15,7 +15,6 @@ describe("deriveTimelineMinimapItems", () => { id: "image-only", createdAt: at, showAssistantMeta: false, - showAssistantTimestamp: false, showAssistantCopyButton: false, assistantCopyStreaming: false, message: { diff --git a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx index 98b34fbc00f89..5356066d0524b 100644 --- a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx +++ b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx @@ -2522,6 +2522,7 @@ it("keeps workspace PDF scroll and zoom after reloads", async () => { const { preview, urls } = fixture; await using screen = await render(preview(urls.original, "one")); await expect.element(screen.getByText("1 / 3 pages", { exact: true })).toBeVisible(); + using workers = vi.spyOn(window, "Worker"); await screen.getByRole("button", { name: "Next page", exact: true }).click(); await vi.waitFor(() => expect(screen.container.textContent).toContain("2 / 3 pages")); await screen.getByRole("button", { name: "Next page", exact: true }).click(); @@ -2576,6 +2577,7 @@ it("keeps workspace PDF scroll and zoom after reloads", async () => { expect(region().scrollTop).toBe(0); expect(region().scrollLeft).toBe(0); }); + expect(workers).not.toHaveBeenCalled(); }); it("clamps workspace PDF scroll when pages shrink or disappear", async () => { diff --git a/apps/web/src/components/files/HtmlArtifactFrame.tsx b/apps/web/src/components/files/HtmlArtifactFrame.tsx index d2995cf6873dc..0bb48ade3a519 100644 --- a/apps/web/src/components/files/HtmlArtifactFrame.tsx +++ b/apps/web/src/components/files/HtmlArtifactFrame.tsx @@ -11,7 +11,7 @@ export function HtmlArtifactFrame(props: { title: string; html: string }) { const theme = useHtmlRenderTheme(); const frame = useRef(null); const [srcDoc] = useState(() => htmlArtifactDocument(props.html, theme)); - // oxlint-disable-next-line t3code/react-effect-budget -- Synchronize theme values into the opaque frame without accepting requests from it. + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Synchronize theme values into the opaque frame without accepting requests from it. useEffect(() => { frame.current?.contentWindow?.postMessage(htmlRenderThemeMessage(theme), "*"); }, [theme]); diff --git a/apps/web/src/components/files/fileSaveSessions.browser.test.tsx b/apps/web/src/components/files/fileSaveSessions.browser.test.tsx index aff76479b7410..70456e2d92bb7 100644 --- a/apps/web/src/components/files/fileSaveSessions.browser.test.tsx +++ b/apps/web/src/components/files/fileSaveSessions.browser.test.tsx @@ -1,5 +1,5 @@ import { render, fakeTimers } from "../../../test/render"; -import { EnvironmentId } from "@t3tools/contracts"; +import { type AuthSessionState, EnvironmentId } from "@t3tools/contracts"; import { AsyncResult } from "effect/reactivity"; import { StrictMode } from "react"; import { describe, expect, it, vi } from "vite-plus/test"; @@ -12,10 +12,18 @@ vi.mock(import("@t3tools/client-runtime/state/runtime"), async (original) => ({ ...(await original()), runAtomCommand: runAtomCommand as never, })); -vi.mock(import("~/state/session"), async (original) => ({ - ...(await original()), - readEnvironmentScope: () => true, -})); +// The real session atom boots the connection runtime, whose endless discovery poll +// would keep vi.runAllTimersAsync from ever draining once its timers are faked. +vi.mock(import("~/state/session"), async (original) => { + const actual = await original(); + const reactivity = await import("effect/reactivity"); + const signedOut = reactivity.Atom.make(reactivity.AsyncResult.initial()); + return { + ...actual, + environmentSession: { ...actual.environmentSession, sessionStateAtom: () => signedOut }, + readEnvironmentScope: () => true, + }; +}); vi.mock(import("./projectFilesQueryState"), async (original) => ({ ...(await original()), confirmProjectFileQueryData: () => true, diff --git a/apps/web/src/components/files/pdfDocument.ts b/apps/web/src/components/files/pdfDocument.ts index 2cc5493718b4c..32e8aefbe9028 100644 --- a/apps/web/src/components/files/pdfDocument.ts +++ b/apps/web/src/components/files/pdfDocument.ts @@ -1,4 +1,4 @@ -import { getDocument, GlobalWorkerOptions } from "pdfjs-dist"; +import { getDocument, GlobalWorkerOptions, PDFWorker } from "pdfjs-dist"; import workerUrl from "pdfjs-dist/build/pdf.worker.min.mjs?url"; import fallbackUrl from "pdfjs-dist/wasm/openjpeg_nowasm_fallback.js?url"; @@ -31,8 +31,13 @@ export class BinaryDataFactory { } } +// Without a shared worker, pdf.js starts a worker and recompiles its 1.3 MB script for every document. +let worker: PDFWorker | undefined; + export function openPdf(bytes: ArrayBuffer) { + worker ??= new PDFWorker(); return getDocument({ + worker, data: new Uint8Array(bytes), useSystemFonts: true, useWorkerFetch: false, diff --git a/apps/web/src/components/home/HomeFleetHost.tsx b/apps/web/src/components/home/HomeFleetHost.tsx index abc3a6a5fee1f..f320f18c70ca8 100644 --- a/apps/web/src/components/home/HomeFleetHost.tsx +++ b/apps/web/src/components/home/HomeFleetHost.tsx @@ -44,7 +44,7 @@ function HomeHub({ environmentId }: { readonly environmentId: EnvironmentId }) { const settings = useAtomValue(serverEnvironment.settingsValueAtom(environmentId)); const home = settings?.home ?? DEFAULT_HOME_SETTINGS; const on = home.threadId !== null; - // oxlint-disable-next-line t3code/react-effect-budget -- keeps the desktop shell alive while this relay is mounted + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- keeps the desktop shell alive while this relay is mounted useEffect(() => { void window.desktopBridge?.setKeepAliveOnClose?.(on); // Without a relay running, closing the window should quit as usual. @@ -157,7 +157,7 @@ function HomeRelay({ // The consumer outlives renders, so it reads the latest handler from an atom. const [handlerAtom] = useState(() => Atom.make({ handle })); const setHandler = useAtomSet(handlerAtom); - // oxlint-disable-next-line t3code/react-effect-budget -- the long-lived consumer reads the latest handler, which must not be written during render + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- the long-lived consumer reads the latest handler, which must not be written during render useEffect(() => { setHandler({ handle }); }, [handle, setHandler]); @@ -202,7 +202,7 @@ function HomeWatchReporter({ const sending = useRef(false); const stopped = useRef(false); - // oxlint-disable-next-line t3code/react-effect-budget -- reports watched-thread changes to the server, a side effect of new shells + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reports watched-thread changes to the server, a side effect of new shells useEffect(() => { const { next, events } = diffWatchedThreads({ previous: previous.current, @@ -240,7 +240,7 @@ function HomeWatchReporter({ timer.current = setTimeout(() => void send(), WATCH_REPORT_DELAY_MS); }, [environmentId, home, knownWatchKeys, labels, liveEnvironmentIds, report, shells]); - // oxlint-disable-next-line t3code/react-effect-budget -- cancels the pending report timer on unmount + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- cancels the pending report timer on unmount useEffect(() => { stopped.current = false; return () => { diff --git a/apps/web/src/components/media/MediaActions.tsx b/apps/web/src/components/media/MediaActions.tsx index f45ba1e7abc78..72c003f717a69 100644 --- a/apps/web/src/components/media/MediaActions.tsx +++ b/apps/web/src/components/media/MediaActions.tsx @@ -113,9 +113,11 @@ export function useMediaActions(source: MediaActionSource) { export function MediaActions({ source, children, + showTooltip = true, }: { source: MediaActionSource; children: ReactElement; + showTooltip?: boolean; }) { const { save, copyImage, canReadMedia, assertCanReadMedia } = useMediaActions(source); const [tooltipOpen, setTooltipOpen] = useState(false); @@ -204,7 +206,7 @@ export function MediaActions({ }; return ( - + ; + readonly loadedFiles: ReadonlyArray["files"][number]>; + readonly sourceFileStats: ReadonlyMap>; +}; +const diffModels = new WeakMap, Map>(); +const patchHashes = new WeakMap(); + +// Hashing, ordering and counting every file of a huge pull request costs a second, and the tab +// renders far more often than its slices change, so the model is kept per slice list. +function diffModel( + slices: ReadonlyArray, + keyPrefix: string, + ignoreWhitespace: boolean, +): DiffModel { + let models = diffModels.get(slices); + if (models === undefined) diffModels.set(slices, (models = new Map())); + const cached = models.get(keyPrefix); + if (cached !== undefined) return cached; + const parsedSlices = slices.map((slice) => { + let hash = patchHashes.get(slice); + if (hash === undefined) patchHashes.set(slice, (hash = fnv1a32(slice.patch))); + // The cache key carries the theme, which the tokenizer caches against, and the patch's + // hash: a refreshed page reuses its cursor, so position alone would return a stale parse. + return parseSlice(slice, `${keyPrefix}:${slice.cursor ?? "first"}:${hash}`, ignoreWhitespace); + }); + const model: DiffModel = { + parsedSlices, + loadedFiles: orderDiffFilesLikeTree( + parsedSlices.flatMap((parsed) => + parsed?.kind === "files" ? orderDiffFiles(parsed.files) : [], + ), + ), + sourceFileStats: new Map( + parsedSlices.flatMap((parsed) => + parsed?.kind === "files" + ? parsed.files.map( + (file, index) => + [ + buildFileDiffRenderKey(file), + getDiffLineStat([parsed.sourceFiles[index] ?? file]), + ] as const, + ) + : [], + ), + ), + }; + models.set(keyPrefix, model); + return model; +} + +const threadsByPathCache = new WeakMap< + ReadonlyArray, + ReadonlyMap> +>(); + +function reviewThreadsByPath(threads: ReadonlyArray) { + let byPath = threadsByPathCache.get(threads); + if (byPath === undefined) { + const grouped = new Map(); + for (const thread of threads) { + const list = grouped.get(thread.path); + if (list) list.push(thread); + else grouped.set(thread.path, [thread]); + } + threadsByPathCache.set(threads, (byPath = grouped)); + } + return byPath; +} + interface FileViewedToggleState { readonly enabled: boolean; readonly isViewed: (path: string) => boolean; @@ -491,20 +561,10 @@ function PullRequestCodeTab({ // Agent context is local, so it does not require host comment permission. const canSelectLines = commit === null && (review.inlineComment || onAddToAgentSelection !== undefined); - // The cache key carries the theme, which is what the tokenizer caches against, so a theme - // change is still a fresh parse. The patch's own hash is part of it too: a refreshed page - // reuses its cursor, and a key of position alone would hand back the parse it replaced. - const parsedSlices = loadedSlices.map((slice) => - parseSlice( - slice, - `pull-request:${scopeKey}:${resolvedTheme}:${ignoreWhitespace}:${slice.cursor ?? "first"}:${fnv1a32(slice.patch)}`, - ignoreWhitespace, - ), - ); - const loadedFiles = orderDiffFilesLikeTree( - parsedSlices.flatMap((parsed) => - parsed?.kind === "files" ? orderDiffFiles(parsed.files) : [], - ), + const { parsedSlices, loadedFiles, sourceFileStats } = diffModel( + loadedSlices, + `pull-request:${scopeKey}:${resolvedTheme}:${ignoreWhitespace}`, + ignoreWhitespace, ); const testFileCount = loadedFiles.filter((file) => isTestChangedFile(resolveFileDiffPath(file)), @@ -523,33 +583,16 @@ function PullRequestCodeTab({ slice.omittedFileStats.map((file) => [file.path, file] as const), ), ); - const sourceFileStats = new Map( - parsedSlices.flatMap((parsed) => - parsed?.kind === "files" - ? parsed.files.map( - (file, index) => - [ - buildFileDiffRenderKey(file), - getDiffLineStat([parsed.sourceFiles[index] ?? file]), - ] as const, - ) - : [], - ), - ); const fileTreeEntries = diffFileTreeEntries(files); + const threadsByPath = reviewThreadsByPath(detail.reviewThreads); // File membership does not guarantee a rendered hunk for the thread. const placedThreadIds = (() => { const placed = new Set(); // Commit diffs use different line coordinates; list conversations separately. if (commit !== null) return placed; for (const file of files) { - const path = resolveFileDiffPath(file); - for (const thread of detail.reviewThreads) { - if ( - thread.path === path && - thread.line !== null && - isLineInFileDiff(file, thread.side, thread.line) - ) { + for (const thread of threadsByPath.get(resolveFileDiffPath(file)) ?? []) { + if (thread.line !== null && isLineInFileDiff(file, thread.side, thread.line)) { placed.add(thread.id); } } @@ -576,9 +619,8 @@ function PullRequestCodeTab({ return created; }; - for (const thread of detail.reviewThreads) { - if (thread.path !== path || thread.line === null) continue; - if (!placedThreadIds.has(thread.id)) continue; + for (const thread of threadsByPath.get(path) ?? []) { + if (thread.line === null || !placedThreadIds.has(thread.id)) continue; groupAt(thread.side, thread.line).threads.push(thread); } if (commit === null) { diff --git a/apps/web/src/components/settings/AuthorizedClientsSettings.tsx b/apps/web/src/components/settings/AuthorizedClientsSettings.tsx index c63c163592c6f..61fa056cff67b 100644 --- a/apps/web/src/components/settings/AuthorizedClientsSettings.tsx +++ b/apps/web/src/components/settings/AuthorizedClientsSettings.tsx @@ -876,8 +876,8 @@ export const AdvertisedEndpointListRow = memo(function AdvertisedEndpointListRow {isDefault ? ( ) : null} -
-
+
+

{endpoint.label}

@@ -894,14 +894,14 @@ export const AdvertisedEndpointListRow = memo(function AdvertisedEndpointListRow ) : null} {!isAvailable ? ( - + Setup required ) : null}
-
+
{isDefault ? ( - + Default ) : null} diff --git a/apps/web/src/components/settings/DictationSettings.tsx b/apps/web/src/components/settings/DictationSettings.tsx index ecc009e8872ea..0c2d9caf650b3 100644 --- a/apps/web/src/components/settings/DictationSettings.tsx +++ b/apps/web/src/components/settings/DictationSettings.tsx @@ -25,10 +25,10 @@ import { useEnvironmentScope } from "~/state/session"; import { useAtomCommand } from "~/state/use-atom-command"; import { Button } from "../ui/button"; import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; +import { Switch } from "../ui/switch"; import { toastManager } from "../ui/toast"; import { EnvironmentRow, environmentTransportLabel } from "./EnvironmentRow"; import { FoldedSettingsSection } from "./FoldedSettingsSection"; -import { ScopedSwitch } from "./ScopedSwitch"; import { useSettingsScope } from "./SettingsScopeContext"; import { SettingsRow, SettingsSection } from "./settingsLayout"; import { searchableSetting } from "./settingsSearch"; @@ -88,7 +88,7 @@ const modelDetail = (model: DictationModel) => * Settings need settings:write; retry and remove need orchestration:operate. */ export function DictationSettingsSection() { - const { scope, environment, connectedEnvironments } = useSettingsScope(); + const { scope, environment, connectedEnvironments, targets } = useSettingsScope(); const environmentId = environment?.connection.phase === "connected" && environment.serverConfig !== null ? environment.environmentId @@ -97,6 +97,9 @@ export function DictationSettingsSection() { // A server from before dictation has no dictation methods, so its subscription fails outright. const outdated = environmentId !== null && state === null && error !== null; const settings = useScopedSettings((unified) => unified.dictation); + const engineMixed = targets.some( + (target) => target.settings.dictation.engine !== settings.engine, + ); const updateSettings = useUpdateScopedSettings(); const canConfigure = useEnvironmentScope(environmentId, AuthSettingsWriteScope); const projectScope = scope.kind === "project" || scope.kind === "checkout"; @@ -120,9 +123,9 @@ export function DictationSettingsSection() { : "Transcribe dictation on this environment with a local speech model. Audio is not sent to any other service." } control={ - @@ -286,12 +289,10 @@ function InactiveDictationModels(props: { const [removing, setRemoving] = useState(null); if (!state?.supported) return null; const inactive = state.models.filter( - // The environment keeps its own active model even when another environment's - // selection is shown; removing it would be a no-op on the server. (model) => model.install._tag === "installed" && - model.id !== props.selectedModel && - model.id !== state.settings.localModel, + (state.settings.engine === "off" || + (model.id !== props.selectedModel && model.id !== state.settings.localModel)), ); if (inactive.length === 0) return null; @@ -402,7 +403,7 @@ export function DictationRoutingSettings({

The machine that turns this device's dictation into text. Automatic uses the machine that owns the thread when its dictation is ready, otherwise another ready machine. Download - models in Integrations. This applies only to this device. + models in Devices. This applies only to this device.

{environments.map((environment) => ( })), ); +function isGroupingSelection(value: unknown): value is SidebarProjectGroupingMode | "inherit" { + return ( + value === "inherit" || + value === "repository" || + value === "repository_path" || + value === "separate" + ); +} + +// Grouping overrides are client settings, so they stay editable without project write access. +function CheckoutGroupingSelect({ member }: { member: SidebarProjectGroupMember }) { + const overrideKey = derivePhysicalProjectKey(member); + const globalMode = useClientSettings((settings) => settings.sidebarProjectGroupingMode); + const selection = useClientSettings( + (settings) => settings.sidebarProjectGroupingOverrides?.[overrideKey] ?? "inherit", + ); + return ( + + ); +} + export type ProjectSettingsCategory = "general" | "source-control" | "project"; interface ProjectSelection { @@ -334,19 +411,32 @@ function ProjectDetail({ if (members) members.push(member); else checkoutsByEnvironment.set(member.environmentId, [member]); } - const checkoutRemoveButton = (member: SidebarProjectGroupMember) => ( - + // A lone checkout is removed from the Danger section, but it still needs its grouping + // rule here so "Keep separate" can be undone. + const checkoutControls = (member: SidebarProjectGroupMember) => ( +
+
+ +
+ {hasMultipleCheckouts ? ( + + ) : null} +
); const checkoutChoices = ( +

+ Grouping rule decides how each checkout joins project groups in the sidebar. Changing it can + move a checkout to a different project. +

{Array.from(checkoutsByEnvironment, ([environmentId, members]) => { if (checkoutsByEnvironment.size === 1) { return members.map((member) => ( @@ -354,7 +444,7 @@ function ProjectDetail({ key={member.physicalProjectKey} title={member.environmentLabel ?? "Environment"} description={member.workspaceRoot} - control={checkoutRemoveButton(member)} + control={checkoutControls(member)} /> )); } @@ -383,26 +473,26 @@ function ProjectDetail({ ) : null} } - control={hasMultiple ? undefined : checkoutRemoveButton(firstMember)} + control={hasMultiple ? undefined : checkoutControls(firstMember)} > {hasMultiple ? (
{members.map((member) => (
+ } > {member.workspaceRoot} {member.workspaceRoot} -
{checkoutRemoveButton(member)}
+
{checkoutControls(member)}
))}
@@ -565,7 +655,7 @@ function ProjectDetail({
- {hasMultipleCheckouts ? checkoutChoices : null} + {checkoutChoices} { outputRef.current = state.output; }, [state.output]); @@ -105,7 +105,7 @@ export function ProviderLoginDialog({ }; // Create the xterm surface when the dialog opens; tear it down on close. - // oxlint-disable-next-line t3code/react-effect-budget -- xterm mounts into a DOM node React has rendered + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- xterm mounts into a DOM node React has rendered useEffect(() => { if (!open) return; const mount = containerRef.current; @@ -186,7 +186,7 @@ export function ProviderLoginDialog({ }, [open, environmentId, instanceId, write, resize]); // Write output deltas to the terminal as they stream in. - // oxlint-disable-next-line t3code/react-effect-budget -- pushes streamed output into the imperative xterm instance + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- pushes streamed output into the imperative xterm instance useEffect(() => { const terminal = terminalRef.current; if (!terminal) return; diff --git a/apps/web/src/components/settings/ProviderSettingsPanel.environment.browser.test.tsx b/apps/web/src/components/settings/ProviderSettingsPanel.environment.browser.test.tsx index 79322dc5ff6ee..3e6cbb5fbf79b 100644 --- a/apps/web/src/components/settings/ProviderSettingsPanel.environment.browser.test.tsx +++ b/apps/web/src/components/settings/ProviderSettingsPanel.environment.browser.test.tsx @@ -36,6 +36,7 @@ const state = vi.hoisted(() => ({ updateModelPreferences: vi.fn(), toggleFavorite: vi.fn(), mutateProviderInstance: vi.fn(), + confirm: vi.fn<() => Promise>(), })); vi.mock(import("../../state/server"), async (original) => { @@ -80,6 +81,14 @@ vi.mock(import("../../state/use-atom-command"), async (original) => ({ "accept-url-auth": state.acceptUrlAuth, })[command.label ?? ""] ?? vi.fn()) as never, })); +vi.mock(import("~/localApi"), async (original) => { + const api = { dialogs: { confirm: state.confirm } }; + return { + ...(await original()), + readLocalApi: (() => api) as never, + ensureLocalApi: (() => api) as never, + }; +}); vi.mock(import("../../state/query"), async (original) => ({ ...(await original()), useEnvironmentQuery: ((query: unknown) => ({ @@ -231,6 +240,7 @@ async function setup() { state.updateModelPreferences.mockReset(); state.toggleFavorite.mockReset(); state.mutateProviderInstance.mockReset().mockResolvedValue(AsyncResult.success({})); + state.confirm.mockReset().mockResolvedValue(false); state.refresh.mockReset().mockResolvedValue(AsyncResult.success(undefined)); state.updateProvider.mockReset().mockResolvedValue(AsyncResult.success(undefined)); state.uninstall.mockReset().mockResolvedValue(AsyncResult.success({})); @@ -359,6 +369,90 @@ describe("EnvironmentProviderSettings routing", () => { }); }); +describe("EnvironmentProviderSettings instance removal", () => { + it("resets a configured default instance only once the user confirms", async () => { + await setup(); + state.settings = { + ...DEFAULT_UNIFIED_SETTINGS, + providerInstances: { + [codexId]: { + driver: ProviderDriverKind.make("codex"), + enabled: true, + config: { binaryPath: "/opt/codex/bin/codex" }, + }, + }, + }; + await setProviders([provider()]); + await using _screen = await render(panel({ targetInstanceId: codexId })); + const reset = page.getByRole("button", { name: "Reset Codex provider settings to default" }); + await userEvent.click(reset); + + expect(state.mutateProviderInstance).not.toHaveBeenCalled(); + expect(state.confirm).toHaveBeenCalledOnce(); + + state.confirm.mockResolvedValue(true); + await userEvent.click(reset); + await vi.waitFor(() => + expect(state.mutateProviderInstance).toHaveBeenCalledWith({ + operation: "remove", + instanceId: codexId, + }), + ); + }); + + it("warns that resetting an enabled default-off provider turns it off", async () => { + await setup(); + const antigravityId = ProviderInstanceId.make("antigravity"); + const antigravity = ProviderDriverKind.make("antigravity"); + state.settings = { + ...DEFAULT_UNIFIED_SETTINGS, + providerInstances: { + [antigravityId]: { + driver: antigravity, + enabled: true, + config: { binaryPath: "/opt/antigravity/bin/agy" }, + }, + }, + }; + await setProviders([{ ...provider(), instanceId: antigravityId, driver: antigravity }]); + await using _screen = await render(panel({ targetInstanceId: antigravityId })); + await userEvent.click(page.getByRole("button", { name: /^Reset .* provider settings/ })); + + expect(state.confirm).toHaveBeenCalledWith( + expect.stringContaining("It will also be turned off."), + { + variant: "destructive", + }, + ); + expect(state.mutateProviderInstance).not.toHaveBeenCalled(); + }); + + it("deletes a custom instance only once the user confirms", async () => { + await setup(); + state.settings = { + ...DEFAULT_UNIFIED_SETTINGS, + providerInstances: { + [customId]: { driver: ProviderDriverKind.make("codex"), enabled: true }, + }, + }; + await using _screen = await render(panel({ targetInstanceId: customId })); + const remove = page.getByRole("button", { name: `Delete instance ${customId}` }); + await userEvent.click(remove); + + expect(state.mutateProviderInstance).not.toHaveBeenCalled(); + expect(state.confirm).toHaveBeenCalledOnce(); + + state.confirm.mockResolvedValue(true); + await userEvent.click(remove); + await vi.waitFor(() => + expect(state.mutateProviderInstance).toHaveBeenCalledWith({ + operation: "remove", + instanceId: customId, + }), + ); + }); +}); + describe("EnvironmentProviderSettings health check interval", () => { it("commits interval drafts and allows retrying rejected edits", async () => { await setup(); diff --git a/apps/web/src/components/settings/ProviderSettingsPanel.tsx b/apps/web/src/components/settings/ProviderSettingsPanel.tsx index 5585a062dd652..fca8b88925e96 100644 --- a/apps/web/src/components/settings/ProviderSettingsPanel.tsx +++ b/apps/web/src/components/settings/ProviderSettingsPanel.tsx @@ -11,6 +11,7 @@ import { connectionStatusTitle } from "@t3tools/client-runtime/connection"; import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors"; import { isAtomCommandInterrupted, + settlePromise, squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; import { @@ -47,6 +48,7 @@ import { useToggleEnvironmentModelFavorite, } from "../../hooks/useSettings"; import { useStableCallback } from "../../hooks/useStableCallback"; +import { ensureLocalApi } from "../../localApi"; import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon"; import { cn } from "../../lib/utils"; import { resolveAppModelSelectionState } from "../../modelSelection"; @@ -127,6 +129,25 @@ import { resolveSelectedProviderEnvironmentId, } from "./ProviderSettingsPanel.logic"; +function providerInstanceName(instance: ProviderInstanceConfig): string { + return ( + instance.displayName?.trim() || + providerClients.get(instance.driver)?.label || + String(instance.driver) + ); +} + +async function confirmProviderInstanceRemoval( + question: string, + consequence = "", +): Promise { + const message = `${question}\nIts saved settings, including any custom binary path, will be removed.${consequence}`; + const confirmed = await settlePromise(() => + ensureLocalApi().dialogs.confirm(message, { variant: "destructive" }), + ); + return confirmed._tag === "Success" && confirmed.value; +} + function modelListChanges(current: ReadonlyArray, next: ReadonlyArray) { const currentSet = new Set(current); const nextSet = new Set(next.map((model) => model.trim()).filter(Boolean)); @@ -830,6 +851,10 @@ export function EnvironmentProviderSettings({ const deleteInstance = useStableCallback( async (instanceId: ProviderInstanceId, instance: ProviderInstanceConfig) => { + const confirmed = await confirmProviderInstanceRemoval( + `Remove the ${providerInstanceName(instance)} provider instance?`, + ); + if (!confirmed) return; const updateResult = await persistProviderInstance({ operation: "remove", instanceId, @@ -866,10 +891,17 @@ export function EnvironmentProviderSettings({ ); const resetDefaultInstance = useStableCallback(async (driverKind: ProviderDriverKind) => { - const result = await persistProviderInstance({ - operation: "remove", - instanceId: defaultInstanceIdForDriver(driverKind), - }); + const instanceId = defaultInstanceIdForDriver(driverKind); + const instance = settings.providerInstances?.[instanceId] ?? { driver: driverKind }; + const turnsOff = + resolveProviderInstanceEnabled(instance) && + !resolveProviderInstanceEnabled({ driver: driverKind }); + const confirmed = await confirmProviderInstanceRemoval( + `Reset the ${providerInstanceName(instance)} provider to its defaults?`, + turnsOff ? " It will also be turned off." : "", + ); + if (!confirmed) return; + const result = await persistProviderInstance({ operation: "remove", instanceId }); if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { const error = squashAtomCommandFailure(result); toastManager.add({ diff --git a/apps/web/src/components/settings/SourceControlAppSignInSettings.tsx b/apps/web/src/components/settings/SourceControlAppSignInSettings.tsx index 5662954ef7cd6..df73fa3b24b45 100644 --- a/apps/web/src/components/settings/SourceControlAppSignInSettings.tsx +++ b/apps/web/src/components/settings/SourceControlAppSignInSettings.tsx @@ -101,7 +101,9 @@ export function SourceControlAppSignInSettings({ readHostCredentialSettings(settings, definition.kind), ); const signedIn = (signIns[host] ?? "").length > 0; - const tokenOverrides = (tokens[host] ?? "").length > 0; + const token = tokens[host]; + // A token read from a secret provider overrides the sign-in like a saved one. + const tokenOverrides = typeof token === "string" ? token.length > 0 : token !== undefined; const canSignIn = useAtomValue( sourceControlEnvironment.startSignIn.permissionAtom(environmentId), ); diff --git a/apps/web/src/components/settings/SourceControlTokenSettings.tsx b/apps/web/src/components/settings/SourceControlTokenSettings.tsx index 912de7ad91701..5a78b5f28287d 100644 --- a/apps/web/src/components/settings/SourceControlTokenSettings.tsx +++ b/apps/web/src/components/settings/SourceControlTokenSettings.tsx @@ -1,4 +1,9 @@ -import type { EnvironmentId } from "@t3tools/contracts"; +import { + isSecretReference, + type EnvironmentId, + type SecretReference, + type SettingsSecretValue, +} from "@t3tools/contracts"; import { ExternalLinkIcon } from "lucide-react"; import { useState } from "react"; @@ -12,8 +17,11 @@ import { serverEnvironment } from "../../state/server"; import { useAtomCommand } from "../../state/use-atom-command"; import { Button, InlineButton } from "../ui/button"; import { Input } from "../ui/input"; -import { SecretInput } from "./SecretInput"; import { Label } from "../ui/label"; +import { SecretSourceInput, useSecretSources } from "./SecretSourceInput"; + +const hasToken = (token: SettingsSecretValue | undefined) => + typeof token === "string" ? token.length > 0 : token !== undefined; export function SourceControlTokenSettings({ environmentId, @@ -34,15 +42,24 @@ export function SourceControlTokenSettings({ }); const defaultHost = definition.publicHost ?? ""; const [host, setHost] = useState(defaultHost); - const [draft, setDraft] = useState(""); + const secretSources = useSecretSources(environmentId); + const [pending, setPending] = useState<{ + readonly key: string; + readonly draft: string | SecretReference; + } | null>(null); const [saving, setSaving] = useState(false); const normalizedHost = host.trim().toLowerCase(); - const isSaved = (tokens[normalizedHost] ?? "").length > 0; + const savedToken = tokens[normalizedHost]; + const isSaved = hasToken(savedToken); const savedHosts = Object.entries(tokens) - .filter(([, value]) => value.length > 0) + .filter(([, value]) => hasToken(value)) .map(([saved]) => saved); + const sourceKey = JSON.stringify([normalizedHost, savedToken ?? ""]); + const draft = + pending?.key === sourceKey ? pending.draft : isSecretReference(savedToken) ? savedToken : ""; + const submission = typeof draft === "string" ? draft.trim() : draft; - const save = async (target: string, token: string) => { + const save = async (target: string, token: SettingsSecretValue) => { setSaving(true); const result = await updateSettings({ environmentId, @@ -55,7 +72,7 @@ export function SourceControlTokenSettings({ }); setSaving(false); if (result._tag === "Success") { - setDraft(""); + setPending(null); onSaved(); } }; @@ -65,7 +82,7 @@ export function SourceControlTokenSettings({ className="grid gap-3" onSubmit={(event) => { event.preventDefault(); - if (normalizedHost && draft.trim()) void save(normalizedHost, draft.trim()); + if (normalizedHost && submission !== "") void save(normalizedHost, submission); }} > {/* Locked while saving: a successful save clears the draft, which would drop edits made mid-request. */} @@ -106,12 +123,15 @@ export function SourceControlTokenSettings({
- setDraft(event.target.value)} + sources={secretSources} + onChange={(event) => setPending({ key: sourceKey, draft: event.target.value })} + onSecretChange={(secret) => setPending({ key: sourceKey, draft: secret ?? "" })} />
@@ -132,7 +152,11 @@ export function SourceControlTokenSettings({ Remove ) : null} -
diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index c78786522522b..c02a12a7bb3c7 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -607,7 +607,9 @@ export const SETTINGS_SEARCH_ITEMS = [ id: "provider-update-checks", title: "Provider update checks", to: "/settings/maintenance", - searchTerms: ["installed cli versions newer available codex claude cursor grok fx opencode"], + searchTerms: [ + "installed cli versions newer available codex claude cursor grok fx kiro opencode", + ], scope: "environment-defaults", }, { @@ -817,7 +819,7 @@ export const SETTINGS_SEARCH_ITEMS = [ title: "Providers", to: "/settings/providers", searchTerms: [ - "agents cli codex claude cursor grok fx opencode antigravity google sign in sign out install subscription instances authentication api key models configuration binary path config directory codex_home shadow home endpoint arguments environment variables display name accent color custom favorite hidden auto compact native sessions import resume", + "agents cli codex claude cursor grok fx kiro opencode antigravity google sign in sign out install subscription instances authentication api key models configuration binary path config directory codex_home shadow home endpoint arguments environment variables display name accent color custom favorite hidden auto compact native sessions import resume", ], }, { diff --git a/apps/web/src/components/sidebar/SidebarDraftBlock.tsx b/apps/web/src/components/sidebar/SidebarDraftBlock.tsx index 10581ecb5a679..bc15ca5945972 100644 --- a/apps/web/src/components/sidebar/SidebarDraftBlock.tsx +++ b/apps/web/src/components/sidebar/SidebarDraftBlock.tsx @@ -82,8 +82,8 @@ const SidebarDraftRow = memo(function SidebarDraftRow(props: { return (
  • \n \n );\n}\n", "apps/web/src/tasks/api.ts": "export const stopTask = (id: string) => fetch(`/api/tasks/${id}/stop`, { method: 'POST' });\n"}}}, "prompt": "In the task list, the Stop button on a running background task does nothing: the task keeps showing Running and its worker thread keeps going. Wire it up.", "expect": {"notCalls": ["t3_thread_launch", "create_threads", "delegate_task", "orchestrator_capabilities", "task_cancel", "task_status", "t3_thread_interrupt", "t3_thread_send"]}, "source": {"request": "juliusmarminge (maintainer) request, 2026-10-29; regression guard"}, "notes": ""} +{"id": "tt-control-task-queue", "area": "orchestration", "kind": "control", "pattern": "Domain task queue lookup", "experience": "A question about the app's task queue limit is ordinary code work, not a T3 task.", "rule": "Ordinary coding tasks need no T3 tools.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Repository: /home/user/app (acme/app). This is the local machine.", "world": {"repo": "acme/app", "branch": "main", "status": "", "files": {"docs/cache.md": "Cache exports must preserve keys.\n", "src/thread-pool.ts": "export const workerCount = 4;\n", "src/task-queue.ts": "export const queueLimit = 10;\n", "src/agent-config.ts": "export const agentLabel = \"Assistant\";\n"}}, "mocks": {"t3_thread_launch": {"threadId": "11111111-1111-4111-8111-111111111111", "projectId": "33333333-3333-4333-8333-333333333333", "modelSelection": {"instanceId": "codex", "model": "gpt-6.1-sol", "options": []}, "runId": "run-acme-thread", "status": "running"}, "t3_thread_read": {"thread": {"threadId": "11111111-1111-4111-8111-111111111111", "title": "Acme cache worker", "status": "running"}, "items": [{"position": 1, "type": "assistant_message", "text": "Checking the cache export."}], "nextPosition": 1, "hasMore": false}, "t3_thread_wait": {"threadId": "11111111-1111-4111-8111-111111111111", "runId": "run-acme-thread", "status": "running", "timedOut": true, "next": "Completion wakes this thread, so end your turn. Do not wait on it or poll it."}}}, "prompt": "Explain the configured limit in src/task-queue.ts. This is the application task queue.", "expect": {"notCalls": ["t3_thread_launch", "create_threads", "delegate_task", "Agent", "Workflow", "orchestrator_capabilities", "task_status", "task_cancel"]}, "source": {"request": "juliusmarminge (maintainer) request, 2026-10-29; regression guard"}, "notes": "Synthetic Acme scenario; no field transcript copied."} +{"id": "tt-control-agent-config", "area": "orchestration", "kind": "control", "pattern": "Domain agent configuration lookup", "experience": "A question about the app's agent label setting is ordinary code work; it starts no agent.", "rule": "Ordinary coding tasks need no T3 tools.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Repository: /home/user/app (acme/app). This is the local machine.", "world": {"repo": "acme/app", "branch": "main", "status": "", "files": {"docs/cache.md": "Cache exports must preserve keys.\n", "src/thread-pool.ts": "export const workerCount = 4;\n", "src/task-queue.ts": "export const queueLimit = 10;\n", "src/agent-config.ts": "export const agentLabel = \"Assistant\";\n"}}, "mocks": {"t3_thread_launch": {"threadId": "11111111-1111-4111-8111-111111111111", "projectId": "33333333-3333-4333-8333-333333333333", "modelSelection": {"instanceId": "codex", "model": "gpt-6.1-sol", "options": []}, "runId": "run-acme-thread", "status": "running"}, "t3_thread_read": {"thread": {"threadId": "11111111-1111-4111-8111-111111111111", "title": "Acme cache worker", "status": "running"}, "items": [{"position": 1, "type": "assistant_message", "text": "Checking the cache export."}], "nextPosition": 1, "hasMore": false}, "t3_thread_wait": {"threadId": "11111111-1111-4111-8111-111111111111", "runId": "run-acme-thread", "status": "running", "timedOut": true, "next": "Completion wakes this thread, so end your turn. Do not wait on it or poll it."}}}, "prompt": "Read src/agent-config.ts and tell me the current default agent label in this application.", "expect": {"notCalls": ["t3_thread_launch", "create_threads", "delegate_task", "Agent", "Workflow", "orchestrator_capabilities"]}, "source": {"request": "juliusmarminge (maintainer) request, 2026-10-29; regression guard"}, "notes": "Synthetic Acme scenario; no field transcript copied."} +{"id": "tt-background-research-no-agent-word", "area": "orchestration", "kind": "guard", "pattern": "bare 'in the background' ask: delegate_task", "experience": "Asked to look into something in the background without the word 'agent', the agent must start a delegate_task, not a background native Agent or a new thread.", "rule": "Background agent work goes to delegate_task; Claude's Agent runs with run_in_background:false. / t3_thread_launch and create_threads make new top-level threads, only when the user asks for a new thread.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Repository: /home/user/app (acme/app). This is the local machine.", "world": {"repo": "acme/app", "branch": "main", "status": "", "files": {"docs/cache.md": "Cache exports must preserve keys.\n", "src/cache/export.ts": "export function exportCache(entries: Map) {\n return [...entries].filter(([, value]) => value !== '').map(([key, value]) => ({ key, value }));\n}\n"}}}, "prompt": "In the background, find out why src/cache/export.ts drops entries that docs/cache.md says must be kept, and report back when you know. I'll keep going on the release notes here.", "expect": {"calls": [{"tool": "delegate_task", "args": {"task": "~cache"}}], "notCalls": ["t3_thread_launch", "create_threads", "Workflow", "t3_thread_wait"], "callsMustNot": [{"tool": "Agent", "args": {"run_in_background": true}}, {"tool": "delegate_task", "args": {"mode": "wait"}}], "maxCalls": {"task_status": 0}}, "source": {"request": "juliusmarminge (maintainer) request, 2026-10-29; regression guard", "review": "council review round 1: bare background ask without 'agent'"}, "notes": "Synthetic Acme scenario. Pairs with tt-background-agent; checks the rule does not depend on the word 'agent'."} +{"id":"tt-control-background-test-run","area":"orchestration","kind":"control","pattern":"background shell command is not a delegate","experience":"Asked to run the test suite in the background while refactoring, the agent should use an ordinary background shell command, not a delegate, subagent or thread.","rule":"Ordinary coding tasks need no T3 tools.","privacy":"commit-safe","setup":{"role":"top","context":"Repository: /home/user/app (acme/app). This is the local machine.","world":{"repo":"acme/app","branch":"main","status":"","files":{"package.json":"{\"scripts\":{\"test\":\"vitest run\"}}\n","src/export/csv.ts":"export function toCsv(rows: Row[]) {\n return rows.map((r) => [r.id, r.total].join(',')).join('\\n');\n}\n"}}},"prompt":"Kick off the full test suite in the background, and meanwhile rename toCsv to rowsToCsv in src/export/csv.ts.","expect":{"notCalls":["delegate_task","t3_thread_launch","create_threads","Workflow","orchestrator_capabilities"],"callsMustNot":[{"tool":"Agent","args":{"run_in_background":true}}],"calls":[{"tool":"Bash","args":{"command":"~test"}}]},"source":{"request":"juliusmarminge (maintainer) request, 2026-10-29; regression guard","review":"council review round 1: over-correction control for 'background'"},"notes":"Synthetic Acme scenario. 'Background' here means a shell command, not an agent."} diff --git a/evals/mcp-tool-use/devices.test.ts b/evals/mcp-tool-use/devices.test.ts index 444e5850c64e5..40c7efb92a82f 100644 --- a/evals/mcp-tool-use/devices.test.ts +++ b/evals/mcp-tool-use/devices.test.ts @@ -1,7 +1,9 @@ // @effect-diagnostics nodeBuiltinImport:off import * as NodeFS from "node:fs"; import * as NodeZlib from "node:zlib"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as Layer from "effect/Layer"; import { assert, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; @@ -100,7 +102,7 @@ it.effect("answers device calls with T3's handlers over the case's world", () => const elsewhere = yield* tools.call("device_open", { hostId: "local", deviceId: IPHONE }); assert.isTrue(elsewhere.isError); assert.include(elsewhere.text, IPHONE); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect("lists the boot state T3 left a device in", () => @@ -113,7 +115,7 @@ it.effect("lists the boot state T3 left a device in", () => yield* tools.call("device_open", { hostId: MAC, deviceId: IPHONE }); const after = json((yield* tools.call("device_list", {})).text); assert.isTrue(after.devices.find((d: { id: string }) => d.id === IPHONE).booted); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it("decodes only T3 device errors as injected failures", () => { @@ -148,7 +150,7 @@ it.effect("rebuilds prior device results with T3, whose sessions reach the measu assert.isFalse((yield* tools.call("device_screenshot", {})).isError); const mock = deviceFailure(testCase.setup.mocks?.device_screenshot); assert.isTrue((yield* tools.call("device_screenshot", {}, mock)).isError); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect("gives a native subagent T3's SubagentStart context instead of T3's append", () => @@ -204,7 +206,7 @@ it.effect("tells the shell simulator the launchers T3 returned and agent-device' // A case without devices keeps the shell prompt every other case has. const plain = makeSample(deviceCase({ world: {} }), base); assert.notInclude(shellRequest(plain, call, "claude-haiku-5-5").system, "agent-device"); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it("prints agent-device's own help for a lone help command on a returned launcher", () => { @@ -315,7 +317,7 @@ it.effect("answers the returned launcher as agent-device does before and after o tools.sessionError(history, `${line("screenshot /tmp/a.png")} 2>&1`), NO_SESSION, ); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); const shared = (session: string): LauncherTarget => ({ @@ -484,7 +486,7 @@ it.effect("starts sessions the world says prior turns opened, and rejects unknow const unknown = { devices, deviceHosts, agentDeviceSessions: { "not-a-device": {} } }; const exit = yield* Effect.exit(makeDeviceTools(unknown, base.environment)); assert.isTrue(exit._tag === "Failure"); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect( @@ -522,7 +524,7 @@ it.effect( }); assert.isUndefined(cannedOutput(sample, `${command} screenshot /tmp/a.png${flags}`)); assert.include(told(), "is open with an app"); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it("keeps a redirection's descriptor out of the app an open names, on either launcher", () => { @@ -631,7 +633,7 @@ it.effect("lists a host whose discovery fails as T3 does: failed, with none of i deviceTools({ deviceDiscoveryFailures: { "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee": failure } }), ); assert.isTrue(unlabeled._tag === "Failure"); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect("denies every device tool with T3's own error when agent device access is off", () => @@ -657,7 +659,7 @@ it.effect("denies every device tool with T3's own error when agent device access } // T3 drops its device text for a thread without the capability, on refs that have it. assert.notInclude(t3SystemAppend(model, false), "## T3 Code devices"); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect("reports an unreadable capture as T3 does: a successful 0×0 screenshot", () => @@ -674,7 +676,7 @@ it.effect("reports an unreadable capture as T3 does: a successful 0×0 screensho yield* withDevices(sample); const told = JSON.stringify(shellRequest(sample, { tool: "Bash", input: {} }, model).messages); assert.include(told, "agent-device's own screenshot finds the PNG and is unaffected"); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect("refuses an open on a device another thread's agent-device session holds", () => @@ -742,7 +744,7 @@ it.effect("refuses an open on a device another thread's agent-device session hol history.push({ tool: "Bash", input: { command: line("close", owner) }, output: "Closed" }); assert.equal(answer("open com.acme.app"), ""); assert.include(describeSessions(tools.sessions(history), tools.owners), "was closed"); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect("leaves a free device free when another thread holds a different one", () => @@ -762,7 +764,7 @@ it.effect("leaves a free device free when another thread holds a different one", assert.isFalse( (yield* tools.call("device_list", {})).text.includes(`"hostId":"${LOCAL_DEVICE_HOST_ID}"`), ); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); type Opened = { command: string; targetArgs: Array; session?: string }; @@ -883,7 +885,7 @@ it.effect( JSON.stringify(request.messages), `${session(own)} (Acme iPhone, ${IPHONE}, on build-mac) has not started`, ); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it("tells the simulator 0.21.31's --foreground and session list behaviour", () => { diff --git a/evals/mcp-tool-use/devices.ts b/evals/mcp-tool-use/devices.ts index 3a36e3a62dcd1..9158028e8a395 100644 --- a/evals/mcp-tool-use/devices.ts +++ b/evals/mcp-tool-use/devices.ts @@ -21,7 +21,7 @@ import { } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Context from "effect/Context"; -import * as Crypto from "effect/Crypto"; +import * as Digest from "effect/crypto/Digest"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -695,7 +695,7 @@ export const makeDeviceTools = Effect.fn("evaluateMcpToolUse.makeDeviceTools")(f Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; - const crypto = yield* Crypto.Crypto; + const digest = yield* Digest.Digest; const { stateDir } = yield* ServerConfig.ServerConfig; const agentEntry = path.join(home, ".t3", "tools", "agent-device", "bin", "agent-device.mjs"); const hosts = new Map([ @@ -720,7 +720,7 @@ export const makeDeviceTools = Effect.fn("evaluateMcpToolUse.makeDeviceTools")(f // As DeviceService.make, minus writing the config file the path names. const configureAgent = (hostId: DeviceHostId, _endpoint: unknown, deviceId?: string) => agentDeviceConfigPath(stateDir, hostId, path, deviceId).pipe( - Effect.provideService(Crypto.Crypto, crypto), + Effect.provideService(Digest.Digest, digest), Effect.mapError( (cause) => new DeviceOperationError({ @@ -775,7 +775,7 @@ export const makeDeviceTools = Effect.fn("evaluateMcpToolUse.makeDeviceTools")(f ); const context = yield* Layer.build( McpHttpServer.layerDeviceToolkit.pipe( - Layer.provideMerge(McpServer.McpServer.layer), + Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), Layer.provideMerge(devices), Layer.provideMerge( Layer.mergeAll( diff --git a/evals/mcp-tool-use/run.test.ts b/evals/mcp-tool-use/run.test.ts index 69de4f0c6c4b2..217e505f5fcf5 100644 --- a/evals/mcp-tool-use/run.test.ts +++ b/evals/mcp-tool-use/run.test.ts @@ -1,6 +1,8 @@ // @effect-diagnostics nodeBuiltinImport:off import * as NodeFS from "node:fs"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as Layer from "effect/Layer"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import { assert, expect, it } from "@effect/vitest"; @@ -23,6 +25,7 @@ import { shellOutput, shellRequest, summarize, + t3Default, t3SystemAppend, t3SubagentContext, withDevices, @@ -70,6 +73,54 @@ it("accepts any tool listed as an alternative", () => { ]); }); +it("counts the new threads an agent asks for, one brief per thread, over both creation tools", () => { + const expect = { newThreads: ["~reconnect", "~csv", "~admin"] }; + const run = (...calls: Array<{ tool: string; input: unknown; failed?: boolean }>): SampleRun => ({ + calls: calls.map((call, step) => ({ step, ...call })), + text: "", + stopReason: "end_turn", + }); + const batch = (...prompts: Array) => ({ + tool: "create_threads", + input: { threads: prompts.map((prompt) => ({ prompt })) }, + }); + const launch = (message: string, failed = false) => ({ + tool: "t3_thread_launch", + input: { message }, + failed, + }); + const label = 'newThreads ["~reconnect","~csv","~admin"]'; + assert.deepEqual(failed(expect, run(batch("Fix reconnect", "Fix CSV dates", "Fix admin"))), []); + assert.deepEqual( + failed(expect, run(launch("Fix reconnect"), batch("Fix CSV dates", "Fix admin"))), + [], + ); + assert.deepEqual( + failed(expect, run(launch("Fix reconnect", true), batch("Fix reconnect", "csv", "admin"))), + [], + ); + assert.deepEqual(failed(expect, run(batch("reconnect", "csv"), launch("csv and admin"))), []); + assert.deepEqual(failed(expect, run(batch("Fix reconnect, csv and admin"))), [label]); + assert.deepEqual(failed(expect, run(batch("reconnect, csv, admin", "csv", "csv"))), [label]); + assert.deepEqual(failed(expect, run(batch("reconnect", "csv", "admin", "docs"))), [label]); + for (const call of [ + { tool: "t3_thread_launch", input: { prompt: "csv" } }, + { tool: "create_threads", input: { threads: [{ message: "csv" }] } }, + ]) { + assert.deepEqual(failed(expect, run(launch("reconnect"), launch("admin"), call)), [label]); + } + assert.deepEqual( + failed( + expect, + run(launch("reconnect"), launch("admin"), { + tool: "t3_thread_launch", + input: { title: "CSV", message: "Fix reconnect" }, + }), + ), + [label], + ); +}); + it("runs code-mode calls without exposing host capabilities, including after await", async () => { const catalog = [{ name: "mock", description: "mock" }]; const result = await executeCodex( @@ -345,6 +396,57 @@ it("replays earlier capability results with the model under test as the caller", assert.include(String(replayed?.content), '"inheritedModel":"claude-opus-5-5"'); }); +it("gives each launched thread its own id, and reading it back shows that thread's brief", () => { + const base = buildBase(template, { model: "claude-sonnet-5-5", keepUserInstructions: false }); + const sample = makeSample(childCase, base); + const one = t3Default(sample, "t3_thread_launch", { + title: "Reconnect", + message: "Fix reconnect", + }); + const batch = t3Default(sample, "create_threads", { + threads: [ + { title: "CSV", prompt: "Fix CSV dates" }, + { prompt: "Fix admin expiry", target: { providerInstanceId: "muse", model: "muse-wonder" } }, + ], + }); + const created = (batch as { threads: Array<{ providerInstanceId: string; model: string }> }) + .threads; + assert.deepEqual( + created.map((thread) => [thread.providerInstanceId, thread.model]), + [ + ["claudeAgent", "claude-sonnet-5-5"], + ["muse", "muse-wonder"], + ], + ); + const ids = [one, ...(batch as { threads: Array }).threads].map( + (thread) => (thread as { threadId: string }).threadId, + ); + assert.equal(new Set(ids).size, 3); + const read = (threadId: unknown) => + t3Default(sample, "t3_thread_read", { threadId }) as { + thread: { title: string; status: string; createdBy?: string }; + items: Array<{ text: string; createdBy: string; creationSource: string }>; + }; + const idle = t3Default(sample, "create_threads", { threads: [{ title: "Later" }] }) as { + threads: Array<{ threadId: string; status: string; runId?: string }>; + }; + assert.equal(idle.threads[0]?.status, "idle"); + assert.isUndefined(idle.threads[0]?.runId); + assert.equal(read(idle.threads[0]?.threadId).thread.status, "idle"); + assert.deepEqual(read(idle.threads[0]?.threadId).items, []); + assert.equal(read(ids[1]).thread.title, "CSV"); + assert.equal(read(ids[2]).items[0]?.text, "Fix admin expiry"); + assert.equal(read(ids[2]).thread.createdBy, "agent"); + assert.deepEqual( + [read(ids[2]).items[0]?.createdBy, read(ids[2]).items[0]?.creationSource], + ["agent", "mcp"], + ); + assert.equal( + read("11111111-1111-4111-8111-111111111111").thread.title, + "Fix the flaky reconnect test", + ); +}); + it("does not record a deferred tool called before it was loaded", () => { const base = buildBase(template, { model: "claude-sonnet-5-5", keepUserInstructions: false }); const sample = makeSample(childCase, base); @@ -464,7 +566,7 @@ it.effect("builds device cases from product-backed worlds and synthetic prior tu assert.equal(native.kind, "bad"); assert.equal(native.setup.harness, "claude"); assert.isNotEmpty(cases.find((c) => c.id === "SEED-01")!.setup.priorTurns!); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.each([ @@ -1178,7 +1280,7 @@ it.effect("accepts a successful exact-host recovery after a real device_open err stopReason: "end_turn", }).every((c) => c.pass), ); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it("keeps subshell-only launcher aliases out of the parent shell", () => { @@ -2836,7 +2938,7 @@ it.effect("fleet case worlds survive decoding and reach the product-backed runne assert.include(error, id === "OWN-01" ? "DEVICE_IN_USE" : "SESSION_NOT_FOUND"); if (id === "OWN-01") assert.equal(tools.owners[0]!.session, "t3-a062c547ef0b6bf8ee839b67"); } - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.each([ @@ -3010,7 +3112,7 @@ it.effect("R12 OWN-01 protects occupied panel sessions from selected and wildcar }), [], ); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect( @@ -3045,7 +3147,7 @@ it.effect( calls: [...calls, calls.at(-1)!, ...good.calls.slice(1)], }), ); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); const capRun6 = [ diff --git a/evals/mcp-tool-use/run.ts b/evals/mcp-tool-use/run.ts index 20f9090692d8b..3e6bb84f697be 100644 --- a/evals/mcp-tool-use/run.ts +++ b/evals/mcp-tool-use/run.ts @@ -10,6 +10,7 @@ import * as NodeUtil from "node:util"; import * as NodeVM from "node:vm"; import * as NodeZlib from "node:zlib"; import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { ComposerContextRecord, @@ -162,6 +163,11 @@ const McpToolUseExpect = Schema.Struct({ order: Schema.optional(Schema.Array(Schema.String)), minCalls: Schema.optional(Schema.Record(Schema.String, Schema.Number)), maxCalls: Schema.optional(Schema.Record(Schema.String, Schema.Number)), + /** + * One `args`-style value per new top-level thread the agent asks for, by `t3_thread_launch` or a + * `create_threads` entry. Each matches a different thread's request; no other thread is asked for. + */ + newThreads: Schema.optional(Schema.Array(Schema.Unknown)), /** The last step with tool calls includes this tool, then the turn ends. */ endsTurnAfter: Schema.optional(Schema.String), /** Regexes that no shell command may match. */ @@ -732,7 +738,8 @@ const createdPullRequests = ({ tool, input, output }: ShellEntry) => : []; /** * One sample's state. ToolSearch adds loaded schemas to `tools`, like Claude Code. `shell` is the - * history the simulator keeps consistent with; `linked` and `nextTask` do the same for T3 results. + * history the simulator keeps consistent with; `linked`, `nextTask` and `threads` do the same for + * T3 results. */ type Sample = { readonly testCase: McpToolUseCase; @@ -744,6 +751,8 @@ type Sample = { readonly linked: Set; readonly codeStore: Record; nextTask: number; + /** Threads the agent launched in this sample, by id, so reading one shows its own brief. */ + readonly threads: Map; /** T3's device tools, once `withDevices` builds them for a world with devices. */ devices?: DeviceTools; /** T3's results for prior device calls whose case result is "default". */ @@ -788,6 +797,7 @@ export const makeSample = (testCase: McpToolUseCase, base: Base): Sample => { linked: new Set([...urls, ...shell.flatMap(createdPullRequests)]), codeStore: {}, nextTask: Math.max(0, ...taskNumbers) + 1, + threads: new Map(), priorResults: new Map(), }; }; @@ -1000,9 +1010,41 @@ const linkedEntry = (sample: Sample, url: string) => { }; /** A believable T3 result for a tool the case does not mock. */ -const t3Default = (sample: Sample, name: string, input: Readonly>) => { +export const t3Default = ( + sample: Sample, + name: string, + input: Readonly>, +) => { const pr = () => pullRequest(sample.repo, input); + const newThread = (request: unknown, brief: unknown) => { + const n = sample.nextTask++; + const title = + isRecord(request) && typeof request.title === "string" ? request.title : "New thread"; + const text = typeof brief === "string" ? brief.trim() : ""; + sample.threads.set(uuid(n), { title, brief: text }); + return { + threadId: uuid(n), + title, + ...(text ? { runId: `run-${n}`, status: "starting" } : { status: "idle" }), + }; + }; switch (name) { + case "t3_thread_launch": + return newThread(input, input.message); + case "create_threads": + return { + threads: (Array.isArray(input.threads) ? input.threads : []).map((request) => { + const target = isRecord(request) && isRecord(request.target) ? request.target : {}; + return { + ...newThread(request, isRecord(request) ? request.prompt : undefined), + createdBy: "agent", + creationSource: "mcp", + providerInstanceId: + target.providerInstanceId ?? (sample.base.codex ? "codex" : "claudeAgent"), + model: target.model ?? sample.base.model, + }; + }), + }; case "orchestrator_capabilities": return { inheritedProviderInstanceId: "claudeAgent", @@ -1108,6 +1150,20 @@ const t3Default = (sample: Sample, name: string, input: Readonly { return Object.entries(expected).every(([path, value]) => matches(value, at(path))); }; +/** Each new top-level thread request in a run; a failed call created nothing. */ +const newThreadRequests = (calls: ReadonlyArray) => + calls.flatMap((call): ReadonlyArray<{ request: unknown; brief: unknown }> => { + if (call.failed === true || !isRecord(call.input)) return []; + if (call.tool === "t3_thread_launch") + return [{ request: call.input, brief: call.input.message }]; + if (call.tool !== "create_threads" || !Array.isArray(call.input.threads)) return []; + return call.input.threads.map((request: unknown) => ({ + request, + brief: isRecord(request) ? request.prompt : undefined, + })); + }); + +/** Whether every expected value can take a different request it matches. */ +const matchesDistinct = ( + expected: ReadonlyArray, + requests: ReturnType, + taken: ReadonlySet = new Set(), +): boolean => { + const [first, ...rest] = expected; + if (expected.length === 0) return true; + return requests.some( + ({ request, brief }, i) => + !taken.has(i) && + matches(first, typeof first === "string" ? brief : request) && + matchesDistinct(rest, requests, new Set([...taken, i])), + ); +}; + /** delegate_task takes `target.options` as an object or `[{id, value}]`. Grade both as an object. */ const withOptionsObject = (input: unknown) => { if (!isRecord(input) || !isRecord(input.target) || !Array.isArray(input.target.options)) { @@ -1472,6 +1557,13 @@ export const gradeSample = (expect: McpToolUseCase["expect"], run: SampleRun) => add(`minCalls ${t} >= ${n}`, count(t) >= n); for (const [t, n] of Object.entries(expect.maxCalls ?? {})) add(`maxCalls ${t} <= ${n}`, count(t) <= n); + if (expect.newThreads !== undefined) { + const requests = newThreadRequests(calls); + add( + `newThreads ${valueText(expect.newThreads)}`, + requests.length === expect.newThreads.length && matchesDistinct(expect.newThreads, requests), + ); + } if (expect.endsTurnAfter !== undefined) { const lastStep = Math.max(-1, ...calls.map((call) => call.step)); const last = calls.filter((call) => call.step === lastStep).map((call) => call.tool); @@ -2235,7 +2327,7 @@ const main = Effect.gen(function* () { if (import.meta.main) { main.pipe( - Effect.provide(Layer.mergeAll(NodeServices.layer, FetchHttpClient.layer)), + Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, FetchHttpClient.layer)), NodeRuntime.runMain, ); } diff --git a/evals/thread-titles/run.ts b/evals/thread-titles/run.ts index 9195d0ed520a2..2a68f8cfd1cee 100644 --- a/evals/thread-titles/run.ts +++ b/evals/thread-titles/run.ts @@ -3,6 +3,7 @@ import * as NodeUtil from "node:util"; import * as NodeCrypto from "node:crypto"; import * as FetchHttpClient from "effect/http/FetchHttpClient"; +import * as NodePlatformCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { CodexSettings, ProviderInstanceId } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; @@ -153,7 +154,7 @@ await Effect.runPromise( Layer.provideMerge( ServerConfig.layerTest(process.cwd(), { prefix: "t3-title-evaluation-state-" }), ), - Layer.provideMerge(NodeServices.layer), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodePlatformCrypto.layer)), ), ), Effect.scoped, diff --git a/infra/relay/package.json b/infra/relay/package.json index 197c37819981e..d69e71dfa5f01 100644 --- a/infra/relay/package.json +++ b/infra/relay/package.json @@ -30,6 +30,7 @@ "effect": "catalog:" }, "devDependencies": { + "@alchemy.run/test": "catalog:", "@cloudflare/workers-types": "^4.20260601.1", "@effect/platform-node": "catalog:", "@effect/vitest": "catalog:", diff --git a/infra/relay/scripts/android-push-watch.ts b/infra/relay/scripts/android-push-watch.ts index 5ab8b114c8dc9..5f052f58e4c17 100644 --- a/infra/relay/scripts/android-push-watch.ts +++ b/infra/relay/scripts/android-push-watch.ts @@ -1,7 +1,7 @@ // @effect-diagnostics nodeBuiltinImport:off - Local developer verification reads private credential files. import * as NodeFSP from "node:fs/promises"; import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; -import * as NodeSocket from "@effect/platform-node/NodeSocket"; +import * as NodeWS from "@effect/platform-node/NodeWS"; import { ORCHESTRATION_V2_WS_METHODS, WS_METHODS, @@ -89,7 +89,7 @@ const main = Effect.gen(function* () { const layerSocketConstructor = Layer.succeed( Socket.WebSocketConstructor, (url, protocols) => - new NodeSocket.NodeWS.WebSocket(url, protocols as string | string[] | undefined, { + new NodeWS.WebSocket(url, protocols as string | string[] | undefined, { headers: { authorization: `Bearer ${connection.bearerToken}` }, }) as unknown as globalThis.WebSocket, ); diff --git a/infra/relay/src/agentActivity/ApnsDeliveryQueue.ts b/infra/relay/src/agentActivity/ApnsDeliveryQueue.ts index b14183c9d29b4..5b633b0c4e6e6 100644 --- a/infra/relay/src/agentActivity/ApnsDeliveryQueue.ts +++ b/infra/relay/src/agentActivity/ApnsDeliveryQueue.ts @@ -1,6 +1,6 @@ import * as Alchemy from "alchemy"; import * as Cloudflare from "@alchemy.run/cloudflare"; -import * as Crypto from "effect/Crypto"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -78,7 +78,7 @@ export class ApnsDeliveryQueue extends Context.Service< const make = Effect.gen(function* () { const sender = yield* ApnsDeliveryQueueSender; - const crypto = yield* Crypto.Crypto; + const random = yield* SecureRandom.SecureRandom; const config = yield* RelayConfiguration.RelayConfiguration; return ApnsDeliveryQueue.of({ @@ -89,7 +89,7 @@ const make = Effect.gen(function* () { "relay.delivery.kind": input.kind, }); const now = yield* DateTime.now; - const jobId = yield* crypto.randomUUIDv4().pipe( + const jobId = yield* random.uuidV4().pipe( Effect.mapError( (cause) => new ApnsDeliveryQueueSendError({ @@ -148,7 +148,7 @@ const make = Effect.gen(function* () { "relay.thread_id": input.notification.threadId, }); const now = yield* DateTime.now; - const jobId = yield* crypto.randomUUIDv4().pipe( + const jobId = yield* random.uuidV4().pipe( Effect.mapError( (cause) => new ApnsDeliveryQueueSendError({ diff --git a/infra/relay/src/agentActivity/DeliveryAttempts.ts b/infra/relay/src/agentActivity/DeliveryAttempts.ts index 161fa48cbce84..fef33de106d55 100644 --- a/infra/relay/src/agentActivity/DeliveryAttempts.ts +++ b/infra/relay/src/agentActivity/DeliveryAttempts.ts @@ -5,7 +5,7 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import { and, eq, inArray, isNull, lt } from "drizzle-orm"; import { QueryBuilder } from "drizzle-orm/pg-core"; -import * as Crypto from "effect/Crypto"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Schema from "effect/Schema"; import * as RelayDb from "../db.ts"; @@ -97,7 +97,7 @@ function insertValues( const make = Effect.gen(function* () { const db = yield* RelayDb.RelayDb; - const crypto = yield* Crypto.Crypto; + const random = yield* SecureRandom.SecureRandom; const isExpiredClaim = (claimedAt: string | null, now: DateTime.DateTime) => { if (claimedAt === null) { @@ -121,7 +121,7 @@ const make = Effect.gen(function* () { ...(input.threadId ? { "relay.thread_id": input.threadId } : {}), }); return yield* Effect.gen(function* () { - const id = yield* crypto.randomUUIDv4(); + const id = yield* random.uuidV4(); const now = yield* DateTime.now; const createdAt = DateTime.formatIso(now); const inserted = yield* db diff --git a/infra/relay/src/agentActivity/FcmDeliveries.ts b/infra/relay/src/agentActivity/FcmDeliveries.ts index 615840fe27aeb..1c6cc0a6b71ff 100644 --- a/infra/relay/src/agentActivity/FcmDeliveries.ts +++ b/infra/relay/src/agentActivity/FcmDeliveries.ts @@ -5,7 +5,7 @@ import { RelayAgentAwarenessPreferences, type RelayDeliveryResult, } from "@t3tools/contracts/relay"; -import * as Crypto from "effect/Crypto"; +import * as Digest from "effect/crypto/Digest"; import type * as PlatformError from "effect/PlatformError"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; @@ -139,7 +139,7 @@ export class FcmDeliveries extends Context.Service< const make = Effect.gen(function* () { const config = yield* RelayConfiguration.RelayConfiguration; - const crypto = yield* Crypto.Crypto; + const crypto = yield* Digest.Digest; const sender = yield* FcmDeliveryQueueSender.FcmDeliveryQueueSender; const client = yield* FcmClient.FcmClient; const devices = yield* LiveActivities.LiveActivities; @@ -297,7 +297,10 @@ const make = Effect.gen(function* () { }; if (alert) { // Hash the full stable group identity to stay within the payload budget. - const digest = yield* crypto.digest("SHA-256", new TextEncoder().encode(alert.alert_id)); + const digest = yield* crypto.digest( + Digest.sha256, + new TextEncoder().encode(alert.alert_id), + ); data.alert_id = Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join(""); } const result = yield* client.send({ diff --git a/infra/relay/src/clientConfig.test.ts b/infra/relay/src/clientConfig.test.ts index c1c27a77639a2..cf61820a6a2cf 100644 --- a/infra/relay/src/clientConfig.test.ts +++ b/infra/relay/src/clientConfig.test.ts @@ -1,6 +1,6 @@ // @effect-diagnostics anyUnknownInErrorContext:off - ScratchStack.deploy is typed with `any` in its error channel by Alchemy. import { inMemoryState } from "alchemy/State"; -import * as Test from "alchemy/Test/Vitest"; +import * as Test from "@alchemy.run/test/Vitest"; import * as ConfigProvider from "effect/ConfigProvider"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; diff --git a/infra/relay/src/environments/EnvironmentConnector.ts b/infra/relay/src/environments/EnvironmentConnector.ts index 09253cc2cf1fd..ad22b54f9ae3f 100644 --- a/infra/relay/src/environments/EnvironmentConnector.ts +++ b/infra/relay/src/environments/EnvironmentConnector.ts @@ -30,7 +30,7 @@ import { } from "@t3tools/shared/relayJwt"; import { stableStringify } from "@t3tools/shared/relaySigning"; import * as Context from "effect/Context"; -import * as Crypto from "effect/Crypto"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; @@ -386,7 +386,7 @@ const make = Effect.gen(function* () { const allocations = yield* ManagedEndpointAllocations.ManagedEndpointAllocations; const settings = yield* RelayConfiguration.RelayConfiguration; const httpClient = yield* HttpClient.HttpClient; - const crypto = yield* Crypto.Crypto; + const random = yield* SecureRandom.SecureRandom; const relayIssuer = normalizeRelayIssuer(settings.relayIssuer); const makeEnvironmentClient = (httpBaseUrl: string) => makeEnvironmentHttpApiClient(httpBaseUrl).pipe( @@ -444,7 +444,7 @@ const make = Effect.gen(function* () { }); const now = yield* DateTime.now; const expiresAt = DateTime.add(now, { minutes: 2 }); - const nonce = yield* crypto.randomUUIDv4().pipe( + const nonce = yield* random.uuidV4().pipe( Effect.mapError( (cause) => new EnvironmentMintRequestFailed({ @@ -458,7 +458,7 @@ const make = Effect.gen(function* () { iss: relayIssuer, aud: `t3-env:${link.environmentId}`, sub: input.userId, - jti: yield* crypto.randomUUIDv4().pipe( + jti: yield* random.uuidV4().pipe( Effect.mapError( (cause) => new EnvironmentMintRequestFailed({ @@ -606,7 +606,7 @@ const make = Effect.gen(function* () { }); const now = yield* DateTime.now; const expiresAt = DateTime.add(now, { minutes: 2 }); - const nonce = yield* crypto.randomUUIDv4().pipe( + const nonce = yield* random.uuidV4().pipe( Effect.mapError( (cause) => new EnvironmentMintRequestFailed({ @@ -620,7 +620,7 @@ const make = Effect.gen(function* () { iss: relayIssuer, aud: `t3-env:${link.environmentId}`, sub: input.userId, - jti: yield* crypto.randomUUIDv4().pipe( + jti: yield* random.uuidV4().pipe( Effect.mapError( (cause) => new EnvironmentMintRequestFailed({ diff --git a/infra/relay/src/environments/EnvironmentCredentials.ts b/infra/relay/src/environments/EnvironmentCredentials.ts index 86938a47eb8de..de346caf64847 100644 --- a/infra/relay/src/environments/EnvironmentCredentials.ts +++ b/infra/relay/src/environments/EnvironmentCredentials.ts @@ -1,5 +1,6 @@ import * as Context from "effect/Context"; -import * as Crypto from "effect/Crypto"; +import * as Digest from "effect/crypto/Digest"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Base64Url from "effect/encoding/Base64Url"; @@ -83,13 +84,15 @@ export class EnvironmentCredentials extends Context.Service< const make = Effect.gen(function* () { const db = yield* RelayDb.RelayDb; - const crypto = yield* Crypto.Crypto; + const random = yield* SecureRandom.SecureRandom; + const digest = yield* Digest.Digest; const hashToken = (token: string) => - crypto.digest("SHA-256", new TextEncoder().encode(token)).pipe(Effect.map(Base64Url.encode)); + digest + .digest(Digest.sha256, new TextEncoder().encode(token)) + .pipe(Effect.map(Base64Url.encode)); const randomTokenPart = (segments: number) => - Effect.map( - Effect.all(Array.from({ length: segments }, () => crypto.randomUUIDv4())), - (values) => values.join("").replaceAll("-", ""), + Effect.map(Effect.all(Array.from({ length: segments }, () => random.uuidV4())), (values) => + values.join("").replaceAll("-", ""), ); const makeCredential = Effect.fnUntraced(function* () { const credentialId = yield* randomTokenPart(2); diff --git a/infra/relay/src/environments/EnvironmentPublishSignatures.test.ts b/infra/relay/src/environments/EnvironmentPublishSignatures.test.ts index bf96390d8d42d..e50e61810aad3 100644 --- a/infra/relay/src/environments/EnvironmentPublishSignatures.test.ts +++ b/infra/relay/src/environments/EnvironmentPublishSignatures.test.ts @@ -1,5 +1,6 @@ // @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"; import * as NodeServices from "@effect/platform-node/NodeServices"; import type { RelayAgentActivityPublishProofPayload, @@ -98,7 +99,7 @@ function layer(replay?: Partial) { }), ), ), - Layer.provideMerge(NodeServices.layer), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCryptoLayer.layer)), ); } diff --git a/infra/relay/src/environments/EnvironmentPublishSignatures.ts b/infra/relay/src/environments/EnvironmentPublishSignatures.ts index 4c89bff5342b0..5206f6f482a86 100644 --- a/infra/relay/src/environments/EnvironmentPublishSignatures.ts +++ b/infra/relay/src/environments/EnvironmentPublishSignatures.ts @@ -11,7 +11,7 @@ import { } from "@t3tools/shared/relayJwt"; import { stableStringify } from "@t3tools/shared/relaySigning"; import * as Context from "effect/Context"; -import * as Crypto from "effect/Crypto"; +import * as Digest from "effect/crypto/Digest"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Base64Url from "effect/encoding/Base64Url"; @@ -93,7 +93,7 @@ const formatEnvironmentPublishReplayThumbprint = (digest: Uint8Array) => const make = Effect.gen(function* () { const proofReplay = yield* DpopProofs.DpopProofReplay; const config = yield* RelayConfiguration.RelayConfiguration; - const crypto = yield* Crypto.Crypto; + const crypto = yield* Digest.Digest; return EnvironmentPublishSignatures.of({ verify: Effect.fn("relay.environment_publish_signatures.verify")(function* (input) { @@ -170,7 +170,7 @@ const make = Effect.gen(function* () { } const thumbprint = yield* crypto .digest( - "SHA-256", + Digest.sha256, environmentPublishReplayThumbprintData({ environmentId: input.environmentId, environmentPublicKey: input.environmentPublicKey, diff --git a/infra/relay/src/environments/ManagedEndpointProvider.test.ts b/infra/relay/src/environments/ManagedEndpointProvider.test.ts index faa3ae637aecf..ea3e8d3e2b233 100644 --- a/infra/relay/src/environments/ManagedEndpointProvider.test.ts +++ b/infra/relay/src/environments/ManagedEndpointProvider.test.ts @@ -1,3 +1,4 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { describe, expect, it } from "@effect/vitest"; @@ -365,7 +366,7 @@ function layerProvider( tunnelLimits = makeTunnelLimits(), ) { return ManagedEndpointProvider.layer.pipe( - Layer.provideMerge(NodeServices.layer), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), Layer.provide(RelayConfiguration.layer(config)), Layer.provide(ManagedEndpointProvider.layerTunnelClient(tunnelClient)), Layer.provide(ManagedEndpointProvider.layerDnsClient(dnsClient)), @@ -751,7 +752,7 @@ describe("ManagedEndpointProvider", () => { {} as Cloudflare.DNS.ReadWriteDnsClient, {} as Alchemy.BaseRuntimeContext, ).pipe( - Layer.provideMerge(NodeServices.layer), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), Layer.provide(RelayConfiguration.layer(config)), Layer.provide( Layer.succeed(ManagedEndpointAllocations.ManagedEndpointAllocations, makeAllocations()), diff --git a/infra/relay/src/environments/ManagedEndpointProvider.ts b/infra/relay/src/environments/ManagedEndpointProvider.ts index 2c2c955abbbfa..0f8a99ceb44e6 100644 --- a/infra/relay/src/environments/ManagedEndpointProvider.ts +++ b/infra/relay/src/environments/ManagedEndpointProvider.ts @@ -5,7 +5,7 @@ import * as Arr from "effect/Array"; import * as Cause from "effect/Cause"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; -import * as Crypto from "effect/Crypto"; +import * as Digest from "effect/crypto/Digest"; import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; @@ -552,7 +552,7 @@ const ignoreNotFound = ( const make = Effect.gen(function* () { const config = yield* RelayConfiguration.RelayConfiguration; - const crypto = yield* Crypto.Crypto; + const digest = yield* Digest.Digest; const tunnels = yield* ManagedEndpointTunnelClient; const dns = yield* ManagedEndpointDnsClient; const allocations = yield* ManagedEndpointAllocations.ManagedEndpointAllocations; @@ -1173,9 +1173,9 @@ const make = Effect.gen(function* () { }); } const cf = yield* requireCloudflareSettings(config, input); - const environmentHash = yield* crypto + const environmentHash = yield* digest .digest( - "SHA-256", + Digest.sha256, new TextEncoder().encode( managedEndpointDigestInput(cf.namespace, input.userId, input.environmentId), ), diff --git a/infra/relay/src/hooks/HookForwarder.ts b/infra/relay/src/hooks/HookForwarder.ts index 034a953863c26..d93c6b4074672 100644 --- a/infra/relay/src/hooks/HookForwarder.ts +++ b/infra/relay/src/hooks/HookForwarder.ts @@ -1,6 +1,6 @@ import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; -import * as Crypto from "effect/Crypto"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -219,7 +219,7 @@ const make = Effect.gen(function* () { const httpClient = yield* HttpClient.HttpClient; const rateLimiter = yield* HookRateLimiter; const inbox = yield* HookInbox.HookInbox; - const crypto = yield* Crypto.Crypto; + const random = yield* SecureRandom.SecureRandom; const signDeliveryProof = Effect.fn("HookForwarder.signDeliveryProof")( function* (input: { @@ -318,14 +318,14 @@ const make = Effect.gen(function* () { // Reuse one delivery ID so inbox retries cannot rerun requests that reached the environment before timeout. yield* Effect.annotateCurrentSpan({ "relay.hook.body_bytes": body.success.byteLength }); - const deliveryId = yield* crypto.randomUUIDv4().pipe(Effect.orDie); + const deliveryId = yield* random.uuidV4(); // Sign once before storing held requests so the inbox needs no signing key. const proof = yield* signDeliveryProof({ environmentId: endpoint.environmentId, deliveryId, receivedAt, hookId: parsed.hookId, - jti: yield* crypto.randomUUIDv4().pipe(Effect.orDie), + jti: yield* random.uuidV4(), }); const hook = { id: deliveryId, diff --git a/infra/relay/src/http/Api.ts b/infra/relay/src/http/Api.ts index 390f3c18f785f..902ace8c56d92 100644 --- a/infra/relay/src/http/Api.ts +++ b/infra/relay/src/http/Api.ts @@ -1,6 +1,6 @@ import { createClerkClient, verifyToken } from "@clerk/backend"; import { sql as drizzleSql } from "drizzle-orm"; -import * as Crypto from "effect/Crypto"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; @@ -819,7 +819,7 @@ export const layerClientApi = HttpApiBuilder.group( "client", Effect.fnUntraced(function* (handlers) { const config = yield* RelayConfiguration.RelayConfiguration; - const crypto = yield* Crypto.Crypto; + const random = yield* SecureRandom.SecureRandom; const relayTokens = yield* RelayTokens.RelayTokens; const linker = yield* EnvironmentLinker.EnvironmentLinker; const links = yield* EnvironmentLinks.EnvironmentLinks; @@ -945,9 +945,7 @@ export const layerClientApi = HttpApiBuilder.group( const { userId } = yield* RelayClientPrincipal; const now = yield* DateTime.now; const expiresAt = DateTime.add(now, { minutes: 5 }); - const jti = yield* crypto - .randomUUIDv4() - .pipe(Effect.catch(() => relayInternalErrorResponse("internal_error"))); + const jti = yield* random.uuidV4(); const challenge = yield* relayTokens .issueLinkChallenge({ userId, @@ -1045,7 +1043,7 @@ export const layerTokenApi = HttpApiBuilder.group( "token", Effect.fnUntraced(function* (handlers) { const config = yield* RelayConfiguration.RelayConfiguration; - const crypto = yield* Crypto.Crypto; + const random = yield* SecureRandom.SecureRandom; const dpopProofs = yield* DpopProofs.DpopProofReplay; const relayTokens = yield* RelayTokens.RelayTokens; return handlers.handle( @@ -1077,9 +1075,7 @@ export const layerTokenApi = HttpApiBuilder.group( ); const now = yield* DateTime.now; const expiresAt = DateTime.addDuration(now, RelayTokens.RELAY_DPOP_ACCESS_TOKEN_TTL); - const jti = yield* crypto - .randomUUIDv4() - .pipe(Effect.catch(() => relayInternalErrorResponse("internal_error"))); + const jti = yield* random.uuidV4(); return { access_token: yield* relayTokens .issueDpopAccessToken({ diff --git a/infra/relay/src/worker.ts b/infra/relay/src/worker.ts index d59fc2f6c9189..08b5cf1f7ab30 100644 --- a/infra/relay/src/worker.ts +++ b/infra/relay/src/worker.ts @@ -5,7 +5,8 @@ import * as Drizzle from "@alchemy.run/drizzle/Postgres"; import * as Config from "effect/Config"; import * as Cause from "effect/Cause"; import * as DateTime from "effect/DateTime"; -import * as Crypto from "effect/Crypto"; +import * as Digest from "effect/crypto/Digest"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; @@ -72,18 +73,7 @@ import * as HookInbox from "./hooks/HookInbox.ts"; import * as HookInboxObject from "./hooks/HookInboxObject.ts"; import * as MobileTelemetry from "./mobileTelemetry/MobileTelemetry.ts"; -const layerWebcrypto = Layer.succeed( - Crypto.Crypto, - Crypto.make({ - randomBytes: (size) => globalThis.crypto.getRandomValues(new Uint8Array(size)), - digest: (algorithm, data) => - Effect.promise(async () => { - const input = new Uint8Array(data.length); - input.set(data); - return new Uint8Array(await globalThis.crypto.subtle.digest(algorithm, input.buffer)); - }), - }), -); +const layerWebcrypto = Layer.mergeAll(SecureRandom.layerWebCrypto, Digest.layerWebCrypto); const layerHttpPlatformNotSupported = Layer.succeed(HttpPlatform.HttpPlatform, { platform: "web", diff --git a/infra/task-cache/scripts/manage.ts b/infra/task-cache/scripts/manage.ts index 212d633cadd1e..8be04a4799149 100644 --- a/infra/task-cache/scripts/manage.ts +++ b/infra/task-cache/scripts/manage.ts @@ -1,3 +1,4 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; import * as NodeServices from "@effect/platform-node/NodeServices"; import * as ChildProcess from "effect/process/ChildProcess"; @@ -67,6 +68,10 @@ const command = Command.make("task-cache").pipe( ); Command.run(command, { version: "1.0.0" }).pipe( - Effect.provide(WriterRegistry.layer.pipe(Layer.provideMerge(NodeServices.layer))), + Effect.provide( + WriterRegistry.layer.pipe( + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ), NodeRuntime.runMain, ); diff --git a/infra/task-cache/src/WriterRegistry.test.ts b/infra/task-cache/src/WriterRegistry.test.ts index 449bdf5b13270..a754a407c5a88 100644 --- a/infra/task-cache/src/WriterRegistry.test.ts +++ b/infra/task-cache/src/WriterRegistry.test.ts @@ -1,3 +1,4 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { expect, it } from "@effect/vitest"; import * as Config from "effect/Config"; @@ -29,7 +30,7 @@ it.effect("loads the private writer registry as deployment configuration", () => Effect.provide(ConfigProvider.layer(ConfigProvider.fromUnknown({ HOME: home }))), ); expect(JSON.parse(Redacted.value(keys))).toEqual({ maria: "digest" }); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect("uses explicit deployment credentials without requiring a local registry", () => @@ -42,7 +43,7 @@ it.effect("uses explicit deployment credentials without requiring a local regist ), ); expect(JSON.parse(Redacted.value(keys))).toEqual({ theo: "digest" }); - }).pipe(Effect.provide(NodeServices.layer)), + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect("fails instead of deploying an empty registry when credentials are missing", () => @@ -54,7 +55,7 @@ it.effect("fails instead of deploying an empty registry when credentials are mis Effect.exit, ); expect(Exit.isFailure(result)).toBe(true); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.live("rejects reserved writer names without modifying credential stores", () => @@ -85,7 +86,7 @@ it.live("rejects reserved writer names without modifying credential stores", () expect(yield* fs.readFileString(`${state}/writers.json`)).toBe(writers); expect(yield* fs.readFileString(`${state}/credentials.json`)).toBe(credentials); } - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect("writes credentials for the supplied deployed worker endpoint", () => @@ -106,7 +107,7 @@ it.effect("writes credentials for the supplied deployed worker endpoint", () => const credential = JSON.parse(yield* fs.readFileString(file)); expect(credential.endpoint).toBe(endpoint); expect(credential.name).toBe("maria"); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect("refuses a concurrent registry update without changing committed credentials", () => @@ -128,7 +129,7 @@ it.effect("refuses a concurrent registry update without changing committed crede expect(Exit.isFailure(result)).toBe(true); expect(yield* fs.readFileString(`${state}/writers.json`)).toBe('{"maria":"digest"}'); expect(yield* fs.exists(`${state}/theo.json`)).toBe(false); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect("keeps the committed registry intact if a replacement write fails", () => @@ -160,7 +161,7 @@ it.effect("keeps the committed registry intact if a replacement write fails", () expect(Exit.isFailure(result)).toBe(true); expect(yield* fs.readFileString(`${state}/writers.json`)).toBe(original); expect(yield* fs.exists(`${state}/writers.lock`)).toBe(false); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect("preserves filesystem errors when acquiring the registry lock", () => @@ -191,7 +192,7 @@ it.effect("preserves filesystem errors when acquiring the registry lock", () => Effect.flip, ); expect(error).toBe(denied); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect("refuses to initialize a missing writer registry implicitly", () => @@ -209,7 +210,7 @@ it.effect("refuses to initialize a missing writer registry implicitly", () => ); expect(Exit.isFailure(result)).toBe(true); expect(yield* fs.exists(`${home}/.config/t3-task-cache/writers.json`)).toBe(false); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect("keeps existing authorization if credential publication fails", () => @@ -243,5 +244,5 @@ it.effect("keeps existing authorization if credential publication fails", () => ); expect(Exit.isFailure(result)).toBe(true); expect(yield* fs.readFileString(`${state}/writers.json`)).toBe(original); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); diff --git a/infra/task-cache/src/WriterRegistry.ts b/infra/task-cache/src/WriterRegistry.ts index 0032f66e292d1..05411dce3cfa7 100644 --- a/infra/task-cache/src/WriterRegistry.ts +++ b/infra/task-cache/src/WriterRegistry.ts @@ -1,6 +1,7 @@ import * as Config from "effect/Config"; import * as Context from "effect/Context"; -import * as Crypto from "effect/Crypto"; +import * as Digest from "effect/crypto/Digest"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import type * as PlatformError from "effect/PlatformError"; @@ -47,7 +48,8 @@ export class WriterRegistry extends Context.Service< const make = Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; - const crypto = yield* Crypto.Crypto; + const random = yield* SecureRandom.SecureRandom; + const digest = yield* Digest.Digest; const state = yield* stateDirectory; const readWriters = Effect.fn("TaskCache.readWriters")(function* () { return yield* decodeWriters(yield* fs.readFileString(`${state}/writers.json`)); @@ -105,10 +107,10 @@ const make = Effect.gen(function* () { "Writer registry is missing. Copy the existing private registry from its administrator; use --new-registry only when creating a new cache.", }); const writers = { ...(exists || revoke ? yield* readWriters() : {}) }; - const token = hex(yield* crypto.randomBytes(32)); + const token = hex(yield* random.randomBytes(32)); if (revoke) delete writers[name]; else { - writers[name] = hex(yield* crypto.digest("SHA-256", new TextEncoder().encode(token))); + writers[name] = hex(yield* digest.digest(Digest.sha256, new TextEncoder().encode(token))); } const entries: Array = []; if (!revoke && endpoint) diff --git a/knip.jsonc b/knip.jsonc index e7289c39147dc..1190e54c57b6e 100644 --- a/knip.jsonc +++ b/knip.jsonc @@ -20,7 +20,7 @@ // Knip loads its preprocessor through a CLI option; native verification and // worktree setup (from t3.json) run directly. release-desktop.yml bundles the // Windows verify script with esbuild through a path knip does not trace, - // electron-builder loads the macOS signer by path, and mobile-e2e.ts runs + // electron-builder loads the macOS signer and the Linux afterPack hook by path, and mobile-e2e.ts runs // agent-device's CLI by path, and mobile-behavior.ts spawns its runner by path. // release-desktop.yml runs the desktop launch check through xvfb-run, which knip // does not trace. @@ -28,6 +28,7 @@ // These fixture scripts are injected into a browser page by path. "fixtures/*/*.js", "knip-schemas.ts", + "linux-after-pack.ts", "mobile-behavior/run.ts", "mobile-native-client.ts", "setup-worktree.ts", diff --git a/package.json b/package.json index 6383d4fd917d9..62118d63901e2 100644 --- a/package.json +++ b/package.json @@ -30,7 +30,7 @@ "report:renders": "node scripts/render-metrics.ts", "lint": "vp lint --report-unused-disable-directives", "knip": "knip --preprocessor ./scripts/knip-schemas.ts", - "knip:check": "knip --include files,dependencies --no-config-hints && knip --workspace apps/server --workspace apps/desktop --workspace apps/web --workspace packages/client-runtime --workspace packages/contracts --workspace packages/effect-acp --workspace packages/effect-codex-app-server --workspace packages/shared --workspace packages/ssh --workspace packages/tailscale --workspace packages/provider-core --workspace packages/provider-acp --workspace packages/provider-acp-registry --workspace packages/provider-testing --workspace packages/provider-pi --workspace packages/provider-muse --workspace packages/provider-opencode --workspace packages/provider-cursor --workspace packages/provider-fx --workspace packages/provider-grok --workspace packages/secret-provider-core --workspace packages/secret-provider-definitions --workspace packages/secret-provider-onepassword --workspace packages/source-control-core --workspace packages/source-control-definitions --workspace packages/source-control-azure-devops --workspace packages/source-control-bitbucket --workspace packages/source-control-forgejo --workspace packages/source-control-gitcafe --workspace packages/source-control-github --workspace packages/source-control-gitlab --workspace packages/source-control-testing --exports --preprocessor ./scripts/knip-schemas.ts --no-config-hints", + "knip:check": "knip --include files,dependencies --no-config-hints && knip --workspace apps/server --workspace apps/desktop --workspace apps/web --workspace packages/client-runtime --workspace packages/contracts --workspace packages/effect-acp --workspace packages/effect-codex-app-server --workspace packages/shared --workspace packages/ssh --workspace packages/tailscale --workspace packages/provider-core --workspace packages/provider-acp --workspace packages/provider-acp-registry --workspace packages/provider-testing --workspace packages/provider-pi --workspace packages/provider-muse --workspace packages/provider-opencode --workspace packages/provider-cursor --workspace packages/provider-fx --workspace packages/provider-grok --workspace packages/provider-kiro --workspace packages/secret-provider-core --workspace packages/secret-provider-definitions --workspace packages/secret-provider-onepassword --workspace packages/source-control-core --workspace packages/source-control-definitions --workspace packages/source-control-azure-devops --workspace packages/source-control-bitbucket --workspace packages/source-control-forgejo --workspace packages/source-control-gitcafe --workspace packages/source-control-github --workspace packages/source-control-gitlab --workspace packages/source-control-testing --exports --preprocessor ./scripts/knip-schemas.ts --no-config-hints", "knip:production": "knip --production --preprocessor ./scripts/knip-schemas.ts", "lint:mobile": "node scripts/mobile-native-static-check.ts", "mobile:install": "node scripts/mobile-native-client.ts ensure", diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index 2ccc8edfb46a4..013e228cd959f 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -544,6 +544,7 @@ "@t3tools/provider-cursor": "workspace:*", "@t3tools/provider-fx": "workspace:*", "@t3tools/provider-grok": "workspace:*", + "@t3tools/provider-kiro": "workspace:*", "@t3tools/provider-muse": "workspace:*", "@t3tools/provider-opencode": "workspace:*", "@t3tools/provider-pi": "workspace:*", diff --git a/packages/client-runtime/src/connection/diagnosis.test.ts b/packages/client-runtime/src/connection/diagnosis.test.ts index 5d396888eb593..93cc54bd044d0 100644 --- a/packages/client-runtime/src/connection/diagnosis.test.ts +++ b/packages/client-runtime/src/connection/diagnosis.test.ts @@ -8,6 +8,8 @@ import { presentConnectionDiagnosis } from "./diagnosis.ts"; import { mapManagedRelayError, mapRemoteEnvironmentError } from "./errors.ts"; import { AVAILABLE_CONNECTION_STATE, + ConnectionBlockedError, + ConnectionTransientError, type ConnectionAttemptError, type SupervisorConnectionState, } from "./model.ts"; @@ -128,6 +130,30 @@ describe("presentConnectionDiagnosis", () => { expect(origin?.hops.map((hop) => hop.hop)).toEqual(["device", "relay", "tunnel", "server"]); }); + it("blames this device, not the host, while its own T3 Connect sign-in loads", () => { + const failure = new ConnectionTransientError({ + reason: "session-pending", + detail: "Waiting for the T3 Connect sign-in to load.", + }); + const diagnosis = diagnose(backoff(failure)); + expect(diagnosis?.headline).not.toContain("did not answer"); + expect(diagnosis?.hops.find((hop) => hop.result === "failed")?.hop).toBe("device"); + expect(diagnosis?.steps.join(" ")).not.toContain("Mac mini"); + expect(diagnosis?.moreInfoUrl).toContain("sign-in-account-or-link-problems"); + // A host with a LAN route as well uses the direct route, still authorized through T3 Connect. + expect(diagnose(backoff(failure), "direct")?.moreInfoUrl).toContain( + "sign-in-account-or-link-problems", + ); + }); + + it("does not report hops as working when the failure names none", () => { + const failure = new ConnectionBlockedError({ + reason: "authentication", + detail: "Your cloud sign-in changed. Sign in again to authorize the environment.", + }); + expect(results(backoff(failure))).not.toContainEqual(expect.stringMatching(/:ok$/)); + }); + it("keeps the relay health status out of a failure that has its own cause", () => { const failure = mapRemoteEnvironmentError( new RemoteEnvironmentAuthFetchError({ message: "Failed to fetch", cause: new TypeError() }), diff --git a/packages/client-runtime/src/connection/diagnosis.ts b/packages/client-runtime/src/connection/diagnosis.ts index a3de100766a7c..4272943e0daa9 100644 --- a/packages/client-runtime/src/connection/diagnosis.ts +++ b/packages/client-runtime/src/connection/diagnosis.ts @@ -26,7 +26,7 @@ export interface ConnectionDiagnosis { readonly hops: ReadonlyArray; readonly steps: ReadonlyArray; readonly facts: ReadonlyArray; - /** The troubleshooting guide section for this failure. Null for direct routes. */ + /** The troubleshooting guide section for this failure. Null for direct routes, except a pending T3 Connect sign-in. */ readonly moreInfoUrl: string | null; } @@ -46,7 +46,15 @@ export interface ConnectionDiagnosisInput { interface Located { readonly hop: ConnectionHop; - readonly cause: ConnectionFailureCause | "offline" | "outdated" | "released" | null; + readonly cause: + | ConnectionFailureCause + | "offline" + | "outdated" + | "released" + | "session_pending" + | null; + /** The failure named no hop, so the hops before this one were never probed. */ + readonly guessed?: true; } const NOT_ANSWERING: ReadonlySet = new Set([ @@ -62,6 +70,9 @@ function locate(input: ConnectionDiagnosisInput): Located | null { if (failure?._tag === "ConnectionBlockedError" && failure.serverUpdateRequired) { return { hop: "server", cause: "outdated" }; } + if (failure?.reason === "session-pending") { + return { hop: "device", cause: "session_pending" }; + } if (failure?.hop !== undefined) { return { hop: failure.hop, cause: failure.failureCause ?? null }; } @@ -71,7 +82,11 @@ function locate(input: ConnectionDiagnosisInput): Located | null { failure.reason === "timeout" || failure.reason === "transport"; const via = failure.via ?? input.via; - return { hop: unreachable && via === "relay" ? "tunnel" : "server", cause: null }; + return { + hop: unreachable && via === "relay" ? "tunnel" : "server", + cause: null, + guessed: true, + }; } const status = input.relayStatus; if (status?.status !== "offline") return null; @@ -84,6 +99,8 @@ function headline(host: string, located: Located, failure: ConnectionAttemptErro switch (located.cause) { case "offline": return "This device is offline"; + case "session_pending": + return "This device is still loading its T3 Connect sign-in"; case "outdated": return `${host} runs an older T3 Code`; case "clock_skew": @@ -141,6 +158,11 @@ function steps(host: string, located: Located, failure: ConnectionAttemptError | switch (located.cause) { case "offline": return ["Connect this device to the internet. T3 Code reconnects on its own."]; + case "session_pending": + return [ + "Wait a moment. T3 Code retries on its own.", + "If it keeps waiting, reload or restart T3 Code on this device.", + ]; case "outdated": return [`Update T3 Code on ${host}.`]; case "clock_skew": @@ -220,6 +242,7 @@ function helpSection( return "the-host-runs-an-older-t3-code"; case "clock_skew": return "the-clock-is-off"; + case "session_pending": case "not_linked": case "tunnel_not_enabled": return "sign-in-account-or-link-problems"; @@ -300,7 +323,12 @@ export function presentConnectionDiagnosis( const hops = order.map((hop, index): ConnectionDiagnosisHop => ({ hop, label: hopLabel(hop, host), - result: index < failedIndex ? "ok" : index === failedIndex ? "failed" : "unchecked", + result: + index === failedIndex + ? "failed" + : index < failedIndex && located.guessed !== true + ? "ok" + : "unchecked", })); // The relay health check only explains the state when no attempt has failed yet. @@ -329,7 +357,10 @@ export function presentConnectionDiagnosis( hops, steps: steps(host, located, failure), facts, - moreInfoUrl: relayPath ? t3ConnectTroubleshootingUrl(helpSection(located, failure)) : null, + moreInfoUrl: + relayPath || located.cause === "session_pending" + ? t3ConnectTroubleshootingUrl(helpSection(located, failure)) + : null, }; } diff --git a/packages/client-runtime/src/connection/registry.test.ts b/packages/client-runtime/src/connection/registry.test.ts index e10d57ab5e854..4950de0124776 100644 --- a/packages/client-runtime/src/connection/registry.test.ts +++ b/packages/client-runtime/src/connection/registry.test.ts @@ -418,7 +418,13 @@ const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* ( ? Effect.die(new Error("Config is not used by registry tests.")) : Effect.succeed({ directEndpoints: options.directEndpoints } as ServerConfig), subscribeServerConfig: () => - Stream.die(new Error("Config is not used by registry tests.")), + options?.directEndpoints === undefined + ? Stream.never + : Stream.make({ + version: 1 as const, + type: "snapshot" as const, + config: { directEndpoints: options.directEndpoints } as ServerConfig, + }), ready: Effect.void, probe: Effect.void, inboundFrames: Effect.succeed(0), diff --git a/packages/client-runtime/src/connection/supervisor.test.ts b/packages/client-runtime/src/connection/supervisor.test.ts index 66d151043b115..eede2763291e3 100644 --- a/packages/client-runtime/src/connection/supervisor.test.ts +++ b/packages/client-runtime/src/connection/supervisor.test.ts @@ -1,4 +1,9 @@ -import { AuthStandardClientScopes, EnvironmentId, type ServerConfig } from "@t3tools/contracts"; +import { + AuthStandardClientScopes, + EnvironmentId, + type ServerConfig, + type ServerConfigStreamEvent, +} from "@t3tools/contracts"; import { describe, expect, it } from "@effect/vitest"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; @@ -79,7 +84,7 @@ const LAN_TARGET = new BearerConnectionTarget({ label: TARGET.label, connectionId: "bearer:lan", }); -const LAN_ROUTE: ConnectionRoute = { +const LAN_ROUTE = { target: LAN_TARGET, profile: Option.some( new BearerConnectionProfile({ @@ -90,7 +95,7 @@ const LAN_ROUTE: ConnectionRoute = { wsBaseUrl: "ws://192.168.1.10:3773/", }), ), -}; +} satisfies ConnectionRoute; const LAN_THEN_RELAY_ENTRY: ConnectionCatalogEntry = { target: LAN_ROUTE.target, profile: LAN_ROUTE.profile, @@ -145,6 +150,7 @@ const makeHarness = Effect.fn("TestConnectionHarness.make")(function* (options?: ) => Effect.Effect; readonly ready?: (attempt: number) => Effect.Effect; readonly probe?: (attempt: number) => Effect.Effect; + readonly configEvents?: Stream.Stream | undefined; readonly initialConfig?: (attempt: number) => Effect.Effect; readonly checkRoute?: (route: ConnectionRoute) => Effect.Effect; readonly checkHost?: (prepared: PreparedConnection) => Effect.Effect; @@ -201,7 +207,13 @@ const makeHarness = Effect.fn("TestConnectionHarness.make")(function* (options?: initialConfig: options?.initialConfig?.(attempt) ?? Effect.die(new Error("Initial config is not used by supervisor tests.")), - subscribeServerConfig: (input) => TEST_RPC_CLIENT.subscribeServerConfig(input), + subscribeServerConfig: () => + options?.configEvents ?? + Stream.fromEffect( + (options?.initialConfig?.(attempt) ?? Effect.never).pipe(Effect.orDie), + ).pipe( + Stream.map((config) => ({ version: 1 as const, type: "snapshot" as const, config })), + ), ready: options?.ready?.(attempt) ?? Effect.void, probe: options?.probe?.(attempt) ?? Effect.void, inboundFrames: options?.inboundFrames ?? Effect.succeed(0), @@ -1789,62 +1801,134 @@ describe("EnvironmentSupervisor routes", () => { }), ); - it.effect("learns the LAN address over T3 Connect and moves to it", () => - Effect.gen(function* () { - const relayEntry: ConnectionCatalogEntry = { - target: RELAY_TARGET, - profile: Option.none(), - enabled: true, - }; - const lanAddress = yield* Ref.make("http://192.168.1.10:3773/"); - const learned = yield* Ref.make>([]); - const harness = yield* makeHarness({ - checkRoute: (route) => - route.target._tag === "BearerConnectionTarget" - ? Effect.succeed("answered") - : Effect.succeed("unchecked"), - prepare: (_attempt, target) => Effect.succeed(preparedFor(target)), - initialConfig: () => - Ref.get(lanAddress).pipe( - Effect.map((httpBaseUrl): Pick => ({ - directEndpoints: [{ kind: "lan", httpBaseUrl }], - })), - Effect.map((config) => config as ServerConfig), - ), - }); - const current = yield* Ref.make(relayEntry); - const supervisor = yield* EnvironmentSupervisor.make(relayEntry, { - initiallyDesired: true, - learnRoutes: ({ activeRoute, reported }) => - Effect.gen(function* () { - const entry = yield* Ref.get(current); - const routes = mergeLearnedRoutes({ - entry, - activeRoute, - reported, - allowInsecure: true, - }); - if (routes === null) return Option.none(); - const next = entryWithRoutes(entry, routes); - yield* Ref.set(current, next); - yield* Ref.update(learned, (all) => [ - ...all, - ...routes.filter(isLearned).map((route) => connectionRouteId(route.target)), - ]); - return Option.some(next); - }), - }).pipe(Effect.provide(harness.dependencies)); + it.effect.each(["initial", "late", "withdrawn", "withdrawn-upgrade", "omitted"] as const)( + "learns the %s direct endpoint over T3 Connect", + (discovery) => + Effect.gen(function* () { + const relayEntry: ConnectionCatalogEntry = + discovery.startsWith("withdrawn") || discovery === "omitted" + ? { + target: LAN_ROUTE.target, + profile: Option.some( + new BearerConnectionProfile({ + ...Option.getOrThrow(LAN_ROUTE.profile), + ...(discovery === "withdrawn-upgrade" + ? { + httpBaseUrl: "https://old.example.test/", + wsBaseUrl: "wss://old.example.test/", + } + : {}), + learned: true, + authorization: "t3-connect", + }), + ), + alternateRoutes: [{ target: RELAY_TARGET, profile: Option.none() }], + enabled: true, + } + : { + target: RELAY_TARGET, + profile: Option.none(), + enabled: true, + }; + const initialProcessed = yield* Deferred.make(); + const discoveryProcessed = yield* Deferred.make(); + const discoveryStarted = yield* Deferred.make(); + const finishDiscovery = yield* Deferred.make(); + const lateAddress = "https://fixture.tail1234.ts.net/"; + const learned = yield* Ref.make>([]); + const harness = yield* makeHarness({ + configEvents: + discovery !== "initial" + ? Stream.concat( + Stream.make({ + version: 1 as const, + type: "snapshot" as const, + config: (discovery === "omitted" + ? {} + : { directEndpoints: [] }) as unknown as ServerConfig, + }).pipe(Stream.ensuring(Deferred.succeed(initialProcessed, undefined))), + Stream.fromEffect( + Deferred.await(finishDiscovery).pipe( + Effect.as({ + version: 1 as const, + type: "snapshot" as const, + config: { + directEndpoints: [{ kind: "tailnet", httpBaseUrl: lateAddress }], + } as unknown as ServerConfig, + }), + ), + ), + ).pipe(Stream.ensuring(Deferred.succeed(discoveryProcessed, undefined))) + : undefined, + checkRoute: (route) => + route.target._tag === "BearerConnectionTarget" + ? Effect.succeed("answered") + : Effect.succeed("unchecked"), + prepare: (_attempt, target) => Effect.succeed(preparedFor(target)), + initialConfig: () => + Effect.succeed({ + directEndpoints: + discovery !== "initial" + ? [] + : [{ kind: "lan", httpBaseUrl: "http://192.168.1.10:3773/" }], + } as unknown as ServerConfig), + }); + const current = yield* Ref.make(relayEntry); + const supervisor = yield* EnvironmentSupervisor.make(relayEntry, { + initiallyDesired: true, + learnRoutes: ({ activeRoute, reported }) => + Effect.gen(function* () { + yield* Deferred.succeed(discoveryStarted, undefined); + const entry = yield* Ref.get(current); + const routes = mergeLearnedRoutes({ + entry, + activeRoute, + reported, + allowInsecure: true, + }); + if (routes === null) return Option.none(); + const next = entryWithRoutes(entry, routes); + yield* Ref.set(current, next); + yield* Ref.update(learned, (all) => [ + ...all, + ...routes.filter(isLearned).map((route) => connectionRouteId(route.target)), + ]); + return Option.some(next); + }), + }).pipe(Effect.provide(harness.dependencies)); - yield* awaitState( - supervisor.state, - (state) => state.phase === "connected" && state.generation === 2, - ); - expect(Option.getOrThrow(yield* SubscriptionRef.get(supervisor.prepared)).target._tag).toBe( - "BearerConnectionTarget", - ); - expect(yield* Ref.get(learned)).toEqual([ - `learned:${TARGET.environmentId}:http://192.168.1.10:3773`, - ]); - }), + if (discovery === "omitted") { + yield* Deferred.await(initialProcessed); + expect(yield* Ref.get(current)).toEqual(relayEntry); + expect(yield* Ref.get(learned)).toEqual([]); + } else { + yield* Deferred.await(discoveryStarted); + } + yield* Deferred.succeed(finishDiscovery, undefined); + if (discovery === "withdrawn-upgrade") { + yield* Deferred.await(discoveryProcessed); + yield* TestClock.adjust("60 seconds"); + expect((yield* SubscriptionRef.get(supervisor.state)).generation).toBe(2); + return; + } + if (discovery === "withdrawn" || discovery === "omitted") { + yield* Deferred.await(discoveryProcessed); + expect(yield* Ref.get(learned)).toContain( + `learned:${TARGET.environmentId}:https://fixture.tail1234.ts.net`, + ); + expect((yield* SubscriptionRef.get(supervisor.state)).generation).toBe(1); + return; + } + yield* awaitState( + supervisor.state, + (state) => state.phase === "connected" && state.generation === 2, + ); + expect(Option.getOrThrow(yield* SubscriptionRef.get(supervisor.prepared)).target._tag).toBe( + "BearerConnectionTarget", + ); + expect(yield* Ref.get(learned)).toEqual([ + `learned:${TARGET.environmentId}:${discovery !== "initial" ? "https://fixture.tail1234.ts.net" : "http://192.168.1.10:3773"}`, + ]); + }), ); }); diff --git a/packages/client-runtime/src/connection/supervisor.ts b/packages/client-runtime/src/connection/supervisor.ts index 212381921961b..3c969f0206243 100644 --- a/packages/client-runtime/src/connection/supervisor.ts +++ b/packages/client-runtime/src/connection/supervisor.ts @@ -36,6 +36,7 @@ import { connectionRoutes, type ConnectionRouteKind, entryWithRoutes, + insertRoute, type ReportedEndpoint, } from "./routes.ts"; @@ -87,6 +88,10 @@ interface PendingRetryTrace { readonly reason: ConnectionAttemptError["reason"]; } +type ConnectedLease = ConnectionDriver.EnvironmentConnectionLease & { + readonly activeRoute: ConnectionRoute | undefined; +}; + interface TracedAttemptFailure { readonly error: ConnectionAttemptError; readonly attemptSpan: Option.Option; @@ -332,35 +337,42 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( const learnRoutesFrom = Effect.fnUntraced(function* ( learn: NonNullable, - lease: ConnectionDriver.EnvironmentConnectionLease, + lease: ConnectedLease, ) { - const config = yield* lease.session.initialConfig.pipe(Effect.option); - const reported = Option.getOrUndefined(config)?.directEndpoints; - if (reported === undefined) return; - const activeId = connectionRouteId(lease.prepared.target); - const activeRoute = (yield* currentRoutes).find( - (route) => connectionRouteId(route.target) === activeId, - ); + const activeRoute = lease.activeRoute; if (activeRoute === undefined) return; - const updated = yield* learn({ activeRoute, reported }); - if (Option.isSome(updated)) { - yield* Ref.set(currentEntry, updated.value); - yield* requestBetterRouteCheck(lease); - } + yield* lease.session.subscribeServerConfig().pipe( + Stream.filter((event) => event.type === "snapshot"), + Stream.map((event) => event.config.directEndpoints), + Stream.filter((reported) => reported !== undefined), + Stream.changesWith((previous, next) => JSON.stringify(previous) === JSON.stringify(next)), + Stream.runForEach((reported) => + Effect.gen(function* () { + const updated = yield* learn({ activeRoute, reported }); + if (Option.isSome(updated)) { + yield* Ref.set(currentEntry, updated.value); + yield* requestBetterRouteCheck(lease); + } + }), + ), + Effect.ignoreCause({ log: true }), + ); }); - const routeIndex = (lease: ConnectionDriver.EnvironmentConnectionLease) => + const routeIndex = (lease: ConnectedLease) => currentRoutes.pipe( - Effect.map((routes) => - routes.findIndex( - (route) => connectionRouteId(route.target) === connectionRouteId(lease.prepared.target), - ), - ), + Effect.map((routes) => { + const activeId = connectionRouteId(lease.prepared.target); + const index = routes.findIndex((route) => connectionRouteId(route.target) === activeId); + return index === -1 && lease.activeRoute !== undefined + ? insertRoute(routes, lease.activeRoute).findIndex( + (route) => connectionRouteId(route.target) === activeId, + ) + : index; + }), ); - const checkBetterRoutes = Effect.fnUntraced(function* ( - lease: ConnectionDriver.EnvironmentConnectionLease, - ) { + const checkBetterRoutes = Effect.fnUntraced(function* (lease: ConnectedLease) { const latest = yield* Ref.get(currentEntry); const current = yield* routeIndex(lease); if (current <= 0) return; @@ -398,8 +410,8 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( }); }); - const betterRouteChecks = yield* Queue.dropping(1); - const requestBetterRouteCheck = (lease: ConnectionDriver.EnvironmentConnectionLease) => + const betterRouteChecks = yield* Queue.dropping(1); + const requestBetterRouteCheck = (lease: ConnectedLease) => routeIndex(lease).pipe( Effect.flatMap((index) => index > 0 ? Queue.offer(betterRouteChecks, lease).pipe(Effect.asVoid) : Effect.void, @@ -665,7 +677,7 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( // event, and "alive" once the socket delivers a frame. A slow or // unreachable host never ends it. const awaitSilentSocket = Effect.fn("EnvironmentSupervisor.awaitSilentSocket")(function* ( - lease: ConnectionDriver.EnvironmentConnectionLease, + lease: ConnectedLease, routeKind: ConnectionRouteKind | undefined, ) { const startedAt = yield* Clock.monotonicTimeNanos; @@ -698,9 +710,7 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( // all probe the live session instead of replacing it, so a healthy socket is // not torn down (the offline report is often wrong, for example for a // loopback server). - const monitorConnectedLease = Effect.fnUntraced(function* ( - lease: ConnectionDriver.EnvironmentConnectionLease, - ) { + const monitorConnectedLease = Effect.fnUntraced(function* (lease: ConnectedLease) { // A probe answers an explicit retry here, so the retry must not also reset // the backoff of a later, unrelated failure. const takeSignal = Queue.take(signals).pipe( @@ -938,11 +948,18 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( } satisfies AttemptOutcome; } + const connectedLease: ConnectedLease = { + ...active.lease, + activeRoute: (yield* currentRoutes).find( + (route) => + connectionRouteId(route.target) === connectionRouteId(active.lease.prepared.target), + ), + }; const connectedAt = yield* Clock.currentTimeMillis; - yield* SubscriptionRef.set(prepared, Option.some(active.lease.prepared)); - yield* SubscriptionRef.set(session, Option.some(active.lease.session)); + yield* SubscriptionRef.set(prepared, Option.some(connectedLease.prepared)); + yield* SubscriptionRef.set(session, Option.some(connectedLease.session)); if (options?.learnRoutes !== undefined) { - yield* learnRoutesFrom(options.learnRoutes, active.lease).pipe(Effect.forkScoped); + yield* learnRoutesFrom(options.learnRoutes, connectedLease).pipe(Effect.forkScoped); } yield* setState({ desired: true, @@ -956,13 +973,13 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( }); const connectedExit = yield* Effect.raceFirst( - active.lease.session.closed.pipe( + connectedLease.session.closed.pipe( Effect.mapError((error): TracedAttemptFailure => ({ error, attemptSpan: active.attemptSpan, })), ), - monitorConnectedLease(active.lease).pipe( + monitorConnectedLease(connectedLease).pipe( Effect.mapError((error): TracedAttemptFailure => ({ error, attemptSpan: active.attemptSpan, diff --git a/packages/client-runtime/src/operations/commands.performance.test.ts b/packages/client-runtime/src/operations/commands.performance.test.ts index d4be3f1a9f456..2a437e3d12815 100644 --- a/packages/client-runtime/src/operations/commands.performance.test.ts +++ b/packages/client-runtime/src/operations/commands.performance.test.ts @@ -11,7 +11,7 @@ import { type OrchestrationV2TurnItem, } from "@t3tools/contracts"; import { describe, expect, it } from "@effect/vitest"; -import * as Crypto from "effect/Crypto"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; @@ -137,12 +137,9 @@ const TARGET = new PrimaryConnectionTarget({ wsBaseUrl: "wss://environment.example.test", }); -const layerTestCrypto = Layer.succeed( - Crypto.Crypto, - Crypto.make({ - randomBytes: (size) => new Uint8Array(size), - digest: (_algorithm, data) => Effect.succeed(data), - }), +const layerTestRandom = Layer.succeed( + SecureRandom.SecureRandom, + SecureRandom.make((size) => new Uint8Array(size)), ); const makeSupervisor = Effect.fn("CommandPerformance.makeSupervisor")(function* (input: { @@ -174,7 +171,7 @@ const makeSupervisor = Effect.fn("CommandPerformance.makeSupervisor")(function* }, }, } as never), - subscribeServerConfig: (requestInput) => client.subscribeServerConfig(requestInput), + subscribeServerConfig: (requestInput = {}) => client.subscribeServerConfig(requestInput), ready: Effect.void, probe: Effect.void, inboundFrames: Effect.succeed(0), @@ -272,6 +269,6 @@ describe("routine command transport budget", () => { }); expect(currentRpcJsonBytes).toBeLessThanOrEqual(MAX_CURRENT_SEND_RPC_JSON_BYTES); expect(currentRpcJsonBytes / formerRpcJsonBytes).toBeLessThanOrEqual(0.000_06); - }).pipe(Effect.provide(layerTestCrypto)), + }).pipe(Effect.provide(layerTestRandom)), ); }); diff --git a/packages/client-runtime/src/operations/commands.test.ts b/packages/client-runtime/src/operations/commands.test.ts index 54c7563c1d85e..821a92721d357 100644 --- a/packages/client-runtime/src/operations/commands.test.ts +++ b/packages/client-runtime/src/operations/commands.test.ts @@ -20,7 +20,7 @@ import { type ProjectMutation, } from "@t3tools/contracts"; import { describe, expect, it } from "@effect/vitest"; -import * as Crypto from "effect/Crypto"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; @@ -43,12 +43,9 @@ import { startThreadTurn, } from "./commands.ts"; -const layerTestCrypto = Layer.succeed( - Crypto.Crypto, - Crypto.make({ - randomBytes: (size) => new Uint8Array(size), - digest: (_algorithm, data) => Effect.succeed(data), - }), +const layerTestRandom = Layer.succeed( + SecureRandom.SecureRandom, + SecureRandom.make((size) => new Uint8Array(size)), ); const TARGET = new PrimaryConnectionTarget({ @@ -116,7 +113,7 @@ const makeSupervisor = Effect.fn("TestEnvironmentCommands.makeSupervisor")(funct }, }, } as never), - subscribeServerConfig: (input) => client.subscribeServerConfig(input), + subscribeServerConfig: (input = {}) => client.subscribeServerConfig(input), ready: Effect.void, probe: Effect.void, inboundFrames: Effect.succeed(0), @@ -153,7 +150,7 @@ describe("V2 environment commands", () => { { type: "queued-run.start", commandId: "send-selected", threadId, runId: "selected" }, { type: "queue.resume", commandId: "resume-queue", threadId }, ]); - }).pipe(Effect.provide(layerTestCrypto)), + }).pipe(Effect.provide(layerTestRandom)), ); it.effect("preserves caller command ids for idempotent V2 commands", () => @@ -169,7 +166,7 @@ describe("V2 environment commands", () => { expect(commands).toEqual([ { type: "thread.archive", commandId: "queued-command", threadId: "thread-1" }, ]); - }).pipe(Effect.provide(layerTestCrypto)), + }).pipe(Effect.provide(layerTestRandom)), ); it.effect("resolves run ordinal zero to the persisted thread-start checkpoint", () => @@ -213,7 +210,7 @@ describe("V2 environment commands", () => { checkpointId, }, ]); - }).pipe(Effect.provide(layerTestCrypto)), + }).pipe(Effect.provide(layerTestRandom)), ); it.effect("preserves an existing worktree and branch during first-message launch", () => @@ -257,7 +254,7 @@ describe("V2 environment commands", () => { branch: "feature", }, }); - }).pipe(Effect.provide(layerTestCrypto)), + }).pipe(Effect.provide(layerTestRandom)), ); it.effect("uses server-resolved delivery intent without fetching the full projection", () => @@ -293,7 +290,7 @@ describe("V2 environment commands", () => { }); } expect(projectionRequests).toEqual([]); - }).pipe(Effect.provide(layerTestCrypto)), + }).pipe(Effect.provide(layerTestRandom)), ); it.effect("Stop with no run left ends the thread's pull request watches", () => @@ -347,7 +344,7 @@ describe("V2 environment commands", () => { watching: false, }, ]); - }).pipe(Effect.provide(layerTestCrypto)), + }).pipe(Effect.provide(layerTestRandom)), ); it.effect.each(["waiting", "completed", "rolled_back"] as const)( @@ -418,7 +415,7 @@ describe("V2 environment commands", () => { }, ], ); - }).pipe(Effect.provide(layerTestCrypto)), + }).pipe(Effect.provide(layerTestRandom)), ); it.effect( @@ -472,7 +469,7 @@ describe("V2 environment commands", () => { subagentId, }, ]); - }).pipe(Effect.provide(layerTestCrypto)), + }).pipe(Effect.provide(layerTestRandom)), ); it.effect( @@ -531,7 +528,7 @@ describe("V2 environment commands", () => { }, { type: "thread.stop", commandId: "lineage-stop", threadId: childThreadId }, ]); - }).pipe(Effect.provide(layerTestCrypto)), + }).pipe(Effect.provide(layerTestRandom)), ); it.effect("stops a thread without relying on background work in the history window", () => @@ -559,6 +556,6 @@ describe("V2 environment commands", () => { threadId: v2ThreadId, }, ]); - }).pipe(Effect.provide(layerTestCrypto)), + }).pipe(Effect.provide(layerTestRandom)), ); }); diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts index e3cbecfc2b2c4..777f7e2adb4f5 100644 --- a/packages/client-runtime/src/operations/commands.ts +++ b/packages/client-runtime/src/operations/commands.ts @@ -30,7 +30,7 @@ import { } from "@t3tools/contracts"; import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests"; -import * as Crypto from "effect/Crypto"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import { getInitialServerConfig, request } from "../rpc/client.ts"; @@ -270,8 +270,8 @@ const allocateCommandId = Effect.fn("EnvironmentCommands.allocateCommandId")(fun input: CommandMetadata, ) { if (input.commandId !== undefined) return input.commandId; - const crypto = yield* Crypto.Crypto; - return CommandId.make(yield* crypto.randomUUIDv4().pipe(Effect.orDie)); + const random = yield* SecureRandom.SecureRandom; + return CommandId.make(yield* random.uuidV4()); }); const dispatch = (command: OrchestrationV2Command) => diff --git a/packages/client-runtime/src/projectFaviconCache.test.ts b/packages/client-runtime/src/projectFaviconCache.test.ts index 6af70685145da..dd03c314ecc4f 100644 --- a/packages/client-runtime/src/projectFaviconCache.test.ts +++ b/packages/client-runtime/src/projectFaviconCache.test.ts @@ -202,11 +202,19 @@ describe("project favicon image loader", () => { await expect(load(url, signal())).rejects.toThrow("too large"); expect(pulled).toBeLessThan(PROJECT_FAVICON_MAX_SOURCE_BYTES / chunk.byteLength + 3); expect(downscale).not.toHaveBeenCalled(); + let cancelled = false; + const declaredStream = new ReadableStream({ + cancel() { + cancelled = true; + }, + }); const declared = loader( - new Response("x", { + new Response(declaredStream, { headers: { "content-type": "image/png", "content-length": String(2 ** 40) }, }), ); await expect(declared.load(url, signal())).rejects.toThrow("too large"); + expect(cancelled).toBe(true); + expect(declared.downscale).not.toHaveBeenCalled(); }); }); diff --git a/packages/client-runtime/src/projectFaviconCache.ts b/packages/client-runtime/src/projectFaviconCache.ts index 0e53de3136b9e..d779a27acebef 100644 --- a/packages/client-runtime/src/projectFaviconCache.ts +++ b/packages/client-runtime/src/projectFaviconCache.ts @@ -50,7 +50,10 @@ export interface ProjectFaviconStorage { async function readBounded(response: Response, maxBytes: number) { const declared = Number(response.headers.get("content-length")); - if (declared > maxBytes) throw new Error("Project icon is too large to decode."); + if (declared > maxBytes) { + await response.body?.cancel().catch(() => {}); + throw new Error("Project icon is too large to decode."); + } if (!response.body) { const bytes = new Uint8Array(await response.arrayBuffer()); if (bytes.byteLength > maxBytes) throw new Error("Project icon is too large to decode."); diff --git a/packages/client-runtime/src/providerClients.ts b/packages/client-runtime/src/providerClients.ts index 37cd15209614a..e23200653b963 100644 --- a/packages/client-runtime/src/providerClients.ts +++ b/packages/client-runtime/src/providerClients.ts @@ -11,6 +11,7 @@ import { modelShortName } from "@t3tools/provider-core/modelShortName"; import { cursorClient } from "@t3tools/provider-cursor/client"; import { fxClient } from "@t3tools/provider-fx/client"; import { grokClient } from "@t3tools/provider-grok/client"; +import { kiroClient } from "@t3tools/provider-kiro/client"; import { museClient } from "@t3tools/provider-muse/client"; import { openCodeClient } from "@t3tools/provider-opencode/client"; import { piClient } from "@t3tools/provider-pi/client"; @@ -41,6 +42,7 @@ export const providerClients = makeProviderClientRegistry([ acpRegistryAgentIds: ["antigravity-acp"], settingsSchema: AntigravitySettings, }, + kiroClient, museClient, piClient, acpRegistryClient, diff --git a/packages/client-runtime/src/rpc/client.test.ts b/packages/client-runtime/src/rpc/client.test.ts index cf9a096dd73bb..b15b20753d396 100644 --- a/packages/client-runtime/src/rpc/client.test.ts +++ b/packages/client-runtime/src/rpc/client.test.ts @@ -48,7 +48,7 @@ function session(client: WsRpcProtocolClient): RpcSession.RpcSession { return { client, initialConfig: Effect.never, - subscribeServerConfig: (input) => client.subscribeServerConfig(input), + subscribeServerConfig: (input = {}) => client.subscribeServerConfig(input), ready: Effect.void, probe: Effect.void, inboundFrames: Effect.succeed(0), diff --git a/packages/client-runtime/src/rpc/session.test.ts b/packages/client-runtime/src/rpc/session.test.ts index adca6b40b184a..95702f14787e3 100644 --- a/packages/client-runtime/src/rpc/session.test.ts +++ b/packages/client-runtime/src/rpc/session.test.ts @@ -447,7 +447,7 @@ describe("RpcSessionFactory", () => { yield* completeInitialConfig(socket, encodeServerConfig(SOURCE_SERVER_CONFIG), options); yield* Fiber.join(ready); const observed = yield* Queue.unbounded(); - yield* session.subscribeServerConfig(options).pipe( + yield* session.subscribeServerConfig().pipe( Stream.runForEach((event) => Queue.offer(observed, event)), Effect.forkChild, ); diff --git a/packages/client-runtime/src/rpc/session.ts b/packages/client-runtime/src/rpc/session.ts index 250c7889c6fce..fa6545618446c 100644 --- a/packages/client-runtime/src/rpc/session.ts +++ b/packages/client-runtime/src/rpc/session.ts @@ -49,7 +49,7 @@ export interface RpcSession { readonly client: WsRpcProtocolClient; readonly initialConfig: Effect.Effect; readonly subscribeServerConfig: ( - input: ServerConfigSubscriptionInput, + input?: ServerConfigSubscriptionInput, ) => ServerConfigSubscription; readonly ready: Effect.Effect; readonly probe: Effect.Effect; @@ -394,7 +394,7 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( }), ), ); - const subscribeServerConfig = (input: ServerConfigSubscriptionInput) => + const subscribeServerConfig = (input: ServerConfigSubscriptionInput = serverConfigInput) => Stream.unwrap( validatedInitialConfig.pipe( Effect.as( diff --git a/packages/client-runtime/src/state/assets.test.ts b/packages/client-runtime/src/state/assets.test.ts index b7a3b3403bd48..e2334489302fb 100644 --- a/packages/client-runtime/src/state/assets.test.ts +++ b/packages/client-runtime/src/state/assets.test.ts @@ -1,5 +1,11 @@ import { describe, expect, it } from "@effect/vitest"; -import { type AssetCreateUrlResult, EnvironmentId, WS_METHODS } from "@t3tools/contracts"; +import { + type AssetCreateUrlResult, + type AssetResource, + EnvironmentId, + ThreadId, + WS_METHODS, +} from "@t3tools/contracts"; import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -22,6 +28,7 @@ import { ASSET_URL_MAX_IN_FLIGHT, createAssetEnvironmentAtoms, createProjectFaviconUrlAtomFamily, + makeRevisionedAssetUrlFamily, } from "./assets.ts"; describe("project favicon URL cache", () => { @@ -229,3 +236,151 @@ describe("asset URL requests", () => { ), ); }); + +const revisionedEnvironmentId = EnvironmentId.make("environment-1"); +const revisionedResource: AssetResource = { + _tag: "workspace-file", + threadId: ThreadId.make("thread-1"), + path: "docs/diagram.png", +}; + +type MintResult = AsyncResult.AsyncResult<{ + relativeUrl: string; + expiresAt: number; + fileRevision?: string; +}>; + +const minted = (n: number, fileRevision?: string): MintResult => + AsyncResult.success({ + relativeUrl: `/a/${n}`, + expiresAt: 60 * 60_000, + ...(fileRevision === undefined ? {} : { fileRevision }), + }); + +// A stand-in for the asset URL query: a refresh starts a mint (counted, shown as +// waiting) and `settle` completes the latest one. +function setup(initial: MintResult) { + let mints = 0; + // Node removal runs on the registry's scheduler; `unmount` flushes it so the + // next mount of the same revision builds a fresh node. + const scheduled: Array<() => void> = []; + const registry = AtomRegistry.make({ + scheduleTask: (task) => { + scheduled.push(task); + return () => {}; + }, + }); + const server = Atom.make(initial).pipe(Atom.keepAlive); + const query = Atom.readable( + (get) => get(server), + () => { + mints += 1; + registry.set(server, AsyncResult.waiting(registry.get(server))); + }, + ).pipe(Atom.keepAlive); + const revisioned = makeRevisionedAssetUrlFamily( + () => query, + () => 0, + ); + const atom = (revision: string | null) => + revisioned({ + environmentId: revisionedEnvironmentId, + input: { resource: revisionedResource }, + revision, + }); + const mount = (revision: string | null) => { + const release = registry.mount(atom(revision)); + return () => { + release(); + for (const task of scheduled.splice(0)) task(); + }; + }; + const settle = (fileRevision?: string) => registry.set(server, minted(mints + 1, fileRevision)); + const url = (revision: string | null) => { + const result = registry.get(atom(revision)); + return result._tag === "Success" ? result.value.relativeUrl : null; + }; + return { mount, settle, url, mints: () => mints }; +} + +describe("makeRevisionedAssetUrlFamily", () => { + it("re-mints a settled URL on first read and on each new revision, not on remount", () => { + const { mount, settle, mints } = setup(minted(0)); + + mount("mutation-1")(); + expect(mints()).toBe(1); + settle(); + + mount("mutation-1")(); + expect(mints()).toBe(1); + + mount("mutation-2")(); + expect(mints()).toBe(2); + }); + + it("re-mints when a revert returns to an earlier revision", () => { + const { mount, settle, mints } = setup(minted(0)); + + mount("mutation-a")(); + settle(); + mount("mutation-b")(); + settle(); + expect(mints()).toBe(2); + + const reverted = mount("mutation-a"); + expect(mints()).toBe(3); + reverted(); + }); + + it("shares a mint in flight on the first read", () => { + const { mount, mints } = setup(AsyncResult.initial(true)); + + mount("mutation-1")(); + expect(mints()).toBe(0); + }); + + it("re-mints after a mint that was in flight when the revision changed", () => { + const { mount, settle, mints } = setup(minted(0)); + + const before = mount("mutation-1"); + settle(); + const edited = mount("mutation-2"); + expect(mints()).toBe(2); + before(); + + const stillMinting = mount("mutation-3"); + edited(); + expect(mints()).toBe(2); + + settle(); + expect(mints()).toBe(3); + settle(); + expect(mints()).toBe(3); + stillMinting(); + }); + + it("keeps the URL while the file is unchanged and swaps it once the file changes", () => { + const { mount, settle, url } = setup(minted(0, "file-a")); + + const first = mount("mutation-1"); + settle("file-a"); + first(); + + const unchanged = mount("mutation-2"); + settle("file-a"); + expect(url("mutation-2")).toBe("/a/0"); + unchanged(); + + // The query now holds /a/3; a later revision must still keep the URL on screen. + const stillUnchanged = mount("mutation-3"); + expect(url("mutation-3")).toBe("/a/0"); + settle("file-a"); + expect(url("mutation-3")).toBe("/a/0"); + stillUnchanged(); + + const edited = mount("mutation-4"); + settle("file-b"); + expect(url("mutation-4")).toBe("/a/5"); + edited(); + }); +}); diff --git a/packages/client-runtime/src/state/assets.ts b/packages/client-runtime/src/state/assets.ts index f2e2c0e90bb48..56b1b5bcd7d70 100644 --- a/packages/client-runtime/src/state/assets.ts +++ b/packages/client-runtime/src/state/assets.ts @@ -131,6 +131,113 @@ export function assetUrlStateFromResult( }; } +type AssetUrlTarget = { + readonly environmentId: EnvironmentId; + readonly input: { readonly resource: AssetResource }; +}; + +const decodeRevisionedAssetUrlKey = Schema.decodeUnknownSync( + Schema.Tuple([EnvironmentId, AssetResource, Schema.NullOr(Schema.String)]), +); + +const isSettled = (result: AsyncResult.AsyncResult) => + !AsyncResult.isInitial(result) && !result.waiting; + +const KEEP_URL_MIN_LIFE_MS = 5 * 60_000; + +/** + * A re-mint signs a new URL even when the file is unchanged, and a new URL reloads the image. + * Keep the shown URL while the server reports the same file revision and it has time left. + */ +function keepUnchangedFile( + shown: AsyncResult.AsyncResult, + next: AsyncResult.AsyncResult, + now: number, +) { + if ( + shown._tag !== "Success" || + next._tag !== "Success" || + next.value.fileRevision === undefined || + next.value.fileRevision !== shown.value.fileRevision || + shown.value.expiresAt - now <= KEEP_URL_MIN_LIFE_MS + ) { + return next; + } + const kept = AsyncResult.success(shown.value); + return next.waiting ? AsyncResult.waiting(kept) : kept; +} + +/** + * The URL is minted per resource and shared across revisions, so reading a + * different revision (even an earlier one after a revert) re-mints it. An + * in-flight mint is shared only on first read; after an edit the server must + * re-read the file, so the re-mint waits for that mint to settle. + */ +export function makeRevisionedAssetUrlFamily( + createUrl: ( + target: AssetUrlTarget, + ) => Atom.Atom>, + now: () => number = Date.now, +) { + // Outside the nodes: a node is dropped once unmounted, and the next read of + // its revision must still see the revisions minted since. Never pruned on + // purpose: pruning would forget the revision and re-mint on the next mount. + // It holds one short entry per file shown, and goes with the registry. + const mintedUnder = new WeakMap>(); + // Also per resource: a new revision builds a new node, which must keep the URL on screen. + const shownUnder = new WeakMap< + AtomRegistry.AtomRegistry, + Map> + >(); + const family = Atom.family((key: string) => { + const [environmentId, resource, revision] = decodeRevisionedAssetUrlKey(JSON.parse(key)); + const resourceKey = JSON.stringify([environmentId, resource]); + const query = createUrl({ environmentId, input: { resource } }); + return Atom.transform( + query, + (get) => { + let minted = mintedUnder.get(get.registry); + if (minted === undefined) { + minted = new Map(); + mintedUnder.set(get.registry, minted); + } + const firstRead = !minted.has(resourceKey); + let pending = minted.get(resourceKey) !== revision; + const current = get.once(query); + if (pending && (firstRead || isSettled(current))) { + pending = false; + minted.set(resourceKey, revision); + if (isSettled(current)) get.refresh(query); + } + let shownByResource = shownUnder.get(get.registry); + if (shownByResource === undefined) { + shownByResource = new Map(); + shownUnder.set(get.registry, shownByResource); + } + const show = (value: AsyncResult.AsyncResult) => { + const previous = shownByResource.get(resourceKey); + const shown = previous === undefined ? value : keepUnchangedFile(previous, value, now()); + shownByResource.set(resourceKey, shown); + return shown; + }; + get.subscribe(query, (value) => { + get.setSelf(show(value)); + if (!pending || !isSettled(value)) return; + pending = false; + minted.set(resourceKey, revision); + get.refresh(query); + }); + return show(get.once(query)); + }, + { initialValueTarget: query }, + // No idle TTL: each mount rebuilds the node, so a revision read again after + // another one is compared against the record instead of a cached node. + ).pipe(Atom.setIdleTTL(0)); + }); + return (target: AssetUrlTarget & { readonly revision: string | null }) => + family(JSON.stringify([target.environmentId, target.input.resource, target.revision])); +} + export function createAssetEnvironmentAtoms( runtime: Atom.AtomRuntime, localMediaEnvironment?: Atom.Atom<{ diff --git a/packages/client-runtime/src/state/attachments.test.ts b/packages/client-runtime/src/state/attachments.test.ts index c1376bc786fd5..a5396dcc0c66c 100644 --- a/packages/client-runtime/src/state/attachments.test.ts +++ b/packages/client-runtime/src/state/attachments.test.ts @@ -9,7 +9,11 @@ import * as Effect from "effect/Effect"; import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; import type { AtomCommand } from "./runtime.ts"; -import { runAttachmentUploadCycle, verifyPersistedAttachmentUpload } from "./attachments.ts"; +import { + formatAttachmentSize, + runAttachmentUploadCycle, + verifyPersistedAttachmentUpload, +} from "./attachments.ts"; const environmentId = EnvironmentId.make("environment-1"); const registry = {} as AtomRegistry.AtomRegistry; @@ -129,3 +133,14 @@ describe("verifyPersistedAttachmentUpload", () => { expect(lookups).toBe(2); }); }); + +describe("formatAttachmentSize", () => { + it.each([ + [1_047_552, "1023 KB"], + [1_047_553, "1.0 MB"], + [1_048_575, "1.0 MB"], + [1_048_576, "1.0 MB"], + ])("formats %d bytes as %s", (sizeBytes, label) => { + expect(formatAttachmentSize(sizeBytes)).toBe(label); + }); +}); diff --git a/packages/client-runtime/src/state/attachments.ts b/packages/client-runtime/src/state/attachments.ts index a78113a201097..800393470ffad 100644 --- a/packages/client-runtime/src/state/attachments.ts +++ b/packages/client-runtime/src/state/attachments.ts @@ -194,9 +194,9 @@ export function clampFileAttachmentUploadBytes(advertisedMaxUploadBytes: number) } export function formatAttachmentSize(sizeBytes: number): string { - return sizeBytes >= 1024 * 1024 - ? `${(sizeBytes / (1024 * 1024)).toFixed(1)} MB` - : `${Math.max(1, Math.ceil(sizeBytes / 1024))} KB`; + const kilobytes = Math.max(1, Math.ceil(sizeBytes / 1024)); + // Pick the unit after rounding, so 1023.5 KB reads "1.0 MB", not "1024 KB". + return kilobytes >= 1024 ? `${(sizeBytes / (1024 * 1024)).toFixed(1)} MB` : `${kilobytes} KB`; } export function fileAttachmentTooLargeMessage(name: string, maxUploadBytes: number): string { diff --git a/packages/client-runtime/src/state/git.ts b/packages/client-runtime/src/state/git.ts index ddce3ca4da8c8..18940290a997a 100644 --- a/packages/client-runtime/src/state/git.ts +++ b/packages/client-runtime/src/state/git.ts @@ -3,10 +3,12 @@ import { Atom } from "effect/reactivity"; import { createEnvironmentRpcCommand, createEnvironmentRpcQueryAtomFamily } from "./runtime.ts"; import type { EnvironmentRegistry } from "../connection/registry.ts"; +import * as Persistence from "../platform/persistence.ts"; import { vcsCommandConcurrency, vcsCommandScheduler } from "./vcsCommandScheduler.ts"; +import { invalidateCachedVcsRefs } from "./vcsRefInvalidation.ts"; export function createGitEnvironmentAtoms( - runtime: Atom.AtomRuntime, + runtime: Atom.AtomRuntime, ) { return { pullRequestResolution: createEnvironmentRpcQueryAtomFamily(runtime, { @@ -18,6 +20,8 @@ export function createGitEnvironmentAtoms( tag: WS_METHODS.gitPreparePullRequestThread, scheduler: vcsCommandScheduler, concurrency: vcsCommandConcurrency, + onSettled: ({ environmentId, input }, registry) => + invalidateCachedVcsRefs(registry, { environmentId, cwd: input.cwd }), }), }; } diff --git a/packages/client-runtime/src/state/projectCommands.test.ts b/packages/client-runtime/src/state/projectCommands.test.ts index 727dd87ff6864..000466b05e1da 100644 --- a/packages/client-runtime/src/state/projectCommands.test.ts +++ b/packages/client-runtime/src/state/projectCommands.test.ts @@ -11,7 +11,7 @@ import { WS_METHODS, } from "@t3tools/contracts"; import { vi } from "vite-plus/test"; -import * as Crypto from "effect/Crypto"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as Deferred from "effect/Deferred"; import * as Fiber from "effect/Fiber"; @@ -107,11 +107,8 @@ const makeHarness = Effect.fn("TestProjectCommands.makeHarness")(function* () { Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor), } as EnvironmentRegistry.EnvironmentRegistry["Service"]), Layer.succeed( - Crypto.Crypto, - Crypto.make({ - randomBytes: (size) => new Uint8Array(size), - digest: (_algorithm, data) => Effect.succeed(data), - }), + SecureRandom.SecureRandom, + SecureRandom.make((size) => new Uint8Array(size)), ), ), ); diff --git a/packages/client-runtime/src/state/projectCommands.ts b/packages/client-runtime/src/state/projectCommands.ts index 03db9b869cc06..caa706d86d46e 100644 --- a/packages/client-runtime/src/state/projectCommands.ts +++ b/packages/client-runtime/src/state/projectCommands.ts @@ -5,7 +5,7 @@ import { type ScopedProjectRef, WS_METHODS, } from "@t3tools/contracts"; -import * as Crypto from "effect/Crypto"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Predicate from "effect/Predicate"; @@ -73,7 +73,7 @@ export class ScratchProjectNotLoadedError extends Schema.TaggedError( - runtime: Atom.AtomRuntime, + runtime: Atom.AtomRuntime, options: { readonly projectAtom: (ref: ScopedProjectRef) => Atom.Atom; }, diff --git a/packages/client-runtime/src/state/pullRequests.test.ts b/packages/client-runtime/src/state/pullRequests.test.ts index 18e33cbbcf559..2564a3da21d0a 100644 --- a/packages/client-runtime/src/state/pullRequests.test.ts +++ b/packages/client-runtime/src/state/pullRequests.test.ts @@ -510,7 +510,7 @@ function session(client: WsRpcProtocolClient): RpcSession { client[WS_METHODS.pullRequestsInvalidate] ?? (() => Effect.void), }, initialConfig: client[WS_METHODS.serverGetConfig]?.({}).pipe(Effect.orDie) ?? Effect.never, - subscribeServerConfig: (input) => client.subscribeServerConfig(input), + subscribeServerConfig: (input = {}) => client.subscribeServerConfig(input), ready: Effect.void, probe: Effect.void, inboundFrames: Effect.succeed(0), diff --git a/packages/client-runtime/src/state/server.test.ts b/packages/client-runtime/src/state/server.test.ts index 15bb2f6834930..f7e46fb777faa 100644 --- a/packages/client-runtime/src/state/server.test.ts +++ b/packages/client-runtime/src/state/server.test.ts @@ -95,7 +95,7 @@ function session(client: WsRpcProtocolClient): RpcSession { return { client, initialConfig: Effect.succeed(CONFIG), - subscribeServerConfig: (input) => client.subscribeServerConfig(input), + subscribeServerConfig: (input = {}) => client.subscribeServerConfig(input), ready: Effect.void, probe: Effect.void, inboundFrames: Effect.succeed(0), diff --git a/packages/client-runtime/src/state/serverUsage.test.ts b/packages/client-runtime/src/state/serverUsage.test.ts index 247f4c650ae71..b16550c7c487c 100644 --- a/packages/client-runtime/src/state/serverUsage.test.ts +++ b/packages/client-runtime/src/state/serverUsage.test.ts @@ -132,7 +132,7 @@ const makeHarness = Effect.fn("ServerUsageTest.makeHarness")(function* ( const session: RpcSession = { client, initialConfig: Effect.succeed(CONFIG), - subscribeServerConfig: (input) => client.subscribeServerConfig(input), + subscribeServerConfig: (input = {}) => client.subscribeServerConfig(input), ready: Effect.void, probe: Effect.void, inboundFrames: Effect.succeed(0), diff --git a/packages/client-runtime/src/state/shell-sync.test.ts b/packages/client-runtime/src/state/shell-sync.test.ts index 7f24f61c53b21..c74ecd82fe85e 100644 --- a/packages/client-runtime/src/state/shell-sync.test.ts +++ b/packages/client-runtime/src/state/shell-sync.test.ts @@ -57,7 +57,7 @@ function session(client: WsRpcProtocolClient): RpcSession.RpcSession { return { client, initialConfig: Effect.succeed({ shellResumeCompletionMarker: true } as never), - subscribeServerConfig: (input) => client.subscribeServerConfig(input), + subscribeServerConfig: (input = {}) => client.subscribeServerConfig(input), ready: Effect.void, probe: Effect.void, inboundFrames: Effect.succeed(0), diff --git a/packages/client-runtime/src/state/threadCommands.test.ts b/packages/client-runtime/src/state/threadCommands.test.ts index 2b1b1162d6bc9..bc210e18ac04f 100644 --- a/packages/client-runtime/src/state/threadCommands.test.ts +++ b/packages/client-runtime/src/state/threadCommands.test.ts @@ -13,7 +13,7 @@ import { type OrchestrationV2ShellSnapshot, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; -import * as Crypto from "effect/Crypto"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; @@ -117,11 +117,8 @@ const makeHarness = Effect.fn("TestThreadCommands.makeHarness")(function* (optio Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor), } as EnvironmentRegistry.EnvironmentRegistry["Service"]), Layer.succeed( - Crypto.Crypto, - Crypto.make({ - randomBytes: (size) => new Uint8Array(size), - digest: (_algorithm, data) => Effect.succeed(data), - }), + SecureRandom.SecureRandom, + SecureRandom.make((size) => new Uint8Array(size)), ), Layer.succeed( ThreadHistoryController.ThreadHistoryController, diff --git a/packages/client-runtime/src/state/threadCommands.ts b/packages/client-runtime/src/state/threadCommands.ts index e0aae375ec5df..88a5759c5ed50 100644 --- a/packages/client-runtime/src/state/threadCommands.ts +++ b/packages/client-runtime/src/state/threadCommands.ts @@ -1,5 +1,5 @@ import type { ThreadId } from "@t3tools/contracts"; -import * as Crypto from "effect/Crypto"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import { Atom } from "effect/reactivity"; @@ -69,7 +69,7 @@ export type LoadEarlierThreadHistoryInput = { }; export function createThreadEnvironmentAtoms( - runtime: Atom.AtomRuntime, + runtime: Atom.AtomRuntime, snapshotAtom: (environmentId: EnvironmentId) => Atom.Atom, ) { const scheduler = createAtomCommandScheduler(); diff --git a/packages/client-runtime/src/state/threadDetail.test.ts b/packages/client-runtime/src/state/threadDetail.test.ts index 3e66202d0bb4b..cde705bdfb157 100644 --- a/packages/client-runtime/src/state/threadDetail.test.ts +++ b/packages/client-runtime/src/state/threadDetail.test.ts @@ -14,7 +14,12 @@ import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; import { v2Now, v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts"; import { applyOrchestrationV2ProjectionEvent } from "./orchestrationV2Projection.ts"; -import { createEnvironmentThreadDetailAtoms, sameThreadStructure } from "./threadDetail.ts"; +import type { ThreadStructureVisibleTurnItem } from "./models.ts"; +import { + createEnvironmentThreadDetailAtoms, + deriveWorkspaceMutationId, + sameThreadStructure, +} from "./threadDetail.ts"; import { mergeOlderHistoryIntoProjection } from "./threadHistoryMerge.ts"; import { EMPTY_ENVIRONMENT_THREAD_STATE } from "./threadState.ts"; @@ -349,3 +354,35 @@ it("matches full structure comparisons across streamed, batched, and reordered u [assistant.id, 1], ]); }); + +describe("deriveWorkspaceMutationId", () => { + const item = (id: string, type: string, status: string) => + ({ + item: { id: TurnItemId.make(id), type, status }, + }) as unknown as ThreadStructureVisibleTurnItem; + + it("keys on the latest finished command or file change and the latest checkpoint", () => { + expect( + deriveWorkspaceMutationId( + [ + item("edit", "file_change", "completed"), + item("reply", "assistant_message", "completed"), + item("command", "command_execution", "running"), + ], + "2026-01-01T00:00:00.000Z", + ), + ).toBe(JSON.stringify(["edit", "2026-01-01T00:00:00.000Z"])); + expect( + deriveWorkspaceMutationId( + [item("edit", "file_change", "completed"), item("mcp", "dynamic_tool", "completed")], + null, + ), + ).toBe(JSON.stringify(["mcp", null])); + }); + + it("is null before anything could have touched the workspace", () => { + expect(deriveWorkspaceMutationId([item("reply", "assistant_message", "completed")], null)).toBe( + null, + ); + }); +}); diff --git a/packages/client-runtime/src/state/threadDetail.ts b/packages/client-runtime/src/state/threadDetail.ts index 5cefc0a2783da..975134df2e07a 100644 --- a/packages/client-runtime/src/state/threadDetail.ts +++ b/packages/client-runtime/src/state/threadDetail.ts @@ -43,6 +43,38 @@ const EMPTY_THREAD_STRUCTURE_TURN_ITEMS: ReadonlyArray = Object.freeze([]); +/** + * Changes when the agent may have changed the workspace, so file views and host images refresh. + * File tools are explicit; commands, MCP or dynamic tools and subagents are included because + * they can mutate the workspace without reporting the paths they touched. + */ +export function deriveWorkspaceMutationId( + visibleTurnItems: ReadonlyArray, + latestCheckpointCompletedAt: string | null, +) { + let itemId: string | null = null; + for (let index = visibleTurnItems.length - 1; index >= 0; index -= 1) { + const item = visibleTurnItems[index]?.item; + if (!item) continue; + if ( + item.type !== "command_execution" && + item.type !== "file_change" && + item.type !== "dynamic_tool" && + item.type !== "subagent" + ) { + continue; + } + if (item.status === "pending" || item.status === "running" || item.status === "waiting") { + continue; + } + itemId = item.id; + break; + } + return itemId === null && latestCheckpointCompletedAt === null + ? null + : JSON.stringify([itemId, latestCheckpointCompletedAt]); +} + type TurnItem = OrchestrationV2ThreadProjection["turnItems"][number]; type VisibleTurnItem = OrchestrationV2ThreadProjection["visibleTurnItems"][number]; type AppThread = OrchestrationV2ThreadProjection["thread"]; @@ -502,8 +534,19 @@ export function createEnvironmentThreadDetailAtoms( ), ); + const workspaceMutationIdAtomFamily = Atom.family((key: string) => + Atom.make((get) => + deriveWorkspaceMutationId( + get(quietVisibleTurnItemsAtomFamily(key)), + get(checkpointSummariesAtomFamily(key)).at(-1)?.completedAt ?? null, + ), + ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-workspace-mutation-id:${key}`)), + ); + return { worktreePathAtom: (ref: ScopedThreadRef) => worktreePathAtomFamily(threadKey(ref)), + workspaceMutationIdAtom: (ref: ScopedThreadRef) => + workspaceMutationIdAtomFamily(threadKey(ref)), updatedAtAtom: (ref: ScopedThreadRef) => updatedAtAtomFamily(threadKey(ref)), lastVisitedAtAtom: (ref: ScopedThreadRef) => lastVisitedAtAtomFamily(threadKey(ref)), pendingRequestsAtom: (ref: ScopedThreadRef) => pendingRequestsAtomFamily(threadKey(ref)), diff --git a/packages/client-runtime/src/state/threadHistoryMerge.ts b/packages/client-runtime/src/state/threadHistoryMerge.ts index f84ea89d2e8bb..89a5188f216a9 100644 --- a/packages/client-runtime/src/state/threadHistoryMerge.ts +++ b/packages/client-runtime/src/state/threadHistoryMerge.ts @@ -112,34 +112,7 @@ export function mergeOlderHistoryIntoProjection( turnItemById.set(String(row.sourceItemId), row.item); } if (page.length === 0 && work === undefined) return projection; - // Shared rows anchor a retry page inside a larger conversation-only load. - // Keep existing gaps and rows outside the page in their current order. - const pageIndexByKey = new Map(); - let lastOverlapIndex = -1; - for (const [index, row] of page.entries()) { - const key = projectedItemKey(row); - pageIndexByKey.set(key, index); - if (currentByKey.has(key)) lastOverlapIndex = index; - } let visible: OrchestrationV2ProjectedTurnItem[] = []; - let pageOffset = 0; - if (lastOverlapIndex === -1) { - for (const row of page) visible.push(row); - pageOffset = page.length; - } - for (const row of projection.visibleTurnItems) { - const pageIndex = pageIndexByKey.get(projectedItemKey(row)); - if (pageIndex === undefined) { - visible.push(row); - continue; - } - for (const pageRow of page.slice(pageOffset, pageIndex + 1)) visible.push(pageRow); - pageOffset = pageIndex + 1; - if (pageIndex === lastOverlapIndex) { - for (const pageRow of page.slice(pageOffset)) visible.push(pageRow); - pageOffset = page.length; - } - } if (work && anchor && deferred) { let end = start + 1; while (end < projection.visibleTurnItems.length) { @@ -171,6 +144,34 @@ export function mergeOlderHistoryIntoProjection( ...projection.visibleTurnItems.slice(end), ]; if (anchor.visibility === "local") turnItemById.set(String(updated.item.id), updated.item); + } else { + // Shared rows anchor a retry page inside a larger conversation-only load. + // Keep existing gaps and rows outside the page in their current order. + const pageIndexByKey = new Map(); + let lastOverlapIndex = -1; + for (const [index, row] of page.entries()) { + const key = projectedItemKey(row); + pageIndexByKey.set(key, index); + if (currentByKey.has(key)) lastOverlapIndex = index; + } + let pageOffset = 0; + if (lastOverlapIndex === -1) { + for (const row of page) visible.push(row); + pageOffset = page.length; + } + for (const row of projection.visibleTurnItems) { + const pageIndex = pageIndexByKey.get(projectedItemKey(row)); + if (pageIndex === undefined) { + visible.push(row); + continue; + } + for (const pageRow of page.slice(pageOffset, pageIndex + 1)) visible.push(pageRow); + pageOffset = pageIndex + 1; + if (pageIndex === lastOverlapIndex) { + for (const pageRow of page.slice(pageOffset)) visible.push(pageRow); + pageOffset = page.length; + } + } } if ( visible.length === projection.visibleTurnItems.length && diff --git a/packages/client-runtime/src/state/threadInbox.ts b/packages/client-runtime/src/state/threadInbox.ts index f0a9b14e56b67..1c374251660a5 100644 --- a/packages/client-runtime/src/state/threadInbox.ts +++ b/packages/client-runtime/src/state/threadInbox.ts @@ -130,7 +130,7 @@ export function createInboxReturnTracker() { const keyOf = (thread: ThreadKeyInput) => `${thread.environmentId}:${thread.id}`; const states = new Map< string, - { working: boolean; deadline: number | null; placement: string } + { working: boolean; deadline: number | null; placement: string | null } >(); const returns = new Map(); const listeners = new Set<() => void>(); @@ -191,17 +191,21 @@ export function createInboxReturnTracker() { for (const thread of threads) { const key = keyOf(thread); present.add(key); - const placement = JSON.stringify([ - thread.archivedAt, - thread.deletedAt, - thread.pinnedAt, - thread.settledOverride, - thread.settledAt, - thread.snoozedAt, - thread.snoozedUntil, - thread.activeOrderKey, - ]); const previous = states.get(key); + const actual = isThreadWorking(thread); + const placement = + actual || previous?.working + ? JSON.stringify([ + thread.archivedAt, + thread.deletedAt, + thread.pinnedAt, + thread.settledOverride, + thread.settledAt, + thread.snoozedAt, + thread.snoozedUntil, + thread.activeOrderKey, + ]) + : null; const actionable = thread.hasPendingApprovals || thread.hasPendingUserInput || @@ -217,7 +221,6 @@ export function createInboxReturnTracker() { thread.pinnedAt != null || thread.settledOverride === "settled" || effectiveSnoozed(thread, { now: observedAt }); - const actual = isThreadWorking(thread); // Only shelf placement is held: execution state and attention requests stay authoritative. const deadline = !actual && previous?.working && !actionable && !moved && !excluded diff --git a/packages/client-runtime/src/state/threadRequests.test.ts b/packages/client-runtime/src/state/threadRequests.test.ts index d9aaf9fdca71a..c2e1024e232ae 100644 --- a/packages/client-runtime/src/state/threadRequests.test.ts +++ b/packages/client-runtime/src/state/threadRequests.test.ts @@ -2,6 +2,8 @@ import { presentThreadShell } from "./models.ts"; import { threadKey } from "./entities.ts"; import { EnvironmentId, + EventId, + MessageId, ThreadId, type ScopedThreadRef, NodeId, @@ -13,6 +15,7 @@ import { import { describe, expect, it, vi } from "vite-plus/test"; import { Atom, AtomRegistry, AsyncResult } from "effect/reactivity"; import * as Cause from "effect/Cause"; +import { applyOrchestrationV2ProjectionEvent } from "./orchestrationV2Projection.ts"; import { v2Now, v2Projection, v2ThreadShell } from "./orchestrationV2TestFixtures.ts"; import { createQuestionHistoryProjector, @@ -360,6 +363,210 @@ it("restores old text answers without mutating history or replacing unchanged ro expect(project({ ...answered, visibleTurnItems: [...rows] })[0]).toBe(result[0]); }); +type QuestionItem = Extract< + OrchestrationV2ThreadProjection["turnItems"][number], + { readonly type: "user_input_request" } +>; + +describe("question history through exact row replacements", () => { + const baseItem = { + threadId: v2Projection.thread.id, + runId: null, + nodeId, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + status: "running" as const, + title: null, + startedAt: v2Now, + completedAt: null, + updatedAt: v2Now, + }; + const assistantItem = (ordinal: number, text = "Hel") => ({ + ...baseItem, + id: TurnItemId.make(`assistant-${ordinal}`), + ordinal, + type: "assistant_message" as const, + messageId: MessageId.make(`message-${ordinal}`), + text, + streaming: true, + }); + const localRow = ( + item: OrchestrationV2ThreadProjection["turnItems"][number], + position: number, + ) => ({ + item, + position, + sourceItemId: item.id, + sourceThreadId: item.threadId, + visibility: "local" as const, + }); + const updated = ( + current: OrchestrationV2ThreadProjection, + item: OrchestrationV2ThreadProjection["turnItems"][number], + ) => + applyOrchestrationV2ProjectionEvent(current, { + id: EventId.make(`event-${item.id}`), + type: "turn-item.updated", + threadId: current.thread.id, + occurredAt: v2Now, + payload: item, + })!; + + it("reads only the replaced row and leaves the request index alone", () => { + const size = 1_000; + const counts = { items: 0, requestIds: 0 }; + const items = Array.from({ length: size }, (_, index) => assistantItem(index)); + const countedRows = items.map((item, index) => { + const row = localRow(item, index); + return Object.defineProperty(row, "item", { + enumerable: true, + get: () => { + counts.items += 1; + return item; + }, + }); + }); + const countedRequests = Array.from({ length: 400 }, (_, index) => { + const request = { + ...projection.runtimeRequests[0]!, + id: RuntimeRequestId.make(`request-${index}`), + }; + return Object.defineProperty(request, "id", { + enumerable: true, + get: () => { + counts.requestIds += 1; + return RuntimeRequestId.make(`request-${index}`); + }, + }); + }); + const initial: OrchestrationV2ThreadProjection = { + ...v2Projection, + turnItems: items, + visibleTurnItems: countedRows, + runtimeRequests: countedRequests, + }; + const project = createQuestionHistoryProjector(); + const scan = (current: OrchestrationV2ThreadProjection) => { + counts.items = 0; + counts.requestIds = 0; + const result = project(current); + return { result, ...counts }; + }; + expect(scan(initial)).toMatchObject({ items: size, requestIds: 400 }); + + const adjacent = updated(initial, assistantItem(size - 1, "Hello")); + const hinted = scan(adjacent); + expect(hinted.result).toBe(adjacent.visibleTurnItems); + expect(hinted).toMatchObject({ items: 0, requestIds: 0 }); + + // A skipped delta has no hint for this exact pair, so it scans again. + const skipped = updated( + updated(adjacent, assistantItem(size - 1, "Hello t")), + assistantItem(size - 1, "Hello there"), + ); + const fallback = scan(skipped); + expect(fallback.result).toBe(skipped.visibleTurnItems); + expect(fallback).toMatchObject({ items: size - 1, requestIds: 0 }); + }); + + it("matches a full projection through streamed rows, request changes and answers", () => { + const question = projection.turnItems[0] as QuestionItem; + const resolved = (answers: Record) => ({ + ...projection.runtimeRequests[0]!, + status: "resolved" as const, + answers, + }); + const explicitRequestId = RuntimeRequestId.make("explicit-question"); + const explicitAnswer = { + requestId: explicitRequestId, + answers: { next: "Explicit" }, + attachmentsByQuestionId: {}, + questionTextById: { next: "What should happen next?" }, + }; + const unanswered: QuestionItem = { + ...question, + id: TurnItemId.make("explicit-question-item"), + ordinal: 1, + requestId: explicitRequestId, + }; + const explicit: QuestionItem = { ...unanswered, questionAnswer: explicitAnswer }; + const explicitRequest = { + ...resolved({ next: "From request" }), + id: explicitRequestId, + }; + const stream = assistantItem(2); + const inherited = { + ...localRow({ ...question, id: TurnItemId.make("inherited-question-item") }, 3), + visibility: "inherited" as const, + sourceThreadId: ThreadId.make("parent-thread"), + }; + const turnItems = [question, explicit, stream]; + let current: OrchestrationV2ThreadProjection = { + ...v2Projection, + turnItems, + visibleTurnItems: [...turnItems.map(localRow), inherited], + runtimeRequests: [projection.runtimeRequests[0]!, explicitRequest], + }; + const project = createQuestionHistoryProjector(); + const step = (next: OrchestrationV2ThreadProjection) => { + current = next; + const result = project(next); + expect(result).toEqual(createQuestionHistoryProjector()(next)); + return result; + }; + const answerOf = (rows: ReadonlyArray<{ readonly item: unknown }>, index: number) => + (rows[index]!.item as { readonly questionAnswer?: { readonly answers: unknown } }) + .questionAnswer?.answers; + + expect(step(current)).toBe(current.visibleTurnItems); + expect(step(updated(current, assistantItem(2, "Hello")))).toBe(current.visibleTurnItems); + + // The last duplicate request wins, and every row asking it gets the answer. + const answered = step({ + ...current, + runtimeRequests: [ + projection.runtimeRequests[0]!, + resolved({ next: "Continue" }), + explicitRequest, + ], + }); + expect(answerOf(answered, 0)).toEqual({ next: "Continue" }); + expect(answerOf(answered, 1)).toEqual({ next: "Explicit" }); + expect(answerOf(answered, 3)).toEqual({ next: "Continue" }); + + const whileOverlaid = step(updated(current, assistantItem(2, "Hello there"))); + expect(whileOverlaid[0]).toBe(answered[0]); + expect(whileOverlaid[3]).toBe(answered[3]); + + const changedAnswer = step({ + ...current, + runtimeRequests: [resolved({ next: "Stop" }), explicitRequest], + }); + expect(answerOf(changedAnswer, 0)).toEqual({ next: "Stop" }); + + const reopened = step({ + ...current, + runtimeRequests: [projection.runtimeRequests[0]!, explicitRequest], + }); + expect(reopened).toBe(current.visibleTurnItems); + + // Dropping an explicit answer falls back to its resolved request. + const restored = step(updated(current, unanswered)); + expect(answerOf(restored, 1)).toEqual({ next: "From request" }); + + const retitled: QuestionItem = { + ...unanswered, + questions: [{ ...question.questions[0]!, question: "Now what?" }], + }; + const retitledRows = step(updated(current, retitled)); + expect(retitledRows[1]!.item).toMatchObject({ + questionAnswer: { questionTextById: { next: "Now what?" } }, + }); + }); +}); + it("loads only child approvals and retains their destination across environments", () => { const local = EnvironmentId.make("local"); const remote = EnvironmentId.make("remote"); diff --git a/packages/client-runtime/src/state/threadRequests.ts b/packages/client-runtime/src/state/threadRequests.ts index a010018c5051d..6cbad534cba1d 100644 --- a/packages/client-runtime/src/state/threadRequests.ts +++ b/packages/client-runtime/src/state/threadRequests.ts @@ -13,6 +13,7 @@ import type { } from "@t3tools/contracts"; import { Atom } from "effect/reactivity"; import { parseThreadKey, threadKey } from "./entities.ts"; +import { getProjectionArrayReplacementIndex } from "./orchestrationV2Projection.ts"; import type { EnvironmentThreadShell } from "./models.ts"; import * as DateTime from "effect/DateTime"; import type { AtomCommandResult } from "./runtime.ts"; @@ -292,54 +293,61 @@ export function createQuestionHistoryProjector< let previousRows: Rows | undefined; let previousRequests: Requests | undefined; let previousResult: Rows | undefined; + let byId = new Map(); const cache = new WeakMap(); - return (projection: { - readonly visibleTurnItems: Rows; - readonly runtimeRequests: Requests; - }): Rows => { - const { visibleTurnItems: rows, runtimeRequests: requests } = projection; - if (rows === previousRows && requests === previousRequests && previousResult) - return previousResult; - const byId = new Map(requests.map((request) => [request.id, request])); + const projectRow = (row: Row): Row => { + const item = row.item; + if (item.type !== "user_input_request" || item.questionAnswer) return row; + const request = byId.get(item.requestId); + if (request?.status !== "resolved" || request.answers === undefined) return row; + const cached = cache.get(row); + const next: Row = + cached?.request === request + ? cached.row + : { + ...row, + item: { + ...item, + questionAnswer: { + requestId: request.id, + answers: request.answers, + attachmentsByQuestionId: {}, + questionTextById: Object.fromEntries( + item.questions.map((question) => [question.id, question.question]), + ), + }, + }, + }; + cache.set(row, { request, row: next }); + return next; + }; + const projectRows = (rows: Rows): Rows => { let result: Row[] | undefined; for (const [index, row] of rows.entries()) { - const item = row.item; - const request = - item.type === "user_input_request" && !item.questionAnswer - ? byId.get(item.requestId) - : undefined; - let next = row; - if ( - item.type === "user_input_request" && - request?.status === "resolved" && - request.answers !== undefined - ) { - const cached = cache.get(row); - next = - cached?.request === request - ? cached.row - : { - ...row, - item: { - ...item, - questionAnswer: { - requestId: request.id, - answers: request.answers, - attachmentsByQuestionId: {}, - questionTextById: Object.fromEntries( - item.questions.map((question) => [question.id, question.question]), - ), - }, - }, - }; - cache.set(row, { request, row: next }); - } + const next = projectRow(row); if (next !== row) result ??= rows.slice(0, index); result?.push(next); } + return result ?? rows; + }; + return (projection: { + readonly visibleTurnItems: Rows; + readonly runtimeRequests: Requests; + }): Rows => { + const { visibleTurnItems: rows, runtimeRequests: requests } = projection; + const sameRequests = requests === previousRequests; + if (rows === previousRows && sameRequests && previousResult) return previousResult; + if (!sameRequests) byId = new Map(requests.map((request) => [request.id, request])); + // Nothing was overlaid and requests are unchanged, so only an exactly replaced row can differ. + const replacedIndex = + sameRequests && previousRows !== undefined && previousResult === previousRows + ? getProjectionArrayReplacementIndex(previousRows, rows) + : undefined; + const unchanged = + replacedIndex !== undefined && projectRow(rows[replacedIndex]!) === rows[replacedIndex]; previousRows = rows; previousRequests = requests; - previousResult = result ?? rows; + previousResult = unchanged ? rows : projectRows(rows); return previousResult; }; } diff --git a/packages/client-runtime/src/state/threads-atoms.test.ts b/packages/client-runtime/src/state/threads-atoms.test.ts index 23263d432444c..af2ab6d0575a6 100644 --- a/packages/client-runtime/src/state/threads-atoms.test.ts +++ b/packages/client-runtime/src/state/threads-atoms.test.ts @@ -97,7 +97,7 @@ const makeHarness = Effect.fn("TestThreadAtoms.makeHarness")(function* (options? threadResumeCompletionMarker: true, threadSnapshotPagination: true, } as never), - subscribeServerConfig: (input) => client.subscribeServerConfig(input), + subscribeServerConfig: (input = {}) => client.subscribeServerConfig(input), ready: Effect.void, probe: Effect.void, inboundFrames: Effect.succeed(0), diff --git a/packages/client-runtime/src/state/threads-sync.test.ts b/packages/client-runtime/src/state/threads-sync.test.ts index 593e29286b66c..5289701420931 100644 --- a/packages/client-runtime/src/state/threads-sync.test.ts +++ b/packages/client-runtime/src/state/threads-sync.test.ts @@ -85,7 +85,7 @@ function testSession(client: WsRpcProtocolClient): RpcSession.RpcSession { return { client, initialConfig: Effect.succeed({} as never), - subscribeServerConfig: (input) => client.subscribeServerConfig(input), + subscribeServerConfig: (input = {}) => client.subscribeServerConfig(input), ready: Effect.void, probe: Effect.void, inboundFrames: Effect.succeed(0), diff --git a/packages/client-runtime/src/state/vcs.test.ts b/packages/client-runtime/src/state/vcs.test.ts index b5cdf7004fd5c..cdbda23422237 100644 --- a/packages/client-runtime/src/state/vcs.test.ts +++ b/packages/client-runtime/src/state/vcs.test.ts @@ -4,6 +4,7 @@ import { AuthSourceControlWriteScope, WS_METHODS, VcsProcessExitError, + type VcsListRefsInput, type VcsListRefsResult, type VcsStatusResult, } from "@t3tools/contracts"; @@ -33,6 +34,7 @@ import * as Persistence from "../platform/persistence.ts"; import { EnvironmentRpcUnavailableError } from "../rpc/client.ts"; import type { WsRpcProtocolClient } from "../rpc/protocol.ts"; import type { RpcSession } from "../rpc/session.ts"; +import { createGitEnvironmentAtoms } from "./git.ts"; import { commitVcsRefsRefresh, @@ -93,7 +95,7 @@ function session(client: WsRpcProtocolClient): RpcSession { return { client, initialConfig: Effect.never, - subscribeServerConfig: (input) => client.subscribeServerConfig(input), + subscribeServerConfig: (input = {}) => client.subscribeServerConfig(input), ready: Effect.void, probe: Effect.void, inboundFrames: Effect.succeed(0), @@ -154,6 +156,98 @@ describe("cached VCS refs", () => { registry.dispose(); }); + it.effect("bypasses the server ref snapshot when a mounted list is invalidated", () => + Effect.scoped( + Effect.gen(function* () { + const requests = yield* Queue.unbounded(); + const client = { + [WS_METHODS.vcsListRefs]: (input: VcsListRefsInput) => + Effect.sync(() => { + Queue.offerUnsafe(requests, input); + return LIVE_REFS; + }), + } as unknown as WsRpcProtocolClient; + const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({ + target: TARGET, + state: yield* SubscriptionRef.make(CONNECTED_CONNECTION_STATE), + session: yield* SubscriptionRef.make(Option.some(session(client))), + prepared: yield* SubscriptionRef.make(Option.none()), + connect: Effect.void, + disconnect: Effect.void, + retryNow: Effect.void, + } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]); + const followStream: EnvironmentRegistry.EnvironmentRegistry["Service"]["followStream"] = ( + _environmentId, + stream, + ) => Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor); + const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({ + followStream, + } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]); + const runtime = Atom.runtime( + Layer.merge( + Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry), + Layer.succeed(Persistence.EnvironmentCacheStore, cacheWithRefs(Option.none())), + ), + ); + const atoms = createVcsEnvironmentAtoms(runtime); + const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) => + Effect.sync(() => registry.dispose()), + ); + yield* Effect.acquireRelease( + Effect.sync(() => + registry.mount( + atoms.listRefs({ + environmentId: TARGET.environmentId, + input: { cwd: "/repo", limit: 100 }, + }), + ), + ), + (unmount) => Effect.sync(unmount), + ); + + expect(yield* Queue.take(requests)).toEqual({ cwd: "/repo", limit: 100 }); + + invalidateVcsRefs(registry, TARGET); + + expect(yield* Queue.take(requests)).toEqual({ cwd: "/repo", limit: 100, refresh: true }); + + yield* Effect.acquireRelease( + Effect.sync(() => + registry.mount( + atoms.listRefs({ + environmentId: TARGET.environmentId, + input: { cwd: "/other-repo", limit: 100 }, + }), + ), + ), + (unmount) => Effect.sync(unmount), + ); + expect(yield* Queue.take(requests)).toEqual({ + cwd: "/other-repo", + limit: 100, + refresh: true, + }); + + yield* Effect.acquireRelease( + Effect.sync(() => + registry.mount( + atoms.listRefs({ + environmentId: TARGET.environmentId, + input: { cwd: "/other-repo", query: "release", limit: 100 }, + }), + ), + ), + (unmount) => Effect.sync(unmount), + ); + expect(yield* Queue.take(requests)).toEqual({ + cwd: "/other-repo", + query: "release", + limit: 100, + }); + }), + ), + ); + it.effect("does not repersist a refresh superseded by ref invalidation", () => Effect.scoped( Effect.gen(function* () { @@ -223,6 +317,8 @@ describe("cached VCS refs", () => { const client = { [WS_METHODS.vcsPull]: () => Effect.fail(expectedError), [WS_METHODS.vcsRefreshStatus]: () => Effect.void, + [WS_METHODS.gitPreparePullRequestThread]: () => + Effect.succeed({ branch: "feature/pr", worktreePath: null }), } as unknown as WsRpcProtocolClient; const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({ target: TARGET, @@ -278,6 +374,17 @@ describe("cached VCS refs", () => { expect(AsyncResult.isSuccess(refreshResult)).toBe(true); expect(yield* Ref.get(clears)).toBe(2); expect(registry.get(vcsRefsCacheStateAtom(TARGET)).revision).toBe(2); + + const prepareResult = yield* Effect.promise(() => + createGitEnvironmentAtoms(runtime).preparePullRequestThread.run(registry, { + environmentId: TARGET.environmentId, + input: { cwd: "/repo", reference: "42", mode: "local" }, + }), + ); + + expect(AsyncResult.isSuccess(prepareResult)).toBe(true); + expect(yield* Ref.get(clears)).toBe(3); + expect(registry.get(vcsRefsCacheStateAtom(TARGET)).revision).toBe(3); }), ), ); diff --git a/packages/client-runtime/src/state/vcs.ts b/packages/client-runtime/src/state/vcs.ts index e05ec4a2c8eb6..ef508f2126c7f 100644 --- a/packages/client-runtime/src/state/vcs.ts +++ b/packages/client-runtime/src/state/vcs.ts @@ -33,6 +33,9 @@ import { withVcsRefsPersistenceLock, } from "./vcsRefInvalidation.ts"; +// Share freshness across search and pagination keys, but keep it local to this registry. +const serverRefsRevisionAtom = Atom.family((_key: string) => Atom.make(0).pipe(Atom.keepAlive)); + const OFFLINE_BRANCH_LIST_LIMIT = 100; const VCS_REFS_IDLE_TTL_MS = 30_000; const VCS_STATUS_IDLE_TTL_MS = 10_000; @@ -143,9 +146,17 @@ export const makeCachedVcsRefsChanges = Effect.fn("CachedVcsRefsState.makeChange ) : Option.none(); const refresh = Effect.fn("CachedVcsRefsState.refresh")(function* () { - const refs = yield* request(WS_METHODS.vcsListRefs, input).pipe( - Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor), + const revisionAtom = serverRefsRevisionAtom( + `${environmentId.length}:${environmentId}${input.cwd}`, ); + const bypassServerSnapshot = + expectedRevision !== undefined && + registry !== undefined && + expectedRevision > registry.get(revisionAtom); + const refs = yield* request( + WS_METHODS.vcsListRefs, + bypassServerSnapshot ? { ...input, refresh: true } : input, + ).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor)); const persist = cache.saveVcsRefs(environmentId, input.cwd, refs).pipe( Effect.catch((error) => Effect.logWarning("Could not persist cached Git refs.").pipe( @@ -168,6 +179,7 @@ export const makeCachedVcsRefsChanges = Effect.fn("CachedVcsRefsState.makeChange expectedRevision, persist: useCache, }); + if (committed && bypassServerSnapshot) registry.set(revisionAtom, expectedRevision); return committed ? Option.some(refs) : Option.none(); }); diff --git a/packages/client-runtime/src/state/vcsAction.test.ts b/packages/client-runtime/src/state/vcsAction.test.ts index 2dfc43e91ee8a..d4a1355fb4ff9 100644 --- a/packages/client-runtime/src/state/vcsAction.test.ts +++ b/packages/client-runtime/src/state/vcsAction.test.ts @@ -86,7 +86,7 @@ function session(client: WsRpcProtocolClient): RpcSession { return { client, initialConfig: Effect.never, - subscribeServerConfig: (input) => client.subscribeServerConfig(input), + subscribeServerConfig: (input = {}) => client.subscribeServerConfig(input), ready: Effect.void, probe: Effect.void, inboundFrames: Effect.succeed(0), diff --git a/packages/client-runtime/src/voice-input/controller.test.ts b/packages/client-runtime/src/voice-input/controller.test.ts index e6a321ace0f72..6aae8808885ee 100644 --- a/packages/client-runtime/src/voice-input/controller.test.ts +++ b/packages/client-runtime/src/voice-input/controller.test.ts @@ -173,6 +173,12 @@ describe("resolveTranscriptCommit", () => { expect( resolveTranscriptCommit(continuing, continuing, "Und die Tests.", "de-DE"), ).toMatchObject({ text: "Fix the bugUnd die Tests before release." }); + const beforeName = at("ask ", 4); + expect( + resolveTranscriptCommit(beforeName, beforeName, "Maria to review.", "en-US"), + ).toMatchObject({ + text: "ask Maria to review.", + }); const midSentence = at("Fix the bug before release.", 11); expect(resolveTranscriptCommit(midSentence, midSentence, "and tests", "en-US")).toMatchObject({ text: "Fix the bug and tests before release.", diff --git a/packages/client-runtime/src/voice-input/controller.ts b/packages/client-runtime/src/voice-input/controller.ts index edaa2bf4fcb73..6357fd47021f4 100644 --- a/packages/client-runtime/src/voice-input/controller.ts +++ b/packages/client-runtime/src/voice-input/controller.ts @@ -124,7 +124,7 @@ export function resolveTranscriptCommit( if (atSentenceStart) { if (!/\p{Lu}/u.test(firstWord)) insertion = withFirstLetterCase(insertion, locale, true); } else { - const plainCapitalized = /^\p{Lu}\p{Ll}*\P{L}*$/u.test(firstWord) && !/^I\b/u.test(firstWord); + const plainCapitalized = /^(?:And|Also|Then|But|Or|So)\b/u.test(firstWord); if (usesEnglishSpacing && plainCapitalized) { insertion = withFirstLetterCase(insertion, locale, false); } diff --git a/packages/contracts/src/model.ts b/packages/contracts/src/model.ts index 1a04cc61c887a..1a2a519e1abc7 100644 --- a/packages/contracts/src/model.ts +++ b/packages/contracts/src/model.ts @@ -119,6 +119,7 @@ const CLAUDE_DRIVER_KIND = ProviderDriverKind.make("claudeAgent"); const CURSOR_DRIVER_KIND = ProviderDriverKind.make("cursor"); const GROK_DRIVER_KIND = ProviderDriverKind.make("grok"); const FX_DRIVER_KIND = ProviderDriverKind.make("fx"); +const KIRO_DRIVER_KIND = ProviderDriverKind.make("kiro"); const MUSE_DRIVER_KIND = ProviderDriverKind.make("muse"); const PI_DRIVER_KIND = ProviderDriverKind.make("pi"); const ACP_REGISTRY_DRIVER_KIND = ProviderDriverKind.make("acpRegistry"); @@ -147,6 +148,8 @@ export const DEFAULT_MODEL_BY_PROVIDER: Partial> [CURSOR_DRIVER_KIND]: "Cursor", [GROK_DRIVER_KIND]: "Grok", [FX_DRIVER_KIND]: "fx", + [KIRO_DRIVER_KIND]: "Kiro", [MUSE_DRIVER_KIND]: "Muse Code", [ACP_REGISTRY_DRIVER_KIND]: "ACP Registry", [PI_DRIVER_KIND]: "Pi", diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index e5882e5805ee5..e215ff8673a63 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -285,6 +285,8 @@ export const OrchestrationV2TurnCapabilities = Schema.Struct({ supportsActiveSteering: Schema.Boolean, // Some native steering mechanisms cancel pending tools before consuming the message. activeSteeringInterruptsTools: Schema.optional(Schema.Boolean), + // Some take text only, so a steer with attachments restarts the turn instead. + activeSteeringAcceptsAttachments: Schema.optional(Schema.Boolean), supportsSteeringByInterruptRestart: Schema.Boolean, supportsQueuedMessages: Schema.Boolean, terminalStatusQuality: Schema.Literals(["strong", "weak", "none"]), diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 156bffd859fea..7381b3922f23e 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -1431,7 +1431,7 @@ export const providerInstanceConfigEnabledFlag = (config: unknown): boolean | un // Must match each driver's enabled decoding default. const DEFAULT_DISABLED_PROVIDER_DRIVERS: ReadonlySet = new Set( - ["cursor", "grok", "fx", "muse", "pi", "opencode", "antigravity"].map((driver) => + ["cursor", "grok", "fx", "kiro", "muse", "pi", "opencode", "antigravity"].map((driver) => ProviderDriverKind.make(driver), ), ); diff --git a/packages/contracts/src/settingsSecretValue.ts b/packages/contracts/src/settingsSecretValue.ts index 101c40998b6f0..97558c82d574f 100644 --- a/packages/contracts/src/settingsSecretValue.ts +++ b/packages/contracts/src/settingsSecretValue.ts @@ -26,26 +26,68 @@ export function acceptsSecretReference(schema: Schema.Top): boolean { return Schema.resolveAnnotationsKey(schema)?.settingsSecretReference === true; } -/** Fields of a settings struct typed `SettingsSecretValue`; any other schema has none. */ -function secretReferenceSettingsFields(schema: Schema.Top): ReadonlyArray { +const declaresSecretReference = (ast: SchemaAST.AST) => + ast.context?.annotations?.settingsSecretReference === true; + +interface SecretReferenceField { + readonly field: string; + readonly keyed: boolean; +} + +/** + * Fields of a settings struct typed `SettingsSecretValue`, or a record of it such as one value + * per host; any other schema has none. + */ +function secretReferenceSettingsFields(schema: Schema.Top): ReadonlyArray { if (!SchemaAST.isObjects(schema.ast)) return []; - return schema.ast.propertySignatures.flatMap((property) => - property.type.context?.annotations?.settingsSecretReference === true && - typeof property.name === "string" - ? [property.name] - : [], - ); + return schema.ast.propertySignatures.flatMap(({ name, type }) => { + if (typeof name !== "string") return []; + if (declaresSecretReference(type)) return [{ field: name, keyed: false }]; + return SchemaAST.isObjects(type) && + type.indexSignatures.some((signature) => declaresSecretReference(signature.type)) + ? [{ field: name, keyed: true }] + : []; + }); } -/** Each declared reference field of `settings` that holds a reference, in field order. */ +/** Where a reference sits: a field, or one key of a record field. */ +export interface SettingsSecretSlot { + readonly field: string; + readonly key: string | undefined; +} + +interface SettingsSecretReference extends SettingsSecretSlot { + readonly reference: SecretReference; +} + +/** Each declared reference slot of `settings` that holds a reference, in field order. */ export function secretReferencesInSettings( schema: Schema.Top, settings: unknown, -): ReadonlyArray<{ readonly field: string; readonly reference: SecretReference }> { +): ReadonlyArray { if (settings === null || typeof settings !== "object") return []; const values = settings as Readonly>; - return secretReferenceSettingsFields(schema).flatMap((field) => { - const value = values[field]; - return isSecretReference(value) ? [{ field, reference: value }] : []; - }); + return secretReferenceSettingsFields(schema).flatMap( + ({ field, keyed }) => { + const value = values[field]; + if (!keyed) + return isSecretReference(value) ? [{ field, key: undefined, reference: value }] : []; + if (value === null || typeof value !== "object") return []; + return Object.entries(value).flatMap(([key, entry]) => + isSecretReference(entry) ? [{ field, key, reference: entry }] : [], + ); + }, + ); +} + +/** `settings` with each slot set to its value, keeping the other keys of a record field. */ +export function withSettingsSecrets>>( + settings: Settings, + slots: ReadonlyArray, +): Settings { + const next: Record = { ...settings }; + for (const { field, key, value } of slots) { + next[field] = key === undefined ? value : { ...(next[field] as object), [key]: value }; + } + return next as Settings; } diff --git a/packages/effect-codex-app-server/src/schema.ts b/packages/effect-codex-app-server/src/schema.ts index 2d5349752a00d..e9acee3bb9e91 100644 --- a/packages/effect-codex-app-server/src/schema.ts +++ b/packages/effect-codex-app-server/src/schema.ts @@ -1,3 +1,8 @@ export * from "./_generated/schema.gen.ts"; export * from "./_generated/meta.gen.ts"; export * from "./_generated/namespaces.gen.ts"; + +// Mirrors codex_protocol::protocol::MAX_THREAD_GOAL_OBJECTIVE_CHARS, which the +// generated schema does not carry. Codex counts Unicode scalar values (Rust +// `chars()`), not UTF-16 code units. +export const MAX_THREAD_GOAL_OBJECTIVE_CHARS = 4_000; diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts index e119922970d30..904fbdfcb5c22 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts @@ -1,3 +1,4 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { describe, expect, it } from "@effect/vitest"; import { @@ -58,7 +59,10 @@ function layerResolver( ) { return Layer.mergeAll( NodeServices.layer, - TestProviderHost.layer().pipe(Layer.provide(NodeServices.layer)), + NodeCrypto.layer, + TestProviderHost.layer().pipe( + Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), Layer.succeed(HostProcess.Platform, "linux"), Layer.succeed(HostProcess.Architecture, "x64"), Layer.succeed(HostProcess.Environment, environment), @@ -756,7 +760,10 @@ describe("AcpRegistrySupport", () => { Effect.provide( Layer.mergeAll( NodeServices.layer, - TestProviderHost.layer().pipe(Layer.provide(NodeServices.layer)), + NodeCrypto.layer, + TestProviderHost.layer().pipe( + Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), ), ), Effect.provideService(HostProcess.Platform, "linux"), @@ -1762,6 +1769,6 @@ describe("acpRegistryManagedBinaryDirectories", () => { architecture: "x64", }); expect(missing).toEqual([]); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), Effect.scoped), ); }); diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts index 1c9466dd1414d..99b1cfdc9f958 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts @@ -23,7 +23,8 @@ 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 Digest from "effect/crypto/Digest"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as Hex from "effect/encoding/Hex"; import * as FileSystem from "effect/FileSystem"; @@ -631,15 +632,17 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct AcpRegistryCatalog["Service"], never, | ChildProcessSpawner.ChildProcessSpawner - | Crypto.Crypto + | SecureRandom.SecureRandom + | Digest.Digest | FileSystem.FileSystem | HttpClient.HttpClient | Path.Path | ProviderHost.ProviderHost > { - const crypto = yield* Crypto.Crypto; + const random = yield* SecureRandom.SecureRandom; + const digester = yield* Digest.Digest; const sha256Hex = (data: Uint8Array) => - crypto.digest("SHA-256", data).pipe(Effect.map(Hex.encode), Effect.orDie); + digester.digest(Digest.sha256, data).pipe(Effect.map(Hex.encode), Effect.orDie); const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const httpClient = yield* HttpClient.HttpClient; @@ -776,7 +779,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct .pipe(Effect.flatMap(decodeRegistryText), Effect.option); const writeRegistryCache = (text: string) => - crypto.randomUUIDv4().pipe( + random.uuidV4().pipe( Effect.flatMap((id) => { const temporaryPath = `${registryCachePath}.${process.pid}-${id}.tmp`; return fileSystem diff --git a/packages/provider-acp-registry/src/server/adapter.ts b/packages/provider-acp-registry/src/server/adapter.ts index 4a3fb1ecd5942..1b8b4240fd00e 100644 --- a/packages/provider-acp-registry/src/server/adapter.ts +++ b/packages/provider-acp-registry/src/server/adapter.ts @@ -20,7 +20,7 @@ import { readCustomModelEntries } from "@t3tools/shared/model"; import { AcpRegistrySettings } from "../settings.ts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { resolveSelfInvocation, type SelfInvocation } from "@t3tools/shared/nodeRuntime"; -import * as Crypto from "effect/Crypto"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; @@ -77,7 +77,7 @@ export interface AcpRegistryAdapterV2Options { ) => Effect.Effect< AcpSessionRuntime.AcpSessionRuntime["Service"], EffectAcpErrors.AcpError, - ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | Scope.Scope + ChildProcessSpawner.ChildProcessSpawner | SecureRandom.SecureRandom | Scope.Scope >; readonly continuationRequests?: Parameters[0]["continuationRequests"]; readonly assertComplete?: Effect.Effect; @@ -139,7 +139,7 @@ function makeAcpRegistryRuntime( ): Effect.Effect< AcpSessionRuntime.AcpSessionRuntime["Service"], EffectAcpErrors.AcpError, - ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | Scope.Scope + ChildProcessSpawner.ChildProcessSpawner | SecureRandom.SecureRandom | Scope.Scope > => Effect.gen(function* () { const { processEnvironment, ...runtimeInput } = input; @@ -310,7 +310,7 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu export type AcpRegistryAdapterV2DriverEnv = | ChildProcessSpawner.ChildProcessSpawner - | Crypto.Crypto + | SecureRandom.SecureRandom | FileSystem.FileSystem | AcpRegistrySupport.AcpRegistryCatalog | IdAllocator.IdAllocatorV2 diff --git a/packages/provider-acp-registry/src/server/auth.test.ts b/packages/provider-acp-registry/src/server/auth.test.ts index 47ce8cabb188b..b81e2e3fba73e 100644 --- a/packages/provider-acp-registry/src/server/auth.test.ts +++ b/packages/provider-acp-registry/src/server/auth.test.ts @@ -1,4 +1,6 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as Layer from "effect/Layer"; import { assert, it } from "@effect/vitest"; import { ProviderInstanceId, type ProviderAuthState } from "@t3tools/contracts"; import { AcpRegistrySettings } from "../settings.ts"; @@ -230,7 +232,7 @@ it.effect("keeps local credentials separate from a matching registry agent ID", owner: "provider", key: "acp:local:test-agent", }); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect( @@ -264,7 +266,7 @@ it.effect( assert.deepEqual(h.closed, [1, 2]); yield* h.controller.logout(Effect.void); assert.deepEqual(h.changed, [true, false]); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect( @@ -308,7 +310,7 @@ it.effect( yield* h.phase("succeeded"); assert.deepEqual(h.started, [3]); assert.deepEqual(h.changed, [true]); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect("cancels the login PTY and rejects further terminal input", () => @@ -329,7 +331,7 @@ it.effect("cancels the login PTY and rejects further terminal input", () => }).pipe(Effect.result))._tag, "Failure", ); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect("does not report authentication when post-login verification fails", () => @@ -343,5 +345,5 @@ it.effect("does not report authentication when post-login verification fails", ( yield* h.phase("failed"); assert.deepEqual(h.changed, []); assert.isTrue(h.killed()); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); diff --git a/packages/provider-acp-registry/src/server/auth.ts b/packages/provider-acp-registry/src/server/auth.ts index 29da27bb291ba..240bca67cea57 100644 --- a/packages/provider-acp-registry/src/server/auth.ts +++ b/packages/provider-acp-registry/src/server/auth.ts @@ -4,7 +4,7 @@ import { type ProviderInstanceId, } from "@t3tools/contracts"; import type { AcpRegistrySettings } from "../settings.ts"; -import * as Crypto from "effect/Crypto"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; @@ -39,7 +39,7 @@ export const makeAcpRegistryAuth = Effect.fn("makeAcpRegistryAuth")(function* (o }) { const catalog = yield* AcpRegistrySupport.AcpRegistryCatalog; const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const crypto = yield* Crypto.Crypto; + const random = yield* SecureRandom.SecureRandom; const pty = yield* Effect.serviceOption(PtyAdapter.PtyAdapter); const coordinator = yield* Effect.serviceOption( AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, @@ -75,7 +75,7 @@ export const makeAcpRegistryAuth = Effect.fn("makeAcpRegistryAuth")(function* (o Layer.provide( Layer.mergeAll( Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner), - Layer.succeed(Crypto.Crypto, crypto), + Layer.succeed(SecureRandom.SecureRandom, random), ), ), ), diff --git a/packages/provider-acp-registry/src/server/authenticationState.test.ts b/packages/provider-acp-registry/src/server/authenticationState.test.ts index 09229cc300e4d..5111c6b349682 100644 --- a/packages/provider-acp-registry/src/server/authenticationState.test.ts +++ b/packages/provider-acp-registry/src/server/authenticationState.test.ts @@ -1,4 +1,6 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as Layer from "effect/Layer"; import { assert, it } from "@effect/vitest"; import { ProviderInstanceId } from "@t3tools/contracts"; import { AcpRegistrySettings } from "../settings.ts"; @@ -10,7 +12,7 @@ import { makeAcpRegistryAuthenticationState } from "./authenticationState.ts"; const settings = Schema.decodeSync(AcpRegistrySettings)({ agentId: "devin" }); -it.layer(NodeServices.layer)("ACP sign-in confirmation", (it) => { +it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("ACP sign-in confirmation", (it) => { it.effect("restores explicit sign-in across driver recreation and server restart", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/packages/provider-acp-registry/src/server/authenticationState.ts b/packages/provider-acp-registry/src/server/authenticationState.ts index 0d076781edf61..44502ceae4670 100644 --- a/packages/provider-acp-registry/src/server/authenticationState.ts +++ b/packages/provider-acp-registry/src/server/authenticationState.ts @@ -1,6 +1,6 @@ import type { ProviderInstanceEnvironment, ProviderInstanceId } from "@t3tools/contracts"; import type { AcpRegistrySettings } from "../settings.ts"; -import * as Crypto from "effect/Crypto"; +import * as Digest from "effect/crypto/Digest"; import * as Effect from "effect/Effect"; import * as Hex from "effect/encoding/Hex"; import * as FileSystem from "effect/FileSystem"; @@ -16,9 +16,11 @@ const decodeState = Schema.decodeUnknownEffect( ); const encodeJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); const hash = Effect.fn("AcpRegistryAuthenticationState.hash")(function* (value: unknown) { - const crypto = yield* Crypto.Crypto; + const crypto = yield* Digest.Digest; const json = yield* encodeJson(value).pipe(Effect.orDie); - const digest = yield* crypto.digest("SHA-256", new TextEncoder().encode(json)).pipe(Effect.orDie); + const digest = yield* crypto + .digest(Digest.sha256, new TextEncoder().encode(json)) + .pipe(Effect.orDie); return Hex.encode(digest); }); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index 4cce056ba72cf..c154b7a2bc6fd 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -11,7 +11,8 @@ import { AcpRegistrySettings } from "../settings.ts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { createModelCapabilities } from "@t3tools/shared/model"; import * as Clock from "effect/Clock"; -import * as Crypto from "effect/Crypto"; +import * as Digest from "effect/crypto/Digest"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; @@ -463,7 +464,10 @@ export const checkAcpRegistryProviderReadiness = Effect.fn( : snapshot; }); -export type AcpRegistryDriverEnv = AcpRegistryAdapterV2DriverEnv | ProviderHost.ProviderHost; +export type AcpRegistryDriverEnv = + | AcpRegistryAdapterV2DriverEnv + | Digest.Digest + | ProviderHost.ProviderHost; export const AcpRegistryDriver: ProviderDriver = { driverKind: DRIVER_KIND, @@ -495,7 +499,7 @@ export const AcpRegistryDriver: ProviderDriver, ): Effect.Effect => { const provided = effect.pipe( Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), - Effect.provideService(Crypto.Crypto, crypto), + Effect.provideService(SecureRandom.SecureRandom, random), ); return Option.isSome(runtimeCoordinator) ? provided.pipe( @@ -792,7 +796,7 @@ export const AcpRegistryDriver: ProviderDriver confirmedAuthentication.set(false)), Effect.tap(() => liveSnapshotSemaphore.withPermit( diff --git a/packages/provider-acp-registry/src/server/probe.ts b/packages/provider-acp-registry/src/server/probe.ts index 0ceabbcfd81a7..58b16e337079e 100644 --- a/packages/provider-acp-registry/src/server/probe.ts +++ b/packages/provider-acp-registry/src/server/probe.ts @@ -11,7 +11,7 @@ import { type ServerProviderSlashCommand, } from "@t3tools/contracts"; import { AcpRegistrySettings } from "../settings.ts"; -import * as Crypto from "effect/Crypto"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; @@ -320,11 +320,13 @@ export const probeAcpRegistryConfiguration = Effect.fn("AcpRegistryProbe.probeCo ): Effect.fn.Return< AcpRegistryConfigurationProbeResult, AcpRegistryOperationError, - AcpRegistrySupport.AcpRegistryCatalog | ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto + | AcpRegistrySupport.AcpRegistryCatalog + | ChildProcessSpawner.ChildProcessSpawner + | SecureRandom.SecureRandom > { const catalog = yield* AcpRegistrySupport.AcpRegistryCatalog; const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const crypto = yield* Crypto.Crypto; + const random = yield* SecureRandom.SecureRandom; const pty = yield* Effect.serviceOption(PtyAdapter.PtyAdapter); const result = yield* Effect.gen(function* () { @@ -362,7 +364,7 @@ export const probeAcpRegistryConfiguration = Effect.fn("AcpRegistryProbe.probeCo Layer.provide( Layer.mergeAll( Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner), - Layer.succeed(Crypto.Crypto, crypto), + Layer.succeed(SecureRandom.SecureRandom, random), ), ), ), @@ -463,7 +465,7 @@ const makeAcpRegistryManagementRuntime = Effect.fn("AcpRegistryProbe.makeManagem function* (input: AcpRegistryManagementInput) { const catalog = yield* AcpRegistrySupport.AcpRegistryCatalog; const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const crypto = yield* Crypto.Crypto; + const random = yield* SecureRandom.SecureRandom; const runtimeCoordinator = yield* Effect.serviceOption( AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, ); @@ -487,7 +489,7 @@ const makeAcpRegistryManagementRuntime = Effect.fn("AcpRegistryProbe.makeManagem Layer.provide( Layer.mergeAll( Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner), - Layer.succeed(Crypto.Crypto, crypto), + Layer.succeed(SecureRandom.SecureRandom, random), ), ), ), diff --git a/packages/provider-acp/src/server/AcpSessionRuntime.ts b/packages/provider-acp/src/server/AcpSessionRuntime.ts index 4544a4ac5ce9d..0ef446ef3453a 100644 --- a/packages/provider-acp/src/server/AcpSessionRuntime.ts +++ b/packages/provider-acp/src/server/AcpSessionRuntime.ts @@ -6,7 +6,7 @@ import * as NodePath from "node:path"; import * as Cause from "effect/Cause"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; -import * as Crypto from "effect/Crypto"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; @@ -21,6 +21,7 @@ import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; +import * as SubscriptionRef from "effect/SubscriptionRef"; import * as ChildProcess from "effect/process/ChildProcess"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as EffectAcpClient from "effect-acp/client"; @@ -1126,6 +1127,8 @@ export class AcpSessionRuntime extends Context.Service< readonly drainEvents: Effect.Effect; readonly getModeState: Effect.Effect; readonly getConfigOptions: Effect.Effect>; + /** The current configuration options, then each later change. */ + readonly configOptionChanges: Stream.Stream>; readonly loadSession: ( sessionId: string, options?: AcpSessionActivationOptions, @@ -1137,6 +1140,7 @@ export class AcpSessionRuntime extends Context.Service< readonly forkSession: ( sessionId: string, options?: AcpSessionActivationOptions, + meta?: NonNullable, ) => Effect.Effect; readonly listSessions: ( cursor?: string, @@ -1236,16 +1240,16 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( ): Effect.fn.Return< AcpSessionRuntime["Service"], EffectAcpErrors.AcpError, - ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | Scope.Scope + ChildProcessSpawner.ChildProcessSpawner | SecureRandom.SecureRandom | Scope.Scope > { - const crypto = yield* Crypto.Crypto; + const random = yield* SecureRandom.SecureRandom; const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const runtimeScope = yield* Scope.fork(yield* Scope.Scope); const eventQueue = yield* Queue.unbounded(); const modeStateRef = yield* Ref.make(undefined); const toolCallsRef = yield* Ref.make(new Map()); const shownToolCallIds = new Set(); - const assistantItemRuntimeId = yield* crypto.randomUUIDv4().pipe( + const assistantItemRuntimeId = yield* random.uuidV4().pipe( Effect.mapError( (cause) => new EffectAcpErrors.AcpTransportError({ @@ -1255,7 +1259,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( ), ); const assistantSegmentRef = yield* Ref.make({ nextSegmentIndex: 0 }); - const configOptionsRef = yield* Ref.make(sessionConfigOptionsFromSetup(undefined)); + const configOptionsRef = yield* SubscriptionRef.make(sessionConfigOptionsFromSetup(undefined)); const initializeStateRef = yield* Ref.make({ _tag: "NotStarted" }); const startStateRef = yield* Ref.make({ _tag: "NotStarted" }); const startupMetadataRef = yield* Ref.make>( @@ -1682,17 +1686,26 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( const acp = yield* Effect.service(EffectAcpClient.AcpClient).pipe(Effect.provide(acpContext)); + // Counts applied `config_option_update`s; see setConfigOption. + const configOptionUpdates = yield* Ref.make(0); const processSessionUpdate = (notification: EffectAcpSchema.SessionNotification) => - handleSessionUpdate({ - queue: eventQueue, - modeStateRef, - configOptionsRef, - toolCallsRef, - shownToolCallIds, - assistantSegmentRef, - assistantItemRuntimeId, - params: notification, - }); + (notification.update.sessionUpdate === "config_option_update" + ? Ref.update(configOptionUpdates, (count) => count + 1) + : Effect.void + ).pipe( + Effect.andThen( + handleSessionUpdate({ + queue: eventQueue, + modeStateRef, + configOptionsRef, + toolCallsRef, + shownToolCallIds, + assistantSegmentRef, + assistantItemRuntimeId, + params: notification, + }), + ), + ); yield* acp.handleSessionUpdate((notification) => notificationSemaphore.withPermit( @@ -1807,7 +1820,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( value: string | boolean, allowUnlistedValue: boolean, ): Effect.fn.Return { - const configOptions = yield* Ref.get(configOptionsRef); + const configOptions = yield* SubscriptionRef.get(configOptionsRef); const configOption = findSessionConfigOption(configOptions, configId); if (!configOption) { return; @@ -1868,7 +1881,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( | EffectAcpSchema.ResumeSessionResponse, ) { const configOptions = sessionConfigOptionsFromSetup(response); - yield* Ref.set(configOptionsRef, configOptions); + yield* SubscriptionRef.set(configOptionsRef, configOptions); yield* Queue.offer(eventQueue, { _tag: "ConfigOptionsUpdated", configOptions, @@ -1911,9 +1924,15 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( sessionSetupResult.configOptions !== undefined && sessionSetupResult.configOptions !== null ) { - yield* Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(sessionSetupResult)); + yield* SubscriptionRef.set( + configOptionsRef, + sessionConfigOptionsFromSetup(sessionSetupResult), + ); } else if (!syntheticReplayIdle) { - yield* Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(sessionSetupResult)); + yield* SubscriptionRef.set( + configOptionsRef, + sessionConfigOptionsFromSetup(sessionSetupResult), + ); } const nextState = { sessionId, @@ -2016,7 +2035,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( validateConfigOptionValue(configId, value, options?.allowUnlistedValue === true).pipe( Effect.andThen(getStartedState), Effect.flatMap((started) => - Ref.get(configOptionsRef).pipe( + SubscriptionRef.get(configOptionsRef).pipe( Effect.flatMap((configOptions) => { const existing = findSessionConfigOption(configOptions, configId); if (existing && configOptionCurrentValueMatches(existing, value)) { @@ -2037,11 +2056,27 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( configId, value: String(value), } satisfies EffectAcpSchema.SetSessionConfigOptionRequest); - return runLoggedRequest( - "session/set_config_option", - requestPayload, - acp.agent.setSessionConfigOption(requestPayload), - ).pipe(Effect.tap((response) => updateConfigOptions(response))); + // An update the agent pushed while the write was in flight is + // newer than its result: Kiro 2.32 answers a `model` write + // without `model`, then advertises it, and that update can be + // handled before this fiber resumes. The result then stays out. + return Ref.get(configOptionUpdates).pipe( + Effect.flatMap((updatesBefore) => + runLoggedRequest( + "session/set_config_option", + requestPayload, + acp.agent.setSessionConfigOption(requestPayload), + ).pipe( + Effect.tap((response) => + Ref.get(configOptionUpdates).pipe( + Effect.flatMap((updatesNow) => + updatesNow === updatesBefore ? updateConfigOptions(response) : Effect.void, + ), + ), + ), + ), + ), + ); }), ), ), @@ -2249,7 +2284,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( ); yield* Ref.set(modeStateRef, parseSessionModeState(sessionSetupResult)); - yield* Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(sessionSetupResult)); + yield* SubscriptionRef.set(configOptionsRef, sessionConfigOptionsFromSetup(sessionSetupResult)); const nextState = { sessionId, @@ -2406,7 +2441,8 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( getEvents: () => Stream.fromQueue(eventQueue), drainEvents, getModeState: Ref.get(modeStateRef), - getConfigOptions: Ref.get(configOptionsRef), + getConfigOptions: SubscriptionRef.get(configOptionsRef), + configOptionChanges: SubscriptionRef.changes(configOptionsRef), loadSession: (sessionId, activationOptions) => start.pipe( Effect.flatMap((started) => { @@ -2437,7 +2473,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( }), Effect.flatMap((response) => adoptSession(sessionId, response)), ), - forkSession: (sessionId, activationOptions) => + forkSession: (sessionId, activationOptions, meta) => start.pipe( Effect.flatMap((started) => { const requestPayload = { @@ -2445,6 +2481,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( cwd: options.cwd, ...sessionSetupFields(started.initializeResult), mcpServers: sessionMcpServers(started.initializeResult, activationOptions), + ...(meta === undefined ? {} : { _meta: meta }), } satisfies EffectAcpSchema.ForkSessionRequest; return runLoggedRequest( "session/fork", @@ -2639,7 +2676,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( if (modeState?.currentModeId === modeId) { return {} satisfies EffectAcpSchema.SetSessionModeResponse; } - const modeConfigOption = (yield* Ref.get(configOptionsRef))?.find( + const modeConfigOption = (yield* SubscriptionRef.get(configOptionsRef))?.find( (option) => option.category === "mode" && option.type === "select", ); if (modeConfigOption === undefined && modeState !== undefined) { @@ -2690,7 +2727,7 @@ export const layer = ( ): Layer.Layer< AcpSessionRuntime, EffectAcpErrors.AcpError, - ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto + ChildProcessSpawner.ChildProcessSpawner | SecureRandom.SecureRandom > => Layer.effect(AcpSessionRuntime, make(options)); function sessionConfigOptionsFromSetup( @@ -2742,7 +2779,9 @@ const handleSessionUpdate = }: { readonly queue: Queue.Queue; readonly modeStateRef: Ref.Ref; - readonly configOptionsRef: Ref.Ref>; + readonly configOptionsRef: SubscriptionRef.SubscriptionRef< + ReadonlyArray + >; readonly toolCallsRef: Ref.Ref>; readonly shownToolCallIds: Set; readonly assistantSegmentRef: Ref.Ref; @@ -2751,7 +2790,7 @@ const handleSessionUpdate = }): Effect.fn.Return { if (params.update.sessionUpdate === "config_option_update") { const configOptions = params.update.configOptions; - yield* Ref.set(configOptionsRef, configOptions); + yield* SubscriptionRef.set(configOptionsRef, configOptions); yield* Ref.update( modeStateRef, (current) => parseSessionModeState({ configOptions }) ?? current, diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index b7c77c4049591..985f6c8ee9887 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -42,10 +42,11 @@ import { resolveT3McpToolId } from "@t3tools/shared/t3McpToolPresentation"; import { compactDynamicToolOutput, htmlRenderFromToolItem } from "@t3tools/shared/toolOutput"; import { FILE_HEADERS_ONLY, formatPatch, structuredPatch } from "diff"; import * as Cause from "effect/Cause"; -import * as Crypto from "effect/Crypto"; +import * as Clock from "effect/Clock"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; -import type * as Duration from "effect/Duration"; +import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Equal from "effect/Equal"; import * as Exit from "effect/Exit"; @@ -311,6 +312,12 @@ export interface AcpAdapterV2Flavor { readonly normalizeSessionUpdate?: ( notification: EffectAcpSchema.SessionNotification, ) => EffectAcpSchema.SessionNotification; + /** + * Agent updates that belong to no turn (Kiro's own cloud-config fetch). They + * are dropped before anything reads them, so they neither show in the turn + * nor count as it starting. + */ + readonly ignoreSessionUpdate?: (notification: EffectAcpSchema.SessionNotification) => boolean; readonly onAvailableCommandsUpdate?: ( commands: ReadonlyArray, ) => Effect.Effect; @@ -338,10 +345,16 @@ export interface AcpAdapterV2Flavor { ) => Effect.Effect< AcpSessionRuntime.AcpSessionRuntime["Service"], EffectAcpErrors.AcpError, - ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | Scope.Scope + ChildProcessSpawner.ChildProcessSpawner | SecureRandom.SecureRandom | Scope.Scope >; readonly customModels?: ReadonlyArray; readonly resolveModelId?: (selection: ModelSelection) => string | undefined; + /** + * The agent advertises its model option only after `session/new` returns + * (Kiro sends it in a `config_option_update`), so in-session model switching + * is not inferred from the setup result. + */ + readonly modelOptionArrivesLate?: boolean; readonly getModelContextWindow?: ( selection: ModelSelection, session: AcpSessionRuntime.AcpSessionRuntimeStartResult, @@ -351,9 +364,23 @@ export interface AcpAdapterV2Flavor { readonly startResult: AcpSessionRuntime.AcpSessionRuntimeStartResult; readonly modelSelection: ModelSelection; }) => Effect.Effect; + /** + * Model-selection option ids `applyModelSelection` sets itself under a + * native id, which the generic option loop then skips (Kiro's + * `reasoningEffort` is its `effortLevel`). + */ + readonly ownedModelOptionIds?: ReadonlyArray; readonly sessionModeForPolicy?: ( policy: ProviderAdapter.ProviderAdapterV2RuntimePolicy, ) => string | undefined; + /** + * Native select-option values to apply for a runtime policy (e.g. Kiro's + * `autopilot`), set on every session configure. A value the session does + * not advertise is skipped; an agent rejecting it fails the session. + */ + readonly sessionConfigForPolicy?: ( + policy: ProviderAdapter.ProviderAdapterV2RuntimePolicy, + ) => ReadonlyArray<{ readonly id: string; readonly value: string }>; /** * The runtime mode a native session mode grants, for flavors whose modes are permission levels. * Under a policy ceiling, a mode the user picks that this does not place under it is not applied. @@ -390,6 +417,41 @@ export interface AcpAdapterV2Flavor { ) => Effect.Effect; readonly subagentsIdleOnTurnCompletion?: boolean; readonly supportsCompaction?: boolean; + /** + * Native steering: `send` queues a message into the running turn and returns the + * agent's id for it, which `injectedSteerId` reads from the update that delivers it. + */ + readonly steering?: { + readonly send: ( + runtime: AcpSessionRuntime.AcpSessionRuntime["Service"], + sessionId: string, + text: string, + ) => Effect.Effect; + readonly injectedSteerId: ( + notification: EffectAcpSchema.SessionNotification, + ) => string | undefined; + }; + /** + * Native fork from an earlier turn. `nativeTurnId` reads the agent's id for a running + * turn's prompt, which the turn keeps as its native ref; forking from that turn sends + * `forkMeta(id)` as the `session/fork` `_meta`. + */ + readonly forkFromTurn?: { + readonly supported: ( + initializeResult: AcpSessionRuntime.AcpSessionRuntimeStartResult["initializeResult"], + ) => boolean; + readonly nativeTurnId: ( + notification: EffectAcpSchema.SessionNotification, + ) => string | undefined; + readonly forkMeta: ( + nativeTurnId: string, + ) => NonNullable; + }; + /** Compacts with the agent's own request, for agents that answer a `/compact` prompt as chat. */ + readonly compactSession?: ( + runtime: AcpSessionRuntime.AcpSessionRuntime["Service"], + sessionId: string, + ) => Effect.Effect; readonly runtimeHarness?: string; readonly registerExtensions?: ( context: AcpAdapterV2ExtensionContext, @@ -430,6 +492,15 @@ export interface AcpAdapterV2Flavor { readonly assertComplete?: Effect.Effect; /** Interrupt the local prompt fiber before `session/cancel` (Grok wedged prompts). */ readonly interruptPromptOnCancel?: boolean; + /** + * Hold `session/cancel` until an update after `session/prompt` matches `isStart`, + * or `bound` has passed; skip it if the prompt settles first. Kiro 2.27.1 can + * drop a cancel sent just after the prompt and run the turn to completion. + */ + readonly cancelAfterPromptStarts?: { + readonly isStart: (update: EffectAcpSchema.SessionUpdate) => boolean; + readonly bound: Duration.Input; + }; /** * The agent's PromptResponse.usage counters read per-turn. The ACP spec * leaves usage semantics open, so this stays unset until proven live. @@ -533,6 +604,8 @@ export interface AcpAdapterV2Options { }; readonly testHooks?: { readonly onDeferredFinalizeScheduled?: (debounce: Duration.Input) => Effect.Effect; + /** `cancelAfterPromptStarts`: Stop is holding `session/cancel` until the prompt starts. */ + readonly onCancelHeld?: () => Effect.Effect; readonly afterPromptWireSettled?: () => Effect.Effect; readonly afterPromptSettledWithBackgroundWork?: () => Effect.Effect; readonly onNativeResponseLifecycle?: (event: { @@ -647,15 +720,57 @@ export const AcpProviderCapabilitiesV2 = { }, } satisfies OrchestrationV2ProviderCapabilities; +const STEER_DELIVERY_BOUND = "2 seconds"; + +/** + * `session/fork` `_meta` for a fork from `providerTurnId`: none for the session head, + * the flavor's meta for a turn the agent named, or `null` when the agent can't fork there. + */ +function forkFromTurnMetaFor(input: { + readonly driver: ProviderDriverKind; + readonly flavor: Pick; + readonly canForkFromTurn: boolean; + readonly forkInput: ProviderAdapter.ProviderAdapterV2ForkThreadInput; +}): NonNullable | undefined | null { + const { forkInput } = input; + if (forkInput.providerTurnId === undefined) return undefined; + const turns = (forkInput.sourceProviderTurns ?? []).filter( + (turn) => turn.providerThreadId === forkInput.sourceProviderThread.id, + ); + const target = turns.find((turn) => turn.id === forkInput.providerTurnId); + if (target === undefined) return null; + if (turns.every((turn) => turn.ordinal <= target.ordinal)) return undefined; + const ref = target.nativeTurnRef; + if ( + input.flavor.forkFromTurn === undefined || + !input.canForkFromTurn || + ref === null || + ref.driver !== input.driver || + ref.strength !== "strong" || + ref.nativeId === null + ) { + return null; + } + return input.flavor.forkFromTurn.forkMeta(ref.nativeId); +} + +function isCompactionMessage(message: ProviderAdapter.ProviderAdapterV2TurnMessage): boolean { + return message.text.trim() === "/compact" && message.attachments.length === 0; +} + function negotiatedCapabilities( base: OrchestrationV2ProviderCapabilities, started: AcpSessionRuntime.AcpSessionRuntimeStartResult, + modelOptionArrivesLate: boolean, + forksFromTurn: boolean, ): OrchestrationV2ProviderCapabilities { const agent = started.initializeResult.agentCapabilities ?? {}; const session = agent.sessionCapabilities; const setup = started.sessionSetupResult; const canSwitchModel = - findModelConfigOption(setup.configOptions) !== undefined || setup.models != null; + modelOptionArrivesLate || + findModelConfigOption(setup.configOptions) !== undefined || + setup.models != null; const canLoad = agent.loadSession === true; const canFork = session?.fork != null; return { @@ -668,7 +783,7 @@ function negotiatedCapabilities( ...base.threads, canReadThreadSnapshot: canLoad, canForkThread: canFork, - canForkFromTurn: false, + canForkFromTurn: canFork && forksFromTurn, }, tools: { ...base.tools, @@ -1111,6 +1226,18 @@ function toolStatus( type ProjectedToolStatus = ReturnType | "interrupted"; +/** + * Some agents answer Stop's `session/cancel` by failing the tools and subagents + * that were running (Kiro: "Tool execution was cancelled by the user."). After + * Stop, a failure is shown as the interruption it was. + */ +function stoppedToolStatus( + turn: Pick, + tool: AcpToolCallState, +): "interrupted" | undefined { + return turn.interrupted && tool.status === "failed" ? "interrupted" : undefined; +} + function nodeStatus(status: ProjectedToolStatus): OrchestrationV2ExecutionNode["status"] { return status === "pending" ? "running" : status; } @@ -1241,8 +1368,16 @@ interface ActiveAcpTurn { promptSettledStatus: "completed" | "interrupted" | "failed" | "cancelled" | null; workAccepted: boolean; readonly promptWireSettled: Deferred.Deferred; + /** Completed once `session/prompt` is the runtime's active prompt. */ + readonly promptDispatched: Deferred.Deferred; + /** Clock millis just before `session/prompt` was handed to the runtime. */ + promptSentAt: number | null; + /** Completed when an update after dispatch matches `cancelAfterPromptStarts.isStart`. */ + readonly promptStarted: Deferred.Deferred; promptUsage: EffectAcpSchema.Usage | undefined; backgroundFinalizeGeneration: number; + /** The agent's own id for this turn's prompt, from `forkFromTurn.nativeTurnId`. */ + nativePromptId: string | undefined; } type AcpRuntimeTeardownState = @@ -1506,7 +1641,7 @@ function shouldPersistToolUpdate( export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( options: AcpAdapterV2Options, ) { - const crypto = yield* Crypto.Crypto; + const random = yield* SecureRandom.SecureRandom; const fileSystem = yield* FileSystem.FileSystem; const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; const agentScope = yield* AgentScope; @@ -1708,6 +1843,15 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( input.runtimePolicy; const events = yield* Queue.unbounded(); const activeTurn = yield* Ref.make(null); + // Keyed by the agent's steer id; an injection can arrive before its send returns. + const steerInjections = new Map>(); + const steerInjection = (steerId: string) => { + const existing = steerInjections.get(steerId); + if (existing !== undefined) return existing; + const created = Deferred.makeUnsafe(); + steerInjections.set(steerId, created); + return created; + }; let pendingStopCloseTurn: ActiveAcpTurn | null = null; let followsAgentWorkState = false; let agentWork: Extract< @@ -2223,8 +2367,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ? {} : { requestLogger: nativeLogging.requestLogger }), protocolLogging: nativeLogging?.protocolLogging ?? { - logIncoming: true, - logOutgoing: true, + logIncoming: false, + logOutgoing: false, logger: () => Effect.void, }, }; @@ -2858,9 +3002,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const emitSubagent = Effect.fnUntraced(function* ( context: ActiveAcpTurn, - update: AcpAdapterV2SubagentUpdate, + reported: AcpAdapterV2SubagentUpdate, ) { - // Hydration uses a new toolCallId but references the original child by task id. + // See stoppedToolStatus: after Stop, a failed subagent was interrupted. + const update: AcpAdapterV2SubagentUpdate = + context.interrupted && reported.status === "failed" + ? { ...reported, status: "interrupted" } + : reported; + // Hydration uses a new toolCallId but references the original child by subagent_id or task id. const existing = context.subagents.get(update.nativeTaskId) ?? (update.childSessionId !== null @@ -3356,10 +3505,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (update.sessionUpdate === "tool_call" || update.sessionUpdate === "tool_call_update") { for (const event of parseSessionUpdateEvent(notification).events) { if (event._tag === "ToolCallUpdated") { + const tool = flavor.normalizeToolCall?.(event.toolCall) ?? event.toolCall; yield* projectSubagentTool( subagent, notification.sessionId, - flavor.normalizeToolCall?.(event.toolCall) ?? event.toolCall, + tool, + stoppedToolStatus(owner.owner, tool), ); } } @@ -3725,7 +3876,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* rearmDeferredFinalize(context); return; } - const status = projectedStatus ?? toolStatus(toolCall.status); + const status = + projectedStatus ?? stoppedToolStatus(context, toolCall) ?? toolStatus(toolCall.status); const now = yield* DateTime.now; const nativeItemId = `${context.nativeThreadId}:tool:${toolCall.toolCallId}`; const ordinal = yield* resolveItemOrdinal(context, nativeItemId); @@ -5012,7 +5164,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } continue; } - yield* projectSubagentTool(subagent, notification.sessionId, toolCall); + yield* projectSubagentTool( + subagent, + notification.sessionId, + toolCall, + stoppedToolStatus(context, toolCall), + ); } return; } @@ -5977,10 +6134,37 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } }); + // Only the flavor's own start marker counts: agents also send late + // updates for the previous prompt (Kiro's context usage) and echoes + // that arrive before they would honor a cancel. + const markPromptStarted = Effect.fnUntraced(function* ( + notification: EffectAcpSchema.SessionNotification, + ) { + const promptStarts = flavor.cancelAfterPromptStarts?.isStart; + if (promptStarts === undefined) return; + const context = yield* Ref.get(activeTurn); + if (context === null || context.nativeThreadId !== notification.sessionId) return; + if (!(yield* Deferred.isDone(context.promptDispatched))) return; + if (!promptStarts(notification.update)) return; + yield* Deferred.succeed(context.promptStarted, undefined); + }); const projectAcpRuntimeSessionUpdateEffect = /* Provider events include streaming deltas; avoid a span for each update. */ Effect.fnUntraced( function* (rawNotification: EffectAcpSchema.SessionNotification) { + if (flavor.ignoreSessionUpdate?.(rawNotification) === true) return; + const nativePromptId = flavor.forkFromTurn?.nativeTurnId(rawNotification); + if (nativePromptId !== undefined) { + const context = yield* Ref.get(activeTurn); + if (context !== null && context.nativeThreadId === rawNotification.sessionId) { + context.nativePromptId ??= nativePromptId; + } + } + const injectedSteerId = flavor.steering?.injectedSteerId(rawNotification); + if (injectedSteerId !== undefined) { + yield* Deferred.succeed(steerInjection(injectedSteerId), undefined); + } + yield* markPromptStarted(rawNotification); const embedded = embeddedTerminalIdsFromSessionUpdate(rawNotification); if (embedded !== undefined) { rememberEmbeddedTerminals({ @@ -6197,8 +6381,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* userInput.acknowledgeNativeResponse; return response ?? ({ outcome: { outcome: "cancelled" } } as const); } - const dispositionFor = (policy: ProviderAdapter.ProviderAdapterV2RuntimePolicy) => - (flavor.permissionDisposition ?? acpPermissionDisposition)(policy, params); + const dispositionFor = ( + policy: ProviderAdapter.ProviderAdapterV2RuntimePolicy, + request: EffectAcpSchema.RequestPermissionRequest = params, + ) => (flavor.permissionDisposition ?? acpPermissionDisposition)(policy, request); if (followsAgentWorkState && dispositionFor(latestRuntimePolicy) === "ask") { if (!(yield* awaitRequestTurn(handlerGeneration))) return { outcome: { outcome: "cancelled" } } as const; @@ -6209,8 +6395,16 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const context = followsAgentWorkState ? yield* Ref.get(activeTurn) : yield* activeContext; + // Kiro sends the tool's kind on its `tool_call` and leaves it + // off the permission request for that call; take it from the + // tool already seen under the same id so policy can tell a + // read from a write. + const knownKind = context?.tools.get(params.toolCall.toolCallId)?.kind; const disposition = dispositionFor( context?.input.runtimePolicy ?? latestRuntimePolicy, + params.toolCall.kind == null && knownKind !== undefined + ? { ...params, toolCall: { ...params.toolCall, kind: knownKind } } + : params, ); if (disposition === "allow") { const optionId = selectAutoApprovedPermissionOption(params); @@ -6272,7 +6466,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( transportRequestId: pendingTransportRequestId, } = admitted.value.pending; const parsedPermission = parsePermissionRequest(params); - const decision = yield* Deferred.await(pendingDecision).pipe( + const answered = yield* Deferred.await(pendingDecision).pipe( Effect.ensuring( runRuntimeCallbackAtGeneration( handlerGeneration, @@ -6284,6 +6478,16 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ).pipe(Effect.asVoid), ), ); + // A card that never offered "this session" (Kiro's, whose + // allow_always saves a workspace rule) cannot be answered with + // it by a stale client or a hand-made respond call. + const offeredOptions = flavor.approvalOptions?.(params); + const decision = + answered === "acceptForSession" && + offeredOptions !== undefined && + !offeredOptions.some((option) => option.decision === "acceptForSession") + ? "accept" + : answered; if ( parsedPermission.kind !== "unknown" && (decision === "accept" || decision === "acceptForSession") @@ -6541,7 +6745,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const mcpBridge = yield* makeAcpMcpOverAcpBridge({ endpoint: mcpContext.endpoint, authorization: mcpContext.authorization, - allocateConnectionId: crypto.randomUUIDv4().pipe(Effect.orDie), + allocateConnectionId: random.uuidV4(), }); yield* Scope.addFinalizer(scope, mcpBridge.dispose); return mcpBridge; @@ -6562,7 +6766,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( .makeRuntime(makeRuntimeInput(runtimeGeneration, mcpContext, resumeSessionId)) .pipe( Effect.provideService(Scope.Scope, runtimeScope), - Effect.provideService(Crypto.Crypto, crypto), + Effect.provideService(SecureRandom.SecureRandom, random), Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner), Effect.provideService(AgentScope, agentScope), Effect.provideService(AgentScopeThreadId, threadId ?? undefined), @@ -6641,7 +6845,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ) .pipe( Effect.provideService(Scope.Scope, replacementScope), - Effect.provideService(Crypto.Crypto, crypto), + Effect.provideService(SecureRandom.SecureRandom, random), Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner), Effect.provideService(AgentScope, agentScope), Effect.provideService(AgentScopeThreadId, threadId ?? undefined), @@ -6816,7 +7020,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.set(activeSessionId, started.sessionId); yield* setActiveSessionSetup(started); rememberTerminalEnvironment(started.sessionId, yield* readMcpContext(input.threadId)); - const capabilities = negotiatedCapabilities(flavor.capabilities, started); + const capabilities = negotiatedCapabilities( + flavor.capabilities, + started, + flavor.modelOptionArrivesLate === true, + flavor.forkFromTurn?.supported(started.initializeResult) === true, + ); const canLoadSession = started.initializeResult.agentCapabilities?.loadSession === true; const canResumeSession = started.initializeResult.agentCapabilities?.sessionCapabilities?.resume != null; @@ -6974,6 +7183,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( return granted !== undefined && !isRuntimeModeAbove(granted, ceiling); }; const optionSelections = (modelSelection.options ?? []).flatMap((selection) => { + if (flavor.ownedModelOptionIds?.includes(selection.id) === true) return []; if (!withinCeiling(selection)) return []; return [ selection.value === ACP_EMPTY_OPTION_VALUE ? { ...selection, value: "" } : selection, @@ -7028,6 +7238,17 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }), ); } + for (const selection of flavor.sessionConfigForPolicy?.(runtimePolicy) ?? []) { + const option = (yield* runtime.getConfigOptions).find( + (candidate) => candidate.id === selection.id, + ); + if (option?.type !== "select" || option.currentValue === selection.value) continue; + const advertisedValues = option.options.flatMap((entry) => + "value" in entry ? [entry.value] : entry.options.map((choice) => choice.value), + ); + if (!advertisedValues.includes(selection.value)) continue; + yield* runtime.setConfigOption(selection.id, selection.value); + } const policyMode = flavor.sessionModeForPolicy?.(runtimePolicy); if (policyMode !== undefined) { yield* runtime.setMode(policyMode); @@ -7143,11 +7364,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( providerThreadId: context.input.providerThread.id, nodeId: context.input.rootNodeId, runAttemptId: context.input.attemptId, - nativeTurnRef: { - driver, - nativeId: context.nativeTurnId, - strength: "weak", - }, + nativeTurnRef: + context.nativePromptId === undefined + ? { driver, nativeId: context.nativeTurnId, strength: "weak" } + : { driver, nativeId: context.nativePromptId, strength: "strong" }, ordinal: context.input.providerTurnOrdinal, status, startedAt: context.startedAt, @@ -7206,6 +7426,30 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } }); + /** + * `cancelAfterPromptStarts`: waits until the agent started the prompt or the + * bound passed since `session/prompt` (since Stop, if none was sent). False + * when the prompt settled first, so there is nothing to cancel. + */ + const promptStillRunsAfterHold = Effect.fnUntraced(function* (context: ActiveAcpTurn) { + const hold = flavor.cancelAfterPromptStarts; + if (hold === undefined) return true; + if (yield* Deferred.isDone(context.promptStarted)) return true; + yield* options.testHooks?.onCancelHeld?.() ?? Effect.void; + const boundPassed = Effect.gen(function* () { + const now = yield* Clock.currentTimeMillis; + const elapsed = now - (context.promptSentAt ?? now); + yield* Effect.sleep( + Duration.millis(Math.max(0, Duration.toMillis(hold.bound) - elapsed)), + ); + }); + return yield* Effect.raceFirst( + Effect.raceFirst(Deferred.await(context.promptStarted), boundPassed).pipe( + Effect.as(true), + ), + Deferred.await(context.completed).pipe(Effect.as(false)), + ); + }); const quarantineStoppedRun = Effect.fnUntraced(function* () { yield* continuationPermit.withPermit( Effect.gen(function* () { @@ -7260,9 +7504,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } const now = yield* DateTime.now; if ( - flavor.supportsCompaction === true && - context.input.message.text.trim() === "/compact" && - context.input.message.attachments.length === 0 && + (flavor.supportsCompaction === true || flavor.compactSession !== undefined) && + isCompactionMessage(context.input.message) && settledStatus === "completed" ) { const nativeItemId = `${context.nativeTurnId}:compaction`; @@ -7380,6 +7623,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } } yield* Ref.set(activeTurn, null); + steerInjections.clear(); if ( postSettleContinuationEnabled && settledStatus === "completed" && @@ -7674,6 +7918,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const providerTurnId = deriveProviderTurnId(nativeTurnId); const completed = yield* Deferred.make(); const promptWireSettled = yield* Deferred.make(); + const promptDispatched = yield* Deferred.make(); + const promptStarted = yield* Deferred.make(); const rememberedContextUsage = (yield* Ref.get(contextUsageBySessionId)).get( requestedSessionId, ); @@ -7729,8 +7975,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( promptSettledStatus: null, workAccepted: false, promptWireSettled, + promptDispatched, + promptSentAt: null, + promptStarted, promptUsage: undefined, backgroundFinalizeGeneration: 0, + nativePromptId: undefined, }; const carryover = yield* Ref.getAndSet(carryoverSubagents, null); let rehydratedCarryoverSubagents: ReadonlyArray = []; @@ -7870,10 +8120,24 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ? undefined : yield* flavor.watchPromptOutcome(requestedSessionId); const promptGeneration = yield* Ref.get(runtimeCallbackGeneration); - yield* runtime.prompt({ prompt: promptParts!.prompt }).pipe( + const promptOptions = { dispatched: context.promptDispatched }; + context.promptSentAt = yield* Clock.currentTimeMillis; + const compactSession = isCompactionMessage(turnInput.message) + ? flavor.compactSession + : undefined; + yield* ( + compactSession === undefined + ? runtime.prompt({ prompt: promptParts!.prompt }, promptOptions) + : Deferred.succeed(context.promptDispatched, undefined).pipe( + Effect.andThen(compactSession(runtime, requestedSessionId)), + Effect.as({ stopReason: "end_turn" } satisfies EffectAcpSchema.PromptResponse), + ) + ).pipe( Effect.tap(() => Ref.update(promptInstructionStates, (current) => { - if (promptParts?.instructionState === undefined) return current; + // Native compaction sends no prompt, so no instructions reached the agent. + if (promptParts?.instructionState === undefined || compactSession !== undefined) + return current; const updated = new Map(current); updated.set(requestedSessionId, promptParts.instructionState); return updated; @@ -8269,7 +8533,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ), ), startTurn, - ...(flavor.supportsCompaction === true + ...(flavor.supportsCompaction === true || flavor.compactSession !== undefined ? { compactThread: (turnInput: ProviderAdapter.ProviderAdapterV2TurnInput) => startTurn({ @@ -8278,13 +8542,69 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }), } : {}), - steerTurn: (turnInput) => - Effect.fail( - new ProviderAdapter.ProviderAdapterSteerRunUnsupportedError({ - driver, - providerThreadId: turnInput.providerThread.id, - }), - ), + steerTurn: Effect.fn("AcpAdapterV2.steerTurn")( + function* (turnInput) { + const steering = flavor.steering; + // The agent takes text only, so a steer with attachments waits for the next turn. + if (steering === undefined || turnInput.message.attachments.length > 0) { + return yield* new ProviderAdapter.ProviderAdapterSteerRunUnsupportedError({ + driver, + providerThreadId: turnInput.providerThread.id, + }); + } + const context = yield* Ref.get(activeTurn); + if ( + context === null || + context.finalized || + context.providerTurnId !== turnInput.providerTurnId + ) { + return yield* new ProviderAdapter.ProviderAdapterProtocolError({ + driver, + detail: `Provider turn ${turnInput.providerTurnId} is not active and cannot be steered.`, + }); + } + // An agent that drops an early cancel drops an early steer too. + const startHold = flavor.cancelAfterPromptStarts; + if (startHold !== undefined) { + yield* Deferred.await(context.promptStarted).pipe( + Effect.timeoutOption(startHold.bound), + ); + } + const steerId = yield* steering.send( + runtime, + context.nativeThreadId, + turnInput.message.text, + ); + const injected = steerInjection(steerId); + // The agent reads a steer at its next step. One that lands after the last + // step is dropped, and the turn settles right after; the orchestrator then + // sends it as a follow-up. The bound keeps Stop from queueing behind a tool. + const outcome = yield* Effect.raceFirst( + Deferred.await(injected).pipe(Effect.as("injected" as const)), + Deferred.await(context.promptWireSettled).pipe(Effect.as("settled" as const)), + ).pipe(Effect.timeoutOption(STEER_DELIVERY_BOUND)); + steerInjections.delete(steerId); + if (Option.contains(outcome, "settled") && !(yield* Deferred.isDone(injected))) { + return yield* new ProviderAdapter.ProviderAdapterProtocolError({ + driver, + detail: `Provider turn ${turnInput.providerTurnId} ended before it read the steering message.`, + }); + } + }, + (effect, turnInput) => + effect.pipe( + Effect.mapError((cause) => + cause._tag === "ProviderAdapterSteerRunUnsupportedError" + ? cause + : new ProviderAdapter.ProviderAdapterSteerRunError({ + driver, + providerThreadId: turnInput.providerThread.id, + providerTurnId: turnInput.providerTurnId, + cause, + }), + ), + ), + ), interruptTurn: Effect.fn("AcpAdapterV2.interruptTurn")( function* (turnInput: ProviderAdapter.ProviderAdapterV2InterruptInput) { return yield* Effect.uninterruptibleMask((restore) => @@ -8546,7 +8866,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Deferred.succeed(teardownBarrier!, undefined).pipe(Effect.ignore); } else { // Settled soft interrupts have no prompt to cancel; cancel could kill background subagents. - if (!settledSoftInterrupt) { + if (!settledSoftInterrupt && (yield* promptStillRunsAfterHold(context))) { yield* runtime.cancel; } if (restartRuntime && flavor.restartRuntimeAfterInterrupt === true) { @@ -8800,7 +9120,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( detail: "ACP driver did not negotiate session/fork", }); } - if (forkInput.providerTurnId !== undefined) { + const forkMeta = forkFromTurnMetaFor({ + driver, + flavor, + canForkFromTurn: capabilities.threads.canForkFromTurn, + forkInput, + }); + if (forkMeta === null) { return yield* new ProviderAdapter.ProviderAdapterProtocolError({ driver, detail: "ACP session/fork can only fork the current session head", @@ -8815,6 +9141,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const forked = yield* runtime.forkSession( sourceSessionId, acpMcpActivation(mcpContext), + forkMeta, ); rememberTerminalEnvironment( forked.sessionId, diff --git a/packages/provider-acp/src/server/nativeLogging.test.ts b/packages/provider-acp/src/server/nativeLogging.test.ts index a394a18154af6..b54945a718134 100644 --- a/packages/provider-acp/src/server/nativeLogging.test.ts +++ b/packages/provider-acp/src/server/nativeLogging.test.ts @@ -1,4 +1,6 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as Layer from "effect/Layer"; import { ProviderDriverKind, ThreadId } from "@t3tools/contracts"; import { assert, it } from "@effect/vitest"; import * as Cause from "effect/Cause"; @@ -10,7 +12,7 @@ import * as AcpErrors from "effect-acp/errors"; import type * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers"; import { makeAcpNativeLoggerFactory } from "./nativeLogging.ts"; -const nodeServicesIt = it.layer(NodeServices.layer); +const nodeServicesIt = it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)); const encodeUnknownJson = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown)); nodeServicesIt("ACP native logging", (it) => { diff --git a/packages/provider-acp/src/server/nativeLogging.ts b/packages/provider-acp/src/server/nativeLogging.ts index eb11d9693c240..63b5936e5b071 100644 --- a/packages/provider-acp/src/server/nativeLogging.ts +++ b/packages/provider-acp/src/server/nativeLogging.ts @@ -1,7 +1,7 @@ import type { ProviderDriverKind, ThreadId } from "@t3tools/contracts"; import { causeErrorTag } from "@t3tools/shared/observability"; import * as Cause from "effect/Cause"; -import * as Crypto from "effect/Crypto"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -28,7 +28,7 @@ function formatRequestLogPayload(event: AcpSessionRuntime.AcpSessionRequestLogEv } export const makeAcpNativeLoggerFactory = Effect.fn("makeAcpNativeLoggerFactory")(function* () { - const crypto = yield* Crypto.Crypto; + const random = yield* SecureRandom.SecureRandom; return (input: { readonly nativeEventLogger: ProviderEventLoggers.EventNdjsonLogger | undefined; readonly provider: ProviderDriverKind; @@ -42,7 +42,7 @@ export const makeAcpNativeLoggerFactory = Effect.fn("makeAcpNativeLoggerFactory" { observedAt, event: { - id: yield* crypto.randomUUIDv4(), + id: yield* random.uuidV4(), kind: logInput.kind, provider: input.provider, createdAt: observedAt, diff --git a/packages/provider-acp/src/server/runtimeModel.ts b/packages/provider-acp/src/server/runtimeModel.ts index 49fd56cc19d6c..ba571af271d79 100644 --- a/packages/provider-acp/src/server/runtimeModel.ts +++ b/packages/provider-acp/src/server/runtimeModel.ts @@ -1095,6 +1095,18 @@ export function extractMcpToolCallIdentity( if (meta?.is_mcp_tool_call === true && server.length > 0 && tool.length > 0) { return { server, tool }; } + // Kiro names the server in `_meta.kiro.serverName` and the call in `rawInput.tool_id` + // ("::"), with the tool's own input under `rawInput.arguments`. + const kiroServer = isRecord(meta?.kiro) ? meta.kiro.serverName : undefined; + const kiroToolId = typeof rawInput?.tool_id === "string" ? rawInput.tool_id.trim() : ""; + if ( + typeof kiroServer === "string" && + kiroServer.length > 0 && + kiroToolId.startsWith(`${kiroServer}::`) && + kiroToolId.length > kiroServer.length + 2 + ) { + return { server: kiroServer, tool: kiroToolId.slice(kiroServer.length + 2) }; + } const claudeCode = isRecord(meta?.claudeCode) ? meta.claudeCode : undefined; const gooseToolCall = isRecord(meta?.goose) ? isRecord(meta.goose.toolCall) diff --git a/packages/provider-core/src/server/failure.test.ts b/packages/provider-core/src/server/failure.test.ts index 84cc14dc2e594..5ca689509c007 100644 --- a/packages/provider-core/src/server/failure.test.ts +++ b/packages/provider-core/src/server/failure.test.ts @@ -146,6 +146,16 @@ it("keeps unrecognized reasons and provider text out of category messages", () = { _tag: "ProviderAdapterProtocolError", reason: "private-config" }, { _tag: "ProviderAdapterProtocolError", reason: "constructor" }, { _tag: "constructor", cause: "private-config" }, + { + _tag: "CodexAppServerRequestError", + method: "thread/goal/set", + message: "thread not found: private-thread", + }, + { + _tag: "CodexAppServerRequestError", + method: "turn/start", + message: "goal objective must be at most 4000 characters", + }, ]) { assert.equal( makeProviderFailure({ cause: { _tag: "ProviderAdapterTurnStartError", cause } }).message, diff --git a/packages/provider-core/src/server/failure.ts b/packages/provider-core/src/server/failure.ts index 9bdebc55d373b..15762a1aa4b60 100644 --- a/packages/provider-core/src/server/failure.ts +++ b/packages/provider-core/src/server/failure.ts @@ -61,6 +61,10 @@ const PROVIDER_FAILURE_CATEGORIES: Partial< }, }; +// codex_protocol::protocol::validate_thread_goal_objective +const CODEX_GOAL_VALIDATION_MESSAGE = + /^goal objective must (?:not be empty|be at most \d{1,6} characters)$/u; + const PROVIDER_FAILURE_REASONS: Record = { previous_turn_active: "the previous turn is still running", attachment_unreadable: "an attachment could not be read", @@ -108,8 +112,22 @@ function curatedCauseMessages(cause: unknown): { case "ClaudeSettingsLaunchArgError": case "ClaudeMcpRegistrationTimeoutError": case "CursorModelUnavailableError": + case "CodexGoalObjectiveTooLongError": case "ProviderSetupError": return { known: stringField(cause, "message"), category: categoryMessage() }; + case "CodexAppServerRequestError": { + // Only Codex's fixed-shape goal validation text is actionable and + // safe to show; other request error text stays hidden. + const rejection = stringField(cause, "message"); + if ( + (cause as Record).method === "thread/goal/set" && + rejection !== undefined && + CODEX_GOAL_VALIDATION_MESSAGE.test(rejection) + ) { + return { known: `Codex rejected the goal: ${rejection}.`, category: categoryMessage() }; + } + break; + } case "AcpProcessExitedError": { const exit = `provider process exited${processExitStatus(cause)}`; const stage = category === undefined ? `The ${exit}` : `${category.summary}: the ${exit}`; diff --git a/packages/provider-core/src/server/maintenance.ts b/packages/provider-core/src/server/maintenance.ts index b9f793cc8bf72..9d2a63c5bfbe3 100644 --- a/packages/provider-core/src/server/maintenance.ts +++ b/packages/provider-core/src/server/maintenance.ts @@ -12,6 +12,8 @@ export interface ProviderMaintenanceCapabilities { * `latestVersion`, then npm. */ readonly lookupLatestVersion?: Effect.Effect; + /** Separates installer release channels that share an update command. */ + readonly latestVersionCacheKey?: string; readonly compareVersions?: (current: string, latest: string) => number; /** Resolved executable path for advisories when no update command is proven. */ readonly installPath?: string; diff --git a/packages/provider-core/src/server/maintenanceResolver.test.ts b/packages/provider-core/src/server/maintenanceResolver.test.ts index 7883d827d4e64..cf6527114da67 100644 --- a/packages/provider-core/src/server/maintenanceResolver.test.ts +++ b/packages/provider-core/src/server/maintenanceResolver.test.ts @@ -1,12 +1,13 @@ // @effect-diagnostics nodeBuiltinImport:off import { expect, it } from "@effect/vitest"; import * as NodeFS from "node:fs"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import * as NodeOS from "node:os"; import * as NodePath from "node:path"; import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; -import * as Crypto from "effect/Crypto"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; @@ -44,8 +45,8 @@ const driver = (value: string) => ProviderDriverKind.make(value); // Shell stubs use POSIX paths; Windows temp paths cannot split on colon. const windowsHost = HostProcess.Platform.defaultValue() === "win32"; const makeTempDir = (name: string) => - Crypto.Crypto.pipe( - Effect.flatMap((crypto) => crypto.randomUUIDv4()), + SecureRandom.SecureRandom.pipe( + Effect.flatMap((random) => random.uuidV4()), Effect.map((id) => NodePath.join(NodeFS.realpathSync(NodeOS.tmpdir()), `${name}-${id}`)), ); const isNativeTestCommandPath = @@ -131,7 +132,11 @@ function stdoutSpawner( } it.layer( - NodeServices.layer.pipe(Layer.merge(Layer.succeed(HostProcess.Environment, { PATH: "" }))), + Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + Layer.succeed(HostProcess.Environment, { PATH: "" }), + ), )("providerMaintenance", (it) => { it.effect("prefers the installer's own latest version over the npm registry", () => resolveLatestProviderVersion({ ...manualPackageTool, latestVersion: "1.2.0" }).pipe( @@ -706,7 +711,7 @@ it.layer( maintenanceCapabilities: capabilities, }), ).toMatchObject({ status: "current", canUpdate: false, canInstallVersion: false }); - }).pipe(Effect.provide(NodeServices.layer)), + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect("stays unknown when choco search fails instead of asking npm", () => @@ -737,7 +742,7 @@ it.layer( ); expect(latest).toBeNull(); - }).pipe(Effect.provide(NodeServices.layer)), + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect.each([ diff --git a/packages/provider-core/src/server/maintenanceResolver.ts b/packages/provider-core/src/server/maintenanceResolver.ts index 1810fff9a52c4..5f5efaae13c80 100644 --- a/packages/provider-core/src/server/maintenanceResolver.ts +++ b/packages/provider-core/src/server/maintenanceResolver.ts @@ -980,6 +980,7 @@ const fetchNpmLatestVersion = Effect.fn("fetchNpmLatestVersion")(function* (pack */ function installerLatestVersionKey(capabilities: ProviderMaintenanceCapabilities) { if (!capabilities.lookupLatestVersion) return null; + if (capabilities.latestVersionCacheKey) return capabilities.latestVersionCacheKey; const update = capabilities.update; if (update) return [update.lockKey, update.executable, ...update.args].join("\0"); return capabilities.installPath diff --git a/packages/provider-core/src/server/orchestrationInstructions.ts b/packages/provider-core/src/server/orchestrationInstructions.ts index 70b3fff064f3b..90ed18e9b3398 100644 --- a/packages/provider-core/src/server/orchestrationInstructions.ts +++ b/packages/provider-core/src/server/orchestrationInstructions.ts @@ -6,7 +6,7 @@ export const T3_CODE_ORCHESTRATION_SECTIONS: ReadonlyArray = [ Ordinary coding tasks need no T3 tools. -- Subagents: use your native tool when the child uses your provider, a model it offers, and no settings beyond yours, and it finishes in this turn (Claude \`Agent\` always with \`run_in_background:false\`; Codex \`spawn_agent\`, then wait). Use \`delegate_task\` for another provider's model, user-asked settings, a separate checkout (\`isolation:"worktree"\`), background work, or \`delegate_task\` by name. A native type running another provider's model counts too. Workflow only when asked. +- Subagents: use your native tool when the child uses your provider, a model it offers, and no settings beyond yours (Claude \`Agent\`, \`run_in_background:false\`; Codex \`spawn_agent\`, then wait). Use \`delegate_task\` for another provider's model, user-asked settings, a separate checkout (\`isolation:"worktree"\`), or \`delegate_task\` by name. A native type on another provider's model counts too. Background agent: \`delegate_task\`, never a background \`Agent\`. Workflow only when asked. - Call \`orchestrator_capabilities\` once per thread, before the first \`delegate_task\`. Again only after an error or a user-named provider change. Settings go in \`target.options\`. Provider or model unavailable: say so. Never switch unasked, or fall back to native tools, Workflow, or CLIs. Never make a child's checkout in the shell or in \`task\`. - Every new delegate review or re-check is a new \`delegate_task\` (brief, findings, objections), never a \`t3_thread_send\`. Fix small review findings yourself; start no delegate for them. When told to proceed without a delegate, or to run fewer, \`task_cancel\` the extras. Start no replacement. - Follow a running delegate's \`next\`. Do not poll it (\`task_status\`, \`sleep\`, watchers, Monitor, ScheduleWakeup). Stop a delegate run you replace or no longer need with \`task_cancel\`, never \`t3_thread_interrupt\` on a \`childThreadId\`. diff --git a/packages/provider-core/src/server/providerAuthFlow.test.ts b/packages/provider-core/src/server/providerAuthFlow.test.ts index 968eb04f78b4d..cf4a4b699d7f0 100644 --- a/packages/provider-core/src/server/providerAuthFlow.test.ts +++ b/packages/provider-core/src/server/providerAuthFlow.test.ts @@ -1,4 +1,6 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as Layer from "effect/Layer"; import { assert, it } from "@effect/vitest"; import { ProviderInstanceId, @@ -41,7 +43,7 @@ it.effect("distinguishes pending method discovery from an agent with no sign-in Effect.map(Option.getOrThrow), ); assert.deepEqual(ready.methods, []); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); const makeHarness = Effect.gen(function* () { @@ -112,7 +114,7 @@ it.effect("requires owner consent and provider verification before success", () yield* phase("verifying"); yield* Deferred.succeed(verified, undefined); assert.strictEqual((yield* phase("succeeded")).phase, "succeeded"); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect("cancellation rejects late consent and permits another login", () => @@ -132,7 +134,7 @@ it.effect("cancellation rejects late consent and permits another login", () => ); const next = yield* controller.start("other"); assert.notStrictEqual(next.flowId, state.flowId); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect("closes admitted provider processes and blocks new ones while login is pending", () => @@ -152,7 +154,7 @@ it.effect("closes admitted provider processes and blocks new ones while login is assert.isTrue( (yield* controller.withAccess!(Effect.void).pipe(Effect.result))._tag === "Failure", ); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect("shared credential invalidation closes admitted processes before permitting reuse", () => @@ -169,7 +171,7 @@ it.effect("shared credential invalidation closes admitted processes before permi yield* controller.invalidate!; assert.isTrue(closed); assert.strictEqual(yield* controller.withAccess!(Effect.succeed("new process")), "new process"); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect.each([ @@ -234,7 +236,7 @@ it.effect.each([ assert.isNull(verifying.interaction); assert.notInclude(verifying.message ?? "", "private-token"); yield* controller.cancel("owner", state.flowId!); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect("shows a device code only to its owner without treating it as authenticated", () => @@ -268,7 +270,7 @@ it.effect("shows a device code only to its owner without treating it as authenti assert.isNull(other.interaction); assert.isNull(other.authorizationUrl); yield* controller.cancel("owner", start.flowId!); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect.each([ @@ -302,7 +304,7 @@ it.effect.each([ Effect.map(Option.getOrThrow), ); assert.strictEqual(failed.message, message); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); const makeBlockingResponseHarness = Effect.gen(function* () { @@ -393,7 +395,7 @@ it.effect.each(["cancel", "logout"] as const)( assert.isTrue(Exit.isFailure(yield* Fiber.join(harness.response))); assert.isFalse(yield* harness.controller.isChangingCredentials!); assert.notEqual((yield* harness.controller.start("other")).flowId, harness.input.flowId); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect( @@ -415,7 +417,7 @@ it.effect( assert.isTrue(yield* Deferred.isDone(harness.cleanupFinished)); assert.isTrue(Exit.isFailure(yield* Fiber.join(harness.response))); yield* harness.controller.withAccess!(Effect.void); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect("closing the controller scope interrupts and drains its adapter response", () => @@ -431,7 +433,7 @@ it.effect("closing the controller scope interrupts and drains its adapter respon yield* Fiber.join(closing); assert.isTrue(yield* Deferred.isDone(harness.cleanupFinished)); assert.isTrue(Exit.isFailure(yield* Fiber.join(harness.response))); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect("a failed method refresh keeps the last discovered methods", () => @@ -458,7 +460,7 @@ it.effect("a failed method refresh keeps the last discovered methods", () => .pipe(Stream.runHead, Effect.map(Option.getOrThrow)); assert.deepEqual(state.methods, [method]); assert.strictEqual(state.message, "interrupted"); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect("rebuilding a controller leaves sessions it admitted to their owners", () => @@ -475,7 +477,7 @@ it.effect("rebuilding a controller leaves sessions it admitted to their owners", ); yield* Scope.close(scope, Exit.void); assert.isFalse(closed); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect("profile import stops owned sessions and gates access until credentials are saved", () => @@ -514,5 +516,5 @@ it.effect("profile import stops owned sessions and gates access until credential yield* controller.withAccess!(Effect.succeed("new credential process")), "new credential process", ); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); diff --git a/packages/provider-core/src/server/providerAuthFlow.ts b/packages/provider-core/src/server/providerAuthFlow.ts index 6dbd06d976f03..c1f8227eb25ff 100644 --- a/packages/provider-core/src/server/providerAuthFlow.ts +++ b/packages/provider-core/src/server/providerAuthFlow.ts @@ -10,7 +10,7 @@ import * as Cause from "effect/Cause"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as Clock from "effect/Clock"; -import * as Crypto from "effect/Crypto"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Deferred from "effect/Deferred"; @@ -72,7 +72,7 @@ export const make = Effect.fn("ProviderAuthFlow.make")(function* (options: { readonly timeoutMs?: number; }) { const scope = yield* Scope.Scope; - const crypto = yield* Crypto.Crypto; + const random = yield* SecureRandom.SecureRandom; const lock = yield* Semaphore.make(1); const timeoutMs = options.timeoutMs ?? 300_000; const empty: ProviderAuthState = { @@ -238,7 +238,7 @@ export const make = Effect.fn("ProviderAuthFlow.make")(function* (options: { operation: "start", detail: "Provider setup is already in progress.", }); - const id = yield* crypto.randomUUIDv4().pipe( + const id = yield* random.uuidV4().pipe( Effect.mapError( () => new ProviderSetupError({ diff --git a/packages/provider-cursor/package.json b/packages/provider-cursor/package.json index b619c3b61fdb4..90122cbe57e66 100644 --- a/packages/provider-cursor/package.json +++ b/packages/provider-cursor/package.json @@ -49,7 +49,7 @@ "test": "vp test run --config ../../vite.config.ts --dir ." }, "dependencies": { - "@cursor/sdk": "1.0.38", + "@cursor/sdk": "1.2.0", "@napi-rs/keyring": "^1.3.0", "@t3tools/contracts": "workspace:*", "@t3tools/provider-core": "workspace:*", diff --git a/packages/provider-cursor/src/server/CursorAccountReader.ts b/packages/provider-cursor/src/server/CursorAccountReader.ts index 17405e28c1cfe..dda308a4caa96 100644 --- a/packages/provider-cursor/src/server/CursorAccountReader.ts +++ b/packages/provider-cursor/src/server/CursorAccountReader.ts @@ -1,5 +1,5 @@ import * as Context from "effect/Context"; -import * as Crypto from "effect/Crypto"; +import * as Digest from "effect/crypto/Digest"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as HttpClient from "effect/http/HttpClient"; @@ -31,7 +31,7 @@ export const layer = Layer.effect( Effect.gen(function* () { const keychain = yield* CursorKeychain.CursorKeychain; const context = yield* Effect.context< - FileSystem.FileSystem | Crypto.Crypto | HttpClient.HttpClient + FileSystem.FileSystem | Digest.Digest | HttpClient.HttpClient >(); return CursorAccountReader.of({ resolve: Effect.fn("CursorAccountReader.resolve")((source) => diff --git a/packages/provider-cursor/src/server/CursorAgentSdk.ts b/packages/provider-cursor/src/server/CursorAgentSdk.ts index 791121a7140ec..f48d7baf1b24a 100644 --- a/packages/provider-cursor/src/server/CursorAgentSdk.ts +++ b/packages/provider-cursor/src/server/CursorAgentSdk.ts @@ -89,6 +89,8 @@ export interface CursorAgentSdkSendInput { readonly message: string | SDKUserMessage; readonly options?: Omit; readonly onDelta?: (update: InteractionUpdate) => Effect.Effect; + /** Runs `agent.summarize()` instead, which takes no message or options. */ + readonly summarize?: boolean; } export interface CursorAgentSdkRun { @@ -139,6 +141,8 @@ export interface CursorAgentSdkLoggedAgentOptions { export interface CursorAgentSdkLoggedSendOptions { readonly model?: SendOptions["model"]; readonly mode?: SendOptions["mode"]; + readonly hasMcpServers?: boolean; + readonly mcpServerNames?: ReadonlyArray; readonly local?: { readonly force?: boolean; readonly hasCustomTools?: boolean; @@ -298,9 +302,12 @@ export function loggedCursorSendOptions( if (options === undefined) { return {}; } + const mcpServerNames = + options.mcpServers === undefined ? undefined : Object.keys(options.mcpServers).toSorted(); return { ...(options.model === undefined ? {} : { model: options.model }), ...(options.mode === undefined ? {} : { mode: options.mode }), + ...(mcpServerNames === undefined ? {} : { hasMcpServers: true, mcpServerNames }), ...(options.local === undefined ? {} : { @@ -466,16 +473,18 @@ export const makeCursorAgentSdkRunner = Effect.fn("makeCursorAgentSdkRunner")(fu const startRun = () => Effect.tryPromise({ try: () => - agent.send(sendInput.message, { - ...sendInput.options, - onDelta: async ({ update }) => { - if (!callbacksReady) { - pendingUpdates.push(update); - return; - } - await dispatchUpdate(update); - }, - }), + sendInput.summarize === true + ? agent.summarize() + : agent.send(sendInput.message, { + ...sendInput.options, + onDelta: async ({ update }) => { + if (!callbacksReady) { + pendingUpdates.push(update); + return; + } + await dispatchUpdate(update); + }, + }), catch: (cause) => runnerError(cause, "run.start"), }); const run = yield* startRun().pipe( diff --git a/packages/provider-cursor/src/server/CursorSdk.test.ts b/packages/provider-cursor/src/server/CursorSdk.test.ts index 0f8871d4ad81e..bf5229c9642fd 100644 --- a/packages/provider-cursor/src/server/CursorSdk.test.ts +++ b/packages/provider-cursor/src/server/CursorSdk.test.ts @@ -35,6 +35,21 @@ describe("CursorSdk unhandled rejection guard", () => { }), ); + it.effect("keeps the server running when the SDK writes after its request stream ended", () => + Effect.gen(function* () { + // Shaped like `ConnectError.from(e, Code.Aborted)` from the SDK's connect-node body pump. + const cause = Object.assign(new Error("write after end"), { + code: "ERR_STREAM_WRITE_AFTER_END", + }); + const reason = Object.assign(new Error("[aborted] write after end", { cause }), { + name: "ConnectError", + code: 10, + rawMessage: "write after end", + }); + assert.deepStrictEqual(yield* rejectThroughGuard(reason), []); + }), + ); + it.effect("still exits on other rejections", () => Effect.gen(function* () { assert.deepStrictEqual(yield* rejectThroughGuard(new Error("WritableIterable is closed")), [ @@ -42,4 +57,15 @@ describe("CursorSdk unhandled rejection guard", () => { ]); }), ); + + it.effect("still exits on aborted requests other than a write after end", () => + Effect.gen(function* () { + const cause = Object.assign(new Error("socket hang up"), { code: "ECONNRESET" }); + const reason = Object.assign(new Error("[aborted] socket hang up", { cause }), { + name: "ConnectError", + code: 10, + }); + assert.deepStrictEqual(yield* rejectThroughGuard(reason), [[1]]); + }), + ); }); diff --git a/packages/provider-cursor/src/server/CursorSdk.ts b/packages/provider-cursor/src/server/CursorSdk.ts index f341a6ffe5256..b59d09725243a 100644 --- a/packages/provider-cursor/src/server/CursorSdk.ts +++ b/packages/provider-cursor/src/server/CursorSdk.ts @@ -32,12 +32,23 @@ function isCursorShellSpawnFailure(reason: unknown): boolean { } /** - * After a local exec fails, the SDK writes a final frame to the exec's stream from - * a promise nothing awaits. If that stream has already closed, the write rejects. - * The SDK's class is minified, so only its `name` identifies it. + * The SDK writes final frames from promises nothing awaits. A closed stream rejects them + * with WriteIterableClosedError; an ended request body rejects them with the Aborted + * ConnectError its connect-node pump wraps around ERR_STREAM_WRITE_AFTER_END. The classes + * are minified, so only `name` identifies them. */ function isCursorClosedStreamWrite(reason: unknown): boolean { - return reason instanceof Error && reason.name === "WriteIterableClosedError"; + if (!(reason instanceof Error)) { + return false; + } + if (reason.name === "WriteIterableClosedError") { + return true; + } + return ( + reason.name === "ConnectError" && + reason.cause instanceof Error && + Reflect.get(reason.cause, "code") === "ERR_STREAM_WRITE_AFTER_END" + ); } function onUnhandledRejection(reason: unknown): void { @@ -46,7 +57,7 @@ function onUnhandledRejection(reason: unknown): void { return; } if (isCursorClosedStreamWrite(reason)) { - console.error("Cursor SDK wrote to a closed exec stream. The server will keep running."); + console.error("Cursor SDK wrote to a closed stream. The server will keep running."); return; } if (process.listenerCount("unhandledRejection") > 1) { diff --git a/packages/provider-cursor/src/server/CursorUsageAccounts.ts b/packages/provider-cursor/src/server/CursorUsageAccounts.ts index 748df5daa186e..2ab2ddbd3c118 100644 --- a/packages/provider-cursor/src/server/CursorUsageAccounts.ts +++ b/packages/provider-cursor/src/server/CursorUsageAccounts.ts @@ -1,11 +1,14 @@ +import type { ProviderInstanceId } from "@t3tools/contracts"; import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost"; import type { ProviderUsageScan } from "@t3tools/provider-core/server/usage"; import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; +import * as Digest from "effect/crypto/Digest"; import * as Deferred from "effect/Deferred"; 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 Layer from "effect/Layer"; @@ -22,9 +25,11 @@ import { isCursorCacheFresh, mergeCursorFetch, type CursorAccountCache, + type CursorCredentialSource, } from "./accountCache.ts"; import type { CursorResolvedCredential } from "./accountUsage.ts"; import * as CursorAccountReader from "./CursorAccountReader.ts"; +import { readStoredCursorApiKey } from "./credentialStore.ts"; const encodeCredentialKey = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); @@ -34,6 +39,14 @@ const decodeCacheFile = Schema.decodeUnknownEffect( Schema.fromJsonString(Schema.Unknown as unknown as Schema.Codec), ); +type PrepareInput = { + readonly instances: ReadonlyArray<{ + readonly instanceId: ProviderInstanceId; + readonly environment: NodeJS.ProcessEnv; + }>; + readonly keychainUsageEnabled: boolean; +}; + type ScanInput = { readonly windowStartMs: number; readonly retentionCutoffMs: number; @@ -43,13 +56,10 @@ type ScanInput = { export class CursorUsageAccounts extends Context.Service< CursorUsageAccounts, { - readonly scan: (input: { - readonly keychainUsageEnabled: boolean; - readonly windowStartMs: number; - readonly retentionCutoffMs: number; - readonly awaitRefresh: boolean; - }) => Effect.Effect>; - readonly prepare: (keychainUsageEnabled: boolean) => Effect.Effect<{ + readonly scan: ( + input: PrepareInput & ScanInput, + ) => Effect.Effect>; + readonly prepare: (input: PrepareInput) => Effect.Effect<{ readonly cacheKey: string; readonly scan: (input: ScanInput) => Effect.Effect>; }>; @@ -65,11 +75,13 @@ const make = Effect.gen(function* () { const accountReader = yield* CursorAccountReader.CursorAccountReader; const hostEnvironment = yield* HostProcess.Environment; const platform = yield* HostProcess.Platform; + const digest = yield* Digest.Digest; const cachePath = path.join(host.paths.stateDir, CURSOR_ACCOUNT_CACHE_FILE_NAME); - /** Account caches by credential source and token fingerprint. */ + /** Account caches by credential source and token or API-key fingerprint. */ const caches = new Map(); - let activeCredentialKey: string | undefined; + /** Credentials the latest preparation observed; refreshes for any other are discarded. */ + let activeCredentialKeys: ReadonlySet = new Set(); let preparationGeneration = 0; let cacheDirty = false; /** Per-credential failures share the cache TTL to prevent repeated requests; null means no login. */ @@ -117,7 +129,7 @@ const make = Effect.gen(function* () { yield* Effect.addFinalizer(() => awaitPersisted); const refreshAccount = Effect.fn("CursorUsageAccounts.refreshAccount")(function* ( - credential: CursorResolvedCredential, + credential: CursorCredentialSource | CursorResolvedCredential, credentialKey: string, retentionStartMs: number, ) { @@ -130,7 +142,7 @@ const make = Effect.gen(function* () { }; let base = caches.get(credentialKey); let fetched = yield* fetchMissing(base); - if (activeCredentialKey !== credentialKey) return; + if (!activeCredentialKeys.has(credentialKey)) return; // Another login's history replaces the cached account's, even if reading it fails. if ( base !== undefined && @@ -141,7 +153,7 @@ const make = Effect.gen(function* () { cacheDirty = true; base = undefined; fetched = yield* fetchMissing(base); - if (activeCredentialKey !== credentialKey) return; + if (!activeCredentialKeys.has(credentialKey)) return; } const { range, result } = fetched; if (result.missing || result.error !== null || result.accountKey === null) { @@ -167,7 +179,7 @@ const make = Effect.gen(function* () { }); const startRefresh = ( - credential: CursorResolvedCredential, + credential: CursorCredentialSource | CursorResolvedCredential, credentialKey: string, retentionStartMs: number, ) => @@ -183,7 +195,7 @@ const make = Effect.gen(function* () { Effect.catchCause(() => Clock.currentTimeMillis.pipe( Effect.map((atMs) => { - if (activeCredentialKey === credentialKey) + if (activeCredentialKeys.has(credentialKey)) failures.set(credentialKey, { atMs, error: CURSOR_ACCOUNT_READ_ERROR }); }), ), @@ -201,14 +213,14 @@ const make = Effect.gen(function* () { ); const accountSource = Effect.fn("CursorUsageAccounts.accountSource")(function* ( - credential: CursorResolvedCredential, + credential: CursorCredentialSource | CursorResolvedCredential, credentialKey: string, authPath: string, windowStartMs: number, retentionStartMs: number, awaitRefresh: boolean, ) { - if (credential.kind === "unavailable") { + if (typeof credential !== "string" && credential.kind === "unavailable") { if (credential.missing && credential.error === null) return null; return { dir: authPath, @@ -260,66 +272,83 @@ const make = Effect.gen(function* () { } satisfies ProviderUsageScan; }); - const prepare: CursorUsageAccounts["Service"]["prepare"] = Effect.fn( - "CursorUsageAccounts.prepare", - )(function* (keychainUsageEnabled) { - const generation = ++preparationGeneration; - const home = yield* HostProcess.HomeDirectory; - const userHome = - (platform === "win32" ? hostEnvironment["USERPROFILE"] : hostEnvironment["HOME"]) || home; - const configHome = hostEnvironment["XDG_CONFIG_HOME"]?.trim(); - const cursorHome = - platform === "darwin" - ? path.join(userHome, "Library", "Application Support") - : platform === "win32" - ? hostEnvironment["APPDATA"] || path.join(userHome, "AppData", "Roaming") - : configHome && path.isAbsolute(configHome) - ? configHome - : path.join(userHome, ".config"); - const authPath = - platform === "darwin" - ? path.join(userHome, ".cursor", "auth.json") - : path.join(cursorHome, platform === "win32" ? "Cursor" : "cursor", "auth.json"); + type PreparedScan = { + readonly cacheKey: string; + /** Credentials whose refreshes this snapshot keeps. */ + readonly credentialKeys: ReadonlyArray; + readonly scan: (input: ScanInput) => Effect.Effect>; + }; + + const notice = (cacheKey: string, source: ProviderUsageScan): PreparedScan => ({ + cacheKey, + credentialKeys: [], + scan: () => Effect.succeed([source]), + }); + + const prepareApiKeys = Effect.fn("CursorUsageAccounts.prepareApiKeys")(function* ( + apiKeys: ReadonlyArray, + authPath: string, + ) { + yield* ensureLoaded; + const keyed = yield* Effect.forEach(apiKeys, (apiKey) => + digest.digest(Digest.sha256, new TextEncoder().encode(apiKey)).pipe( + // A fingerprint, so a replaced key never reads the previous account's cache. + Effect.map((hash) => ({ apiKey, credentialKey: `api-key:${Hex.encode(hash)}` })), + ), + ); + const credentialKeys = keyed.map(({ credentialKey }) => credentialKey).toSorted(); + return { + cacheKey: encodeCredentialKey(credentialKeys), + credentialKeys, + scan: ({ windowStartMs, retentionCutoffMs, awaitRefresh }: ScanInput) => + Effect.forEach(keyed, ({ apiKey, credentialKey }) => + accountSource( + { kind: "apiKey", apiKey }, + credentialKey, + authPath, + windowStartMs, + retentionCutoffMs, + awaitRefresh, + ), + ).pipe(Effect.map((sources) => sources.filter((source) => source !== null))), + } satisfies PreparedScan; + }); + + const prepareLogin = Effect.fn("CursorUsageAccounts.prepareLogin")(function* ( + keychainUsageEnabled: boolean, + authPath: string, + generation: number, + ): Effect.fn.Return { const credentialStore = hostEnvironment["AGENT_CLI_CREDENTIAL_STORE"]; const loginUnavailable = - Boolean(hostEnvironment["CURSOR_AUTH_TOKEN"]?.trim()) || - Boolean(hostEnvironment["CURSOR_API_KEY"]?.trim()) || - credentialStore === "memory"; + Boolean(hostEnvironment["CURSOR_AUTH_TOKEN"]?.trim()) || credentialStore === "memory"; const useKeychain = platform === "darwin" && credentialStore !== "file"; if (useKeychain && !loginUnavailable && !keychainUsageEnabled) { - return { - cacheKey: "keychain-disabled", - scan: () => - Effect.succeed([ - { - dir: authPath, - volumeId: "", - files: null, - message: "Cursor account usage is off on this environment.", - action: "enableCursorKeychain", - }, - ]), - }; + return notice("keychain-disabled", { + dir: authPath, + volumeId: "", + files: null, + message: "Cursor account usage is off on this environment.", + action: "enableCursorKeychain", + }); } if (loginUnavailable) { - return { - cacheKey: "login-unavailable", - scan: () => - Effect.succeed([ - { - dir: authPath, - files: null, - message: "Cursor account history needs a Cursor CLI login on this server.", - }, - ]), - }; + return notice("login-unavailable", { + dir: authPath, + files: null, + message: "Cursor account history needs a Cursor CLI login on this server.", + }); } // A Keychain login outlives an uninstalled Cursor, so it also needs Cursor's local directory. if ( useKeychain && !(yield* fileSystem.exists(path.dirname(authPath)).pipe(Effect.orElseSucceed(() => true))) ) { - return { cacheKey: "not-installed", scan: () => Effect.succeed([]) }; + return { + cacheKey: "not-installed", + credentialKeys: [], + scan: () => Effect.succeed([]), + } satisfies PreparedScan; } yield* ensureLoaded; const sourceKey = useKeychain ? "keychain" : authPath; @@ -327,9 +356,8 @@ const make = Effect.gen(function* () { const cacheKey = resolved.kind === "token" ? encodeCredentialKey([sourceKey, resolved.fingerprint]) : ""; // A slower credential resolution keeps its request's snapshot, but cannot - // replace the identity observed by a newer preparation. + // drop the caches of the identity observed by a newer preparation. if (generation === preparationGeneration) { - activeCredentialKey = cacheKey; const prefix = encodeCredentialKey([sourceKey]).slice(0, -1) + ","; for (const key of caches.keys()) { if (key !== cacheKey && (key === sourceKey || key.startsWith(prefix))) { @@ -344,26 +372,80 @@ const make = Effect.gen(function* () { } return { cacheKey: resolved.kind === "token" ? cacheKey : encodeCredentialKey(resolved), - scan: Effect.fn("CursorUsageAccounts.scanPrepared")(function* ({ - windowStartMs, - retentionCutoffMs, - awaitRefresh, - }: ScanInput) { - const source = yield* accountSource( + credentialKeys: [cacheKey], + scan: ({ windowStartMs, retentionCutoffMs, awaitRefresh }: ScanInput) => + accountSource( resolved, cacheKey, authPath, windowStartMs, retentionCutoffMs, awaitRefresh, - ); - return source === null ? [] : [source]; + ).pipe(Effect.map((source) => (source === null ? [] : [source]))), + } satisfies PreparedScan; + }); + + const prepare: CursorUsageAccounts["Service"]["prepare"] = Effect.fn( + "CursorUsageAccounts.prepare", + )(function* ({ instances, keychainUsageEnabled }) { + const generation = ++preparationGeneration; + const home = yield* HostProcess.HomeDirectory; + const userHome = + (platform === "win32" ? hostEnvironment["USERPROFILE"] : hostEnvironment["HOME"]) || home; + const configHome = hostEnvironment["XDG_CONFIG_HOME"]?.trim(); + const cursorHome = + platform === "darwin" + ? path.join(userHome, "Library", "Application Support") + : platform === "win32" + ? hostEnvironment["APPDATA"] || path.join(userHome, "AppData", "Roaming") + : configHome && path.isAbsolute(configHome) + ? configHome + : path.join(userHome, ".config"); + const authPath = + platform === "darwin" + ? path.join(userHome, ".cursor", "auth.json") + : path.join(cursorHome, platform === "win32" ? "Cursor" : "cursor", "auth.json"); + + // T3's Cursor sign-in and CURSOR_API_KEY name the account the agent uses, so they win. + const apiKeys = yield* Effect.forEach(instances, ({ instanceId, environment }) => + environment.CURSOR_API_KEY?.trim() + ? Effect.succeed(environment.CURSOR_API_KEY.trim()) + : readStoredCursorApiKey(instanceId).pipe( + Effect.provideService(ProviderHost.ProviderHost, host), + Effect.orElseSucceed(() => undefined), + ), + ); + const uniqueApiKeys = [...new Set(apiKeys.filter((apiKey) => apiKey !== undefined))]; + // An instance without a key runs on the CLI login, so that account still counts. + const usesLogin = uniqueApiKeys.length === 0 || apiKeys.includes(undefined); + const prepared: ReadonlyArray = [ + ...(uniqueApiKeys.length > 0 ? [yield* prepareApiKeys(uniqueApiKeys, authPath)] : []), + ...(usesLogin ? [yield* prepareLogin(keychainUsageEnabled, authPath, generation)] : []), + ]; + if (generation === preparationGeneration) { + activeCredentialKeys = new Set(prepared.flatMap(({ credentialKeys }) => credentialKeys)); + } + return { + cacheKey: encodeCredentialKey(prepared.map(({ cacheKey }) => cacheKey)), + scan: Effect.fn("CursorUsageAccounts.scanPrepared")(function* (input: ScanInput) { + const sources = (yield* Effect.forEach(prepared, ({ scan }) => scan(input))).flat(); + // Credentials for one account share its source, and a repeated source would count + // sessions twice. A failed credential can hold older records, so a current read wins, + // then a refresh the client must follow up on, then a notice the user can act on. + const rank = (source: ProviderUsageScan) => + source.status === "ok" ? 3 : source.refreshing ? 2 : source.action ? 1 : 0; + const byAccount = new Map(); + for (const source of sources) { + const kept = byAccount.get(source.dir); + if (kept === undefined || rank(source) > rank(kept)) byAccount.set(source.dir, source); + } + return [...byAccount.values()]; }), }; }); const scan: CursorUsageAccounts["Service"]["scan"] = (input) => - prepare(input.keychainUsageEnabled).pipe(Effect.flatMap((snapshot) => snapshot.scan(input))); + prepare(input).pipe(Effect.flatMap((snapshot) => snapshot.scan(input))); return CursorUsageAccounts.of({ scan, prepare, awaitPersisted }); }); diff --git a/packages/provider-cursor/src/server/accountCache.ts b/packages/provider-cursor/src/server/accountCache.ts index bcbb1ca402b17..b2ff2fbd6b3a2 100644 --- a/packages/provider-cursor/src/server/accountCache.ts +++ b/packages/provider-cursor/src/server/accountCache.ts @@ -2,7 +2,10 @@ import { cursorRateModel } from "./accountUsage.ts"; import type { UsageRecord } from "@t3tools/provider-core/server/usage"; -export type CursorCredentialSource = string | { readonly kind: "keychain" }; +export type CursorCredentialSource = + | string + | { readonly kind: "keychain" } + | { readonly kind: "apiKey"; readonly apiKey: string }; export const CURSOR_ACCOUNT_TTL_MS = 60 * 1000; diff --git a/packages/provider-cursor/src/server/accountUsage.test.ts b/packages/provider-cursor/src/server/accountUsage.test.ts index 7c6059310870c..829ebcbeb8918 100644 --- a/packages/provider-cursor/src/server/accountUsage.test.ts +++ b/packages/provider-cursor/src/server/accountUsage.test.ts @@ -1,13 +1,17 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as Layer from "effect/Layer"; import { assert, describe, it } from "@effect/vitest"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as FetchHttpClient from "effect/http/FetchHttpClient"; import * as HttpClient from "effect/http/HttpClient"; import * as HttpClientError from "effect/http/HttpClientError"; import * as HttpClientResponse from "effect/http/HttpClientResponse"; import * as Path from "effect/Path"; +import * as TestClock from "effect/testing/TestClock"; import * as CursorKeychain from "./CursorKeychain.ts"; import { readCursorAccountUsage, readCursorCredential } from "./accountUsage.ts"; @@ -78,6 +82,11 @@ describe("Cursor account history", () => { const resolved = yield* readCursorCredential( source === "file" ? authPath : { kind: "keychain" }, keychainToken, + ).pipe( + Effect.provideService( + HttpClient.HttpClient, + dashboard(() => assert.fail("Resolving a login makes no request.")), + ), ); currentToken = token("auth|second"); const fileSystem = yield* FileSystem.FileSystem; @@ -100,7 +109,7 @@ describe("Cursor account history", () => { assert.strictEqual(requests, 1); assert.isNull(result.error); assert.isFalse(result.missing); - }).pipe(Effect.provide(NodeServices.layer)), + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect( @@ -154,7 +163,7 @@ describe("Cursor account history", () => { }); assert.strictEqual(result.records[0]?.reportedCostUsd, 0.25); assert.isFalse(result.accountKey?.includes("demo") ?? true); - }).pipe(Effect.provide(NodeServices.layer)), + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect("reads Cursor account history beyond 100 pages", () => @@ -173,7 +182,7 @@ describe("Cursor account history", () => { assert.isNull(result.error); assert.strictEqual(requests, 101); assert.deepStrictEqual(result.records, []); - }).pipe(Effect.provide(NodeServices.layer)), + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect("accepts confirmed empty Cursor usage but rejects error envelopes", () => @@ -207,7 +216,7 @@ describe("Cursor account history", () => { assert.isNotNull(result.error); assert.deepStrictEqual(result.records, []); } - }).pipe(Effect.provide(NodeServices.layer)), + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect("requires a terminal Cursor page after a full page reaches the reported count", () => @@ -233,7 +242,7 @@ describe("Cursor account history", () => { assert.isNull(result.error); assert.strictEqual(result.records.length, 1000); assert.strictEqual(requests, 2); - }).pipe(Effect.provide(NodeServices.layer)), + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect( @@ -284,7 +293,7 @@ describe("Cursor account history", () => { }); assert.isNotNull(inconsistent.error); assert.deepStrictEqual(inconsistent.records, []); - }).pipe(Effect.provide(NodeServices.layer)), + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect( @@ -319,11 +328,59 @@ describe("Cursor account history", () => { ); assert.isTrue(missing.missing); assert.isFalse(requested); - }).pipe(Effect.provide(NodeServices.layer)), + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); }); describe("readCursorAccountUsage", () => { + it.effect("reads an API key's account history through Cursor's API", () => + Effect.gen(function* () { + const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`; + const requests: Array = []; + const result = yield* readAccountUsage( + { kind: "apiKey", apiKey: "api-key" }, + 0, + 1781000000000, + ({ url, headers }) => { + requests.push([url, headers.get("authorization")]); + return url.endsWith("/auth/exchange_user_api_key") + ? Response.json({ accessToken }) + : Response.json({ + totalUsageEventsCount: 1, + usageEventsDisplay: [ + { timestamp: "1780000000000", model: "gpt-5", tokenUsage: { outputTokens: 4 } }, + ], + }); + }, + ); + assert.isNull(result.error); + assert.deepStrictEqual(requests, [ + ["https://api2.cursor.sh/auth/exchange_user_api_key", "Bearer api-key"], + [ + "https://api2.cursor.sh/aiserver.v1.DashboardService/GetFilteredUsageEvents", + `Bearer ${accessToken}`, + ], + ]); + assert.strictEqual(result.records[0]?.totals.outputTokens, 4); + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); + + it.effect("stops waiting for an API key exchange that never answers", () => + Effect.gen(function* () { + const read = yield* Effect.forkChild( + readAccountUsage( + { kind: "apiKey", apiKey: "api-key" }, + 0, + 1781000000000, + () => new Promise(() => {}), + ), + ); + yield* TestClock.adjust("10 seconds"); + const result = yield* Fiber.join(read); + assert.strictEqual(result.error, "Cursor account usage could not be read."); + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); + it.effect("asks for Keychain approval when the prompt goes unanswered", () => Effect.gen(function* () { const result = yield* readAccountUsage( @@ -341,7 +398,7 @@ describe("readCursorAccountUsage", () => { missing: false, error: "Allow Keychain access on the Mac running T3 Code, then refresh.", }); - }).pipe(Effect.provide(NodeServices.layer)), + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect("reads the pages behind the first together and keeps them in page order", () => @@ -375,7 +432,7 @@ describe("readCursorAccountUsage", () => { result.records.map((record) => record.timestampMs), Array.from({ length: 8001 }, (_, index) => 1780000000000 + index), ); - }).pipe(Effect.provide(NodeServices.layer)), + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect("ends like a page-by-page read when a page fails, leaving no request open", () => @@ -415,6 +472,6 @@ describe("readCursorAccountUsage", () => { assert.deepStrictEqual(result.records, []); assert.strictEqual(open, 0); } - }).pipe(Effect.provide(NodeServices.layer)), + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); }); diff --git a/packages/provider-cursor/src/server/accountUsage.ts b/packages/provider-cursor/src/server/accountUsage.ts index bd34e90f3c24d..3df297c633cd6 100644 --- a/packages/provider-cursor/src/server/accountUsage.ts +++ b/packages/provider-cursor/src/server/accountUsage.ts @@ -1,5 +1,5 @@ import type { UsageRecord } from "@t3tools/provider-core/server/usage"; -import * as Crypto from "effect/Crypto"; +import * as Digest from "effect/crypto/Digest"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Base64Url from "effect/encoding/Base64Url"; @@ -13,6 +13,8 @@ import * as PlatformError from "effect/PlatformError"; import * as Result from "effect/Result"; import * as Schema from "effect/Schema"; +import type { CursorCredentialSource } from "./accountCache.ts"; +import { DEFAULT_CURSOR_API_ENDPOINT, exchangeCursorApiKey } from "./apiKey.ts"; import * as CursorKeychain from "./CursorKeychain.ts"; function object(value: unknown): Record { @@ -57,8 +59,8 @@ const billedEventIdentity = (...fields: readonly unknown[]) => JSON.stringify(fi const textEncoder = new TextEncoder(); const accountHash = Effect.fn("accountHash")(function* (value: string) { - const crypto = yield* Crypto.Crypto; - return Hex.encode(yield* crypto.digest("SHA-256", textEncoder.encode(value))); + const digest = yield* Digest.Digest; + return Hex.encode(yield* digest.digest(Digest.sha256, textEncoder.encode(value))); }); function canonicalJson(value: unknown): string { @@ -90,19 +92,30 @@ const DASHBOARD_USAGE_URL = "https://cursor.com/api/dashboard/get-filtered-usage const NO_REDIRECT: RequestInit = { redirect: "error" }; export type CursorResolvedCredential = - | { readonly kind: "token"; readonly accessToken: string; readonly fingerprint: string } + | { + readonly kind: "token"; + readonly accessToken: string; + readonly fingerprint: string; + /** API-key tokens read usage through Cursor's RPC API, not the web dashboard. */ + readonly viaApiKey: boolean; + } | { readonly kind: "unavailable"; readonly missing: boolean; readonly error: string | null }; export const readCursorCredential = Effect.fn("readCursorCredential")(function* ( - credentialSource: string | { readonly kind: "keychain" }, + credentialSource: CursorCredentialSource, keychainToken: Effect.Effect< string | null, | CursorKeychain.CursorKeychainTimeoutError | CursorKeychain.CursorKeychainReadError | CursorAccountUsageInvalidError > = invalid("No Keychain reader"), -): Effect.fn.Return { +): Effect.fn.Return< + CursorResolvedCredential, + never, + FileSystem.FileSystem | Digest.Digest | HttpClient.HttpClient +> { const fileSystem = yield* FileSystem.FileSystem; + const httpClient = yield* HttpClient.HttpClient; const credential = yield* Effect.result< unknown, | PlatformError.PlatformError @@ -117,7 +130,14 @@ export const readCursorCredential = Effect.fn("readCursorCredential")(function* Effect.flatMap(decodeJson), Effect.map((credentials) => object(credentials).accessToken), ) - : keychainToken, + : credentialSource.kind === "apiKey" + ? exchangeCursorApiKey(credentialSource.apiKey).pipe( + Effect.provideService(HttpClient.HttpClient, httpClient), + Effect.mapError( + () => new CursorAccountUsageInvalidError({ reason: "Invalid API key" }), + ), + ) + : keychainToken, ); if (Result.isFailure(credential)) { const cause = credential.failure; @@ -132,9 +152,11 @@ export const readCursorCredential = Effect.fn("readCursorCredential")(function* ? null : typeof credentialSource === "string" ? "Cursor credentials could not be read." - : CursorKeychain.isCursorKeychainTimeoutError(cause) - ? "Allow Keychain access on the Mac running T3 Code, then refresh." - : "Cursor Keychain credentials could not be read.", + : credentialSource.kind === "apiKey" + ? "Cursor account usage could not be read." + : CursorKeychain.isCursorKeychainTimeoutError(cause) + ? "Allow Keychain access on the Mac running T3 Code, then refresh." + : "Cursor Keychain credentials could not be read.", }; } const accessToken = credential.success; @@ -151,7 +173,12 @@ export const readCursorCredential = Effect.fn("readCursorCredential")(function* const fingerprint = yield* Effect.result(accountHash(accessToken)); if (Result.isFailure(fingerprint)) return { kind: "unavailable", missing: false, error: "Cursor credentials could not be read." }; - return { kind: "token", accessToken, fingerprint: fingerprint.success }; + return { + kind: "token", + accessToken, + fingerprint: fingerprint.success, + viaApiKey: typeof credentialSource !== "string" && credentialSource.kind === "apiKey", + }; }); /** @@ -159,7 +186,7 @@ export const readCursorCredential = Effect.fn("readCursorCredential")(function* * from cache reads. `keychainToken` is only run for a Keychain login. */ export const readCursorAccountUsage = Effect.fn("readCursorAccountUsage")(function* ( - credentialSource: string | { readonly kind: "keychain" } | CursorResolvedCredential, + credentialSource: CursorCredentialSource | CursorResolvedCredential, sinceMs: number, endDate: number, keychainToken: Effect.Effect< @@ -171,11 +198,13 @@ export const readCursorAccountUsage = Effect.fn("readCursorAccountUsage")(functi ): Effect.fn.Return< CursorAccountUsageReadResult, never, - FileSystem.FileSystem | Crypto.Crypto | HttpClient.HttpClient + FileSystem.FileSystem | Digest.Digest | HttpClient.HttpClient > { const httpClient = yield* HttpClient.HttpClient; const resolved = - typeof credentialSource === "string" || credentialSource.kind === "keychain" + typeof credentialSource === "string" || + credentialSource.kind === "keychain" || + credentialSource.kind === "apiKey" ? yield* readCursorCredential(credentialSource, keychainToken) : credentialSource; if (resolved.kind === "unavailable") @@ -196,6 +225,20 @@ export const readCursorAccountUsage = Effect.fn("readCursorAccountUsage")(functi accountKey = yield* accountHash(subject); if (!Number.isFinite(sinceMs) || !Number.isFinite(endDate) || sinceMs < 0 || sinceMs > endDate) return yield* invalid("Invalid date window"); + // The web dashboard rejects API-key tokens; Cursor's RPC API accepts them. + const pageRequest = resolved.viaApiKey + ? HttpClientRequest.post( + `${DEFAULT_CURSOR_API_ENDPOINT}/aiserver.v1.DashboardService/GetFilteredUsageEvents`, + ).pipe( + HttpClientRequest.bearerToken(accessToken), + HttpClientRequest.setHeader("connect-protocol-version", "1"), + ) + : HttpClientRequest.post(DASHBOARD_USAGE_URL).pipe( + HttpClientRequest.setHeaders({ + Origin: "https://cursor.com", + Cookie: `WorkosCursorSessionToken=${encodeURIComponent(`${userId}::${accessToken}`)}`, + }), + ); const records: UsageRecord[] = []; const occurrences = new Map(); const pages: unknown[][] = []; @@ -211,11 +254,7 @@ export const readCursorAccountUsage = Effect.fn("readCursorAccountUsage")(functi } const response = yield* httpClient .execute( - HttpClientRequest.post(DASHBOARD_USAGE_URL).pipe( - HttpClientRequest.setHeaders({ - Origin: "https://cursor.com", - Cookie: `WorkosCursorSessionToken=${encodeURIComponent(`${userId}::${accessToken}`)}`, - }), + pageRequest.pipe( HttpClientRequest.bodyText( pageRequestBody(page, pageSize, sinceMs, endDate), "application/json", diff --git a/packages/provider-cursor/src/server/adapter.test.ts b/packages/provider-cursor/src/server/adapter.test.ts index e03c4e07242d4..4c421a352a8ca 100644 --- a/packages/provider-cursor/src/server/adapter.test.ts +++ b/packages/provider-cursor/src/server/adapter.test.ts @@ -219,7 +219,7 @@ describe("CursorAdapterV2", () => { Stream.takeUntil((event) => event.type === "turn.terminal"), Stream.runCollect, ); - assert.isFalse(sentWithMcpOverride); + assert.isTrue(sentWithMcpOverride); const rows = events.filter((event) => event.type === "subagent.updated"); assert.equal(rows[0]?.subagent.status, "running"); assert.equal(rows[0]?.subagent.model, model ?? null); @@ -510,11 +510,11 @@ describe("CursorAdapterV2", () => { ), ); - it.effect("fails standalone SDK transport diagnostics and sends compaction as /compress", () => + it.effect("fails standalone SDK transport diagnostics and compacts with SDK summarize", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-v2-errors-" }); - const sentMessages: Array = []; + const summarizeRequests: Array = []; let sendCalls = 0; const instanceId = ProviderInstanceId.make("cursor"); const threadId = ThreadId.make("cursor-transport-error-thread"); @@ -538,9 +538,7 @@ describe("CursorAdapterV2", () => { send: (input) => Effect.sync(() => { sendCalls += 1; - sentMessages.push( - typeof input.message === "string" ? input.message : input.message.text, - ); + summarizeRequests.push(input.summarize === true); const runId = `native-cursor-run-${sendCalls}`; return { agentId: "native-cursor-error", @@ -551,9 +549,10 @@ describe("CursorAdapterV2", () => { status: "finished" as const, model: { id: "composer-2.5" }, durationMs: 1, - ...(sendCalls === 1 - ? { result: "Error: RetriableError: WritableIterable is closed" } - : {}), + result: + sendCalls === 1 + ? "Error: RetriableError: WritableIterable is closed" + : "Summary of the conversation so far", }), cancel: Effect.void, }; @@ -646,11 +645,12 @@ describe("CursorAdapterV2", () => { attachments: [], }, }); - yield* runtime.events.pipe( - Stream.filter((event) => event.type === "turn.terminal"), - Stream.runHead, + const compactionEvents = yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, ); - assert.equal(sentMessages[1], "/compress"); + assert.deepEqual(summarizeRequests, [false, true]); + assert.notInclude(JSON.stringify(compactionEvents), "Summary of the conversation so far"); }).pipe( Effect.scoped, Effect.provide( diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.ts index 924139ec34daa..73f7ac9d9767d 100644 --- a/packages/provider-cursor/src/server/adapter.ts +++ b/packages/provider-cursor/src/server/adapter.ts @@ -2385,15 +2385,18 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( hasDeviceTools, delivered, ); + const compacted = message === "/compress"; const pendingUpdates: Array = []; let context: ActiveCursorTurn | null = null; - // MCP send overrides replace the ambient servers loaded when the agent opens. + // Create-time and send-time mcpServers merge with settingSources (SDK >= 1.0.39). const sdkRun = yield* agent.session .send({ message, + summarize: compacted, options: { model: cursorSdkModelSelection(turnInput.modelSelection), mode: turnInput.runtimePolicy.interactionMode === "plan" ? "plan" : "agent", + ...(mcpServers === undefined ? {} : { mcpServers }), }, onDelta: (update) => { if (context === null) { @@ -2405,7 +2408,6 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( }, }) .pipe(Effect.mapError(classifyCursorModelRejection(turnInput.modelSelection))); - const compacted = message === "/compress"; yield* Ref.set(told, { agent: agent.nativeThreadId, orchestration: !compacted && (delivered.orchestration || mcpServers !== undefined), @@ -2469,6 +2471,8 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( if ( context !== null && context.assistant.nextSegment === 0 && + // A summarize run's result is the summary, not an answer. + !compacted && // Text from a resume that made no progress is not the turn's answer. !isResumeFailureAfterTurnEnded(context, result) && result.result !== undefined && diff --git a/packages/provider-cursor/src/server/apiKey.ts b/packages/provider-cursor/src/server/apiKey.ts new file mode 100644 index 0000000000000..06c93e1f3bc55 --- /dev/null +++ b/packages/provider-cursor/src/server/apiKey.ts @@ -0,0 +1,24 @@ +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import * as HttpClient from "effect/http/HttpClient"; +import * as HttpClientRequest from "effect/http/HttpClientRequest"; +import * as HttpClientResponse from "effect/http/HttpClientResponse"; + +export const DEFAULT_CURSOR_API_ENDPOINT = "https://api2.cursor.sh"; + +const ApiKeyExchange = Schema.Struct({ accessToken: Schema.NonEmptyString }); + +/** Trades a user API key for the access token Cursor's RPCs accept, as `@cursor/sdk` does. */ +export const exchangeCursorApiKey = Effect.fn("exchangeCursorApiKey")(function* (apiKey: string) { + const client = yield* HttpClient.HttpClient; + const response = yield* client.execute( + HttpClientRequest.post(`${DEFAULT_CURSOR_API_ENDPOINT}/auth/exchange_user_api_key`).pipe( + HttpClientRequest.bearerToken(apiKey), + HttpClientRequest.bodyJsonUnsafe({}), + ), + ); + const { accessToken } = yield* HttpClientResponse.schemaBodyJson(ApiKeyExchange)( + yield* HttpClientResponse.filterStatusOk(response), + ); + return accessToken; +}, Effect.timeout("10 seconds")); diff --git a/packages/provider-cursor/src/server/auth.test.ts b/packages/provider-cursor/src/server/auth.test.ts index a5910387aaac1..c2e368641b5af 100644 --- a/packages/provider-cursor/src/server/auth.test.ts +++ b/packages/provider-cursor/src/server/auth.test.ts @@ -1,5 +1,7 @@ import type { SdkLoginOptions, StoredSdkCredentials } from "@cursor/sdk"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as Layer from "effect/Layer"; import { expect, it } from "@effect/vitest"; import { ProviderInstanceId, ProviderSetupError, type ProviderAuthState } from "@t3tools/contracts"; import * as Clock from "effect/Clock"; @@ -79,7 +81,7 @@ const phase = (auth: Auth, phase: ProviderAuthState["phase"], session = owner) = Effect.map(Option.getOrThrow), ); -it.layer(NodeServices.layer)("CursorAuth", (it) => { +it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("CursorAuth", (it) => { it.effect("closes SDK sessions and interrupts in-flight credential work before signing out", () => Effect.gen(function* () { const harness = yield* makeHarness(); diff --git a/packages/provider-cursor/src/server/auth.ts b/packages/provider-cursor/src/server/auth.ts index e9f4749ff4655..d34b3721f6ae7 100644 --- a/packages/provider-cursor/src/server/auth.ts +++ b/packages/provider-cursor/src/server/auth.ts @@ -6,7 +6,7 @@ import { } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; import * as Clock from "effect/Clock"; -import * as Crypto from "effect/Crypto"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; @@ -52,7 +52,7 @@ export interface CursorAuthOptions { export const makeCursorAuth = Effect.fn("makeCursorAuth")(function* (options: CursorAuthOptions) { const scope = yield* Scope.Scope; - const crypto = yield* Crypto.Crypto; + const random = yield* SecureRandom.SecureRandom; const lock = yield* Semaphore.make(1); const configuredKey = options.apiKey?.trim() || undefined; const emptyState: ProviderAuthState = { @@ -339,7 +339,7 @@ export const makeCursorAuth = Effect.fn("makeCursorAuth")(function* (options: Cu operation: "start", detail: "Cursor setup is already in progress.", }); - const id = yield* crypto.randomUUIDv4().pipe( + const id = yield* random.uuidV4().pipe( Effect.mapError( (cause) => new ProviderSetupError({ diff --git a/packages/provider-cursor/src/server/credentialStore.ts b/packages/provider-cursor/src/server/credentialStore.ts index d0638132f1b6f..d995a49f0d215 100644 --- a/packages/provider-cursor/src/server/credentialStore.ts +++ b/packages/provider-cursor/src/server/credentialStore.ts @@ -1,5 +1,6 @@ import type { SdkCredentialStore } from "@cursor/sdk"; import { ProviderSetupError, type ProviderInstanceId } from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; @@ -90,3 +91,22 @@ export const makeCursorCredentialStore = Effect.fn("makeCursorCredentialStore")( }; return { store, binding: credentials.binding }; }); + +/** The unexpired API key from this instance's T3 sign-in, read without loading the SDK. */ +export const readStoredCursorApiKey = Effect.fn("readStoredCursorApiKey")(function* ( + instanceId: ProviderInstanceId, +) { + const stored = yield* (yield* (yield* ProviderHost.ProviderHost).credentials( + "cursor", + instanceId, + )).get; + if (Option.isNone(stored)) return undefined; + const credentials = yield* decodeCredentials(new TextDecoder().decode(stored.value)).pipe( + Effect.option, + ); + if (Option.isNone(credentials)) return undefined; + const { apiKey, apiKeyExpiresAtMs } = credentials.value; + return apiKeyExpiresAtMs === undefined || apiKeyExpiresAtMs > (yield* Clock.currentTimeMillis) + ? apiKey + : undefined; +}); diff --git a/packages/provider-cursor/src/server/driver.test.ts b/packages/provider-cursor/src/server/driver.test.ts index 8f034ff185e98..d273e4b278194 100644 --- a/packages/provider-cursor/src/server/driver.test.ts +++ b/packages/provider-cursor/src/server/driver.test.ts @@ -1,5 +1,6 @@ // @effect-diagnostics nodeBuiltinImport:off import type { AgentOptions, SDKModel } from "@cursor/sdk"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { expect, it } from "@effect/vitest"; import { @@ -42,7 +43,7 @@ import { loadCursorSdk } from "./sdk.ts"; const { Cursor } = loadCursorSdk(); const layerTest = TestProviderHost.layer({ runBackgroundWork: false }).pipe( - Layer.provideMerge(NodeServices.layer), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), Layer.provideMerge(IdAllocator.layer), Layer.provideMerge(McpProviderSessions.layer), Layer.provideMerge(CursorSdk.layer), diff --git a/packages/provider-cursor/src/server/driver.ts b/packages/provider-cursor/src/server/driver.ts index cf95e89bd854b..a73ef9e047396 100644 --- a/packages/provider-cursor/src/server/driver.ts +++ b/packages/provider-cursor/src/server/driver.ts @@ -5,7 +5,7 @@ import { } from "@t3tools/contracts"; import { CursorSettings } from "../settings.ts"; import * as Effect from "effect/Effect"; -import * as Crypto from "effect/Crypto"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; @@ -51,7 +51,7 @@ const MAINTENANCE_CAPABILITIES = makeManualOnlyProviderMaintenanceCapabilities({ export type CursorDriverEnv = | CursorAdapterV2DriverEnv - | Crypto.Crypto + | SecureRandom.SecureRandom | FileSystem.FileSystem | Path.Path | HttpClient.HttpClient @@ -74,14 +74,20 @@ export const CursorDriver: ProviderDriver< usage: { kind: "scan", provider: "cursor", - prepare: ({ settings }) => + prepare: ({ instances, settings }) => CursorUsageAccounts.CursorUsageAccounts.pipe( - Effect.flatMap((accounts) => accounts.prepare(settings.cursorKeychainUsageEnabled)), + Effect.flatMap((accounts) => + accounts.prepare({ + instances, + keychainUsageEnabled: settings.cursorKeychainUsageEnabled, + }), + ), ), - scan: ({ settings, windowStartMs, retentionCutoffMs, awaitRefresh }) => + scan: ({ instances, settings, windowStartMs, retentionCutoffMs, awaitRefresh }) => CursorUsageAccounts.CursorUsageAccounts.pipe( Effect.flatMap((accounts) => accounts.scan({ + instances, keychainUsageEnabled: settings.cursorKeychainUsageEnabled, windowStartMs, retentionCutoffMs, diff --git a/packages/provider-cursor/src/server/usageLimits.test.ts b/packages/provider-cursor/src/server/usageLimits.test.ts index 1b4cadf88ae3f..617616d14bc25 100644 --- a/packages/provider-cursor/src/server/usageLimits.test.ts +++ b/packages/provider-cursor/src/server/usageLimits.test.ts @@ -182,17 +182,46 @@ describe("Cursor usage limits", () => { }), ); - it.effect("does not use a stored login for an explicit API key", () => + it.effect("reads an API key's own account instead of a stored login", () => Effect.gen(function* () { - const limits = yield* withNodeServices( - readCursorUsageLimits({ apiEndpoint: "" }, { CURSOR_API_KEY: "different-account" }).pipe( - Effect.provideService( - HttpClient.HttpClient, - HttpClient.make(() => Effect.die("must not request usage")), + for (const platform of ["linux", "darwin"] as const) { + const requests: Array = []; + const limits = yield* withNodeServices( + readCursorUsageLimits({ apiEndpoint: "" }, { CURSOR_API_KEY: "api-key" }, true).pipe( + Effect.provideService(HostProcess.Platform, platform), + Effect.provideService( + FileSystem.FileSystem, + FileSystem.makeNoop({ + readFileString: () => Effect.die("must not read a stored login"), + }), + ), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make((request) => { + requests.push([request.url, request.headers.authorization]); + return Effect.succeed( + HttpClientResponse.fromWeb( + request, + Response.json( + request.url.endsWith("/auth/exchange_user_api_key") + ? { accessToken: "api-key-access-token" } + : { planUsage: { totalPercentUsed: 37 } }, + ), + ), + ); + }), + ), ), - ), - ); - expect(limits.unavailable?.reason).toBe("unsupported"); + ); + expect(requests).toEqual([ + ["https://api2.cursor.sh/auth/exchange_user_api_key", "Bearer api-key"], + [ + "https://api2.cursor.sh/aiserver.v1.DashboardService/GetCurrentPeriodUsage", + "Bearer api-key-access-token", + ], + ]); + expect(limits.windows[0]?.usedPercent).toBe(37); + } }), ); @@ -246,13 +275,14 @@ describe("Cursor usage limits", () => { }), ); - it.effect("does not read Keychain or send its token to a custom endpoint", () => + it.effect("does not send a Keychain login or API key to a custom endpoint", () => Effect.gen(function* () { for (const [apiEndpoint, environment] of [ ["http://localhost:3000", {}], ["", { CURSOR_API_ENDPOINT: "http://localhost:3000" }], ["https://cursor-proxy.example", {}], ["", { CURSOR_API_ENDPOINT: "https://cursor-proxy.example" }], + ["https://cursor-proxy.example", { CURSOR_API_KEY: "api-key" }], ] as const) { const limits = yield* withNodeServices( readCursorUsageLimits({ apiEndpoint }, environment, true).pipe( diff --git a/packages/provider-cursor/src/server/usageLimits.ts b/packages/provider-cursor/src/server/usageLimits.ts index 049e646d2c492..87fcecef4e97f 100644 --- a/packages/provider-cursor/src/server/usageLimits.ts +++ b/packages/provider-cursor/src/server/usageLimits.ts @@ -16,10 +16,10 @@ import { makeUnavailableUsageLimits, makeUsageLimits, } from "@t3tools/provider-core/server/usageLimits"; +import { DEFAULT_CURSOR_API_ENDPOINT, exchangeCursorApiKey } from "./apiKey.ts"; import * as CursorKeychain from "./CursorKeychain.ts"; const CursorCredentials = Schema.Struct({ accessToken: Schema.optional(Schema.String) }); -const DEFAULT_CURSOR_API_ENDPOINT = "https://api2.cursor.sh"; const decodeCredentials = Schema.decodeEffect(Schema.fromJsonString(CursorCredentials)); const CursorUsageResponse = Schema.Struct({ billingCycleEnd: Schema.optional(Schema.Union([Schema.String, Schema.Number])), @@ -77,19 +77,25 @@ export const readCursorUsageLimits = Effect.fn("readCursorUsageLimits")(function DEFAULT_CURSOR_API_ENDPOINT ).replace(/\/$/, ""); let token = environment.CURSOR_AUTH_TOKEN?.trim(); - // An explicit API key can name a different account from the stored login. - if (!token && environment.CURSOR_API_KEY?.trim()) { - return makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" }); - } + const apiKey = environment.CURSOR_API_KEY?.trim(); const credentialStore = environment.AGENT_CLI_CREDENTIAL_STORE; - if (!token && credentialStore === "memory") { + // An API key can name a different account from the stored login, so read the key's own. + if (!token && apiKey) { + if (endpoint !== DEFAULT_CURSOR_API_ENDPOINT) { + return makeUnavailableUsageLimits({ + checkedAt, + reason: "unsupported", + message: "Cursor usage for an API key requires the default Cursor endpoint.", + }); + } + token = yield* exchangeCursorApiKey(apiKey); + } else if (!token && credentialStore === "memory") { return makeUnavailableUsageLimits({ checkedAt, reason: "unsupported", message: "Cursor usage requires a CLI login or CURSOR_AUTH_TOKEN.", }); - } - if (!token && platform === "darwin" && credentialStore !== "file") { + } else if (!token && platform === "darwin" && credentialStore !== "file") { if (!allowKeychain) { return makeUnavailableUsageLimits({ checkedAt, diff --git a/packages/provider-fx/src/server/acpSupport.ts b/packages/provider-fx/src/server/acpSupport.ts index fb6dfae56ef86..b77a4431faf1a 100644 --- a/packages/provider-fx/src/server/acpSupport.ts +++ b/packages/provider-fx/src/server/acpSupport.ts @@ -7,7 +7,7 @@ import { } from "@t3tools/contracts"; import type { FxSettings } from "../settings.ts"; import { getModelSelectionStringOptionValue } from "@t3tools/shared/model"; -import type * as Crypto from "effect/Crypto"; +import type * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import type * as Scope from "effect/Scope"; @@ -219,7 +219,7 @@ export const makeFxAcpRuntime = Effect.fn("makeFxAcpRuntime")(function* ( ): Effect.fn.Return< AcpSessionRuntime.AcpSessionRuntime["Service"], EffectAcpErrors.AcpError, - ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | Scope.Scope + ChildProcessSpawner.ChildProcessSpawner | SecureRandom.SecureRandom | Scope.Scope > { const { fxSettings, environment, ...runtimeOptions } = input; const context = yield* Layer.build( diff --git a/packages/provider-fx/src/server/adapter.ts b/packages/provider-fx/src/server/adapter.ts index dfb956e6d13f1..868b13f497de3 100644 --- a/packages/provider-fx/src/server/adapter.ts +++ b/packages/provider-fx/src/server/adapter.ts @@ -2,7 +2,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import { resolveSelfInvocation, type SelfInvocation } from "@t3tools/shared/nodeRuntime"; import { type OrchestrationV2ProviderCapabilities } from "@t3tools/contracts"; import { FxSettings } from "../settings.ts"; -import type * as Crypto from "effect/Crypto"; +import type * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import type * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; @@ -159,7 +159,7 @@ export interface FxAdapterV2Options { ) => Effect.Effect< AcpSessionRuntime.AcpSessionRuntime["Service"], EffectAcpErrors.AcpError, - ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | Scope.Scope + ChildProcessSpawner.ChildProcessSpawner | SecureRandom.SecureRandom | Scope.Scope >; readonly assertComplete?: Effect.Effect; } @@ -203,7 +203,7 @@ export const makeFxAdapterV2 = Effect.fn("makeFxAdapterV2")(function* ( export type FxAdapterV2DriverEnv = | ChildProcessSpawner.ChildProcessSpawner - | Crypto.Crypto + | SecureRandom.SecureRandom | FileSystem.FileSystem | IdAllocator.IdAllocatorV2 | Path.Path diff --git a/packages/provider-fx/src/server/driver.ts b/packages/provider-fx/src/server/driver.ts index c922b315b56ce..7a3ef9dd4b4bf 100644 --- a/packages/provider-fx/src/server/driver.ts +++ b/packages/provider-fx/src/server/driver.ts @@ -1,7 +1,7 @@ import { TextGenerationError } from "@t3tools/contracts"; import { FxSettings } from "../settings.ts"; import * as HostProcess from "@t3tools/shared/HostProcess"; -import type * as Crypto from "effect/Crypto"; +import type * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; @@ -63,7 +63,7 @@ const unsupportedTextGeneration: ProviderTextGeneration = (() => { export type FxDriverEnv = | FxAdapterV2DriverEnv | ChildProcessSpawner.ChildProcessSpawner - | Crypto.Crypto + | SecureRandom.SecureRandom | FileSystem.FileSystem | Path.Path | ProviderHost.ProviderHost; diff --git a/packages/provider-grok/src/server/acpSupport.ts b/packages/provider-grok/src/server/acpSupport.ts index be98e177da994..a7d1d5ed3b0cd 100644 --- a/packages/provider-grok/src/server/acpSupport.ts +++ b/packages/provider-grok/src/server/acpSupport.ts @@ -6,7 +6,7 @@ import { type RuntimeMode, } from "@t3tools/contracts"; import type { GrokSettings } from "../settings.ts"; -import * as Crypto from "effect/Crypto"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Scope from "effect/Scope"; @@ -126,7 +126,7 @@ export const makeGrokAcpRuntime = Effect.fn("GrokAcpSupport.makeGrokAcpRuntime") ): Effect.fn.Return< AcpSessionRuntime.AcpSessionRuntime["Service"], EffectAcpErrors.AcpError, - ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | Scope.Scope + ChildProcessSpawner.ChildProcessSpawner | SecureRandom.SecureRandom | Scope.Scope > { const processGroupPlatform = yield* HostProcess.Platform.pipe(Effect.provide(NodeServices.layer)); const acpContext = yield* Layer.build( diff --git a/packages/provider-grok/src/server/adapter.ts b/packages/provider-grok/src/server/adapter.ts index d826315b69fa6..35a8794619dff 100644 --- a/packages/provider-grok/src/server/adapter.ts +++ b/packages/provider-grok/src/server/adapter.ts @@ -14,7 +14,7 @@ import { type RuntimeMode, } from "@t3tools/contracts"; import { GrokSettings } from "../settings.ts"; -import * as Crypto from "effect/Crypto"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; @@ -128,7 +128,7 @@ export interface GrokAdapterV2Options { ) => Effect.Effect< AcpSessionRuntime.AcpSessionRuntime["Service"], EffectAcpErrors.AcpError, - ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | Scope.Scope + ChildProcessSpawner.ChildProcessSpawner | SecureRandom.SecureRandom | Scope.Scope >; readonly assertComplete?: Effect.Effect; } @@ -357,7 +357,7 @@ export const makeGrokAdapterV2 = Effect.fn("makeGrokAdapterV2")(function* ( export type GrokAdapterV2DriverEnv = | ChildProcessSpawner.ChildProcessSpawner - | Crypto.Crypto + | SecureRandom.SecureRandom | FileSystem.FileSystem | IdAllocator.IdAllocatorV2 | Path.Path diff --git a/packages/provider-grok/src/server/driver.test.ts b/packages/provider-grok/src/server/driver.test.ts index 3a080ec60582a..5987a27c38ad2 100644 --- a/packages/provider-grok/src/server/driver.test.ts +++ b/packages/provider-grok/src/server/driver.test.ts @@ -1,3 +1,4 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { expect, it } from "@effect/vitest"; import { ProviderInstanceId } from "@t3tools/contracts"; @@ -21,7 +22,7 @@ import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; const layerTest = TestProviderHost.layer({ runBackgroundWork: false }).pipe( - Layer.provideMerge(NodeServices.layer), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), Layer.provideMerge(IdAllocator.layer), Layer.provideMerge(McpProviderSessions.layer), Layer.provideMerge(ProviderLatestVersions.layer), diff --git a/packages/provider-grok/src/server/driver.ts b/packages/provider-grok/src/server/driver.ts index acb8690509e2d..c9f683c3417ee 100644 --- a/packages/provider-grok/src/server/driver.ts +++ b/packages/provider-grok/src/server/driver.ts @@ -1,6 +1,6 @@ import { ProviderDriverKind } from "@t3tools/contracts"; import { GrokSettings } from "../settings.ts"; -import * as Crypto from "effect/Crypto"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; @@ -93,7 +93,7 @@ export type GrokDriverEnv = | GrokAdapterV2DriverEnv | ProviderHost.ProviderHost | ChildProcessSpawner.ChildProcessSpawner - | Crypto.Crypto + | SecureRandom.SecureRandom | FileSystem.FileSystem | HttpClient.HttpClient | ProviderLatestVersions.ProviderLatestVersions @@ -117,7 +117,7 @@ export const GrokDriver: ProviderDriver enabled, config, }) { - const crypto = yield* Crypto.Crypto; + const random = yield* SecureRandom.SecureRandom; const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const httpClient = yield* HttpClient.HttpClient; const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions; @@ -189,7 +189,7 @@ export const GrokDriver: ProviderDriver Effect.provideService(HttpClient.HttpClient, httpClient), Effect.provideService(FileSystem.FileSystem, fileSystem), Effect.provideService(Path.Path, path), - Effect.provideService(Crypto.Crypto, crypto), + Effect.provideService(SecureRandom.SecureRandom, random), Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), ); diff --git a/packages/provider-grok/src/server/status.ts b/packages/provider-grok/src/server/status.ts index 3ea0c00ec1a7e..aa58c8babae7d 100644 --- a/packages/provider-grok/src/server/status.ts +++ b/packages/provider-grok/src/server/status.ts @@ -9,7 +9,7 @@ import { import type { GrokSettings } from "../settings.ts"; import type * as EffectAcpSchema from "effect-acp/compat"; import { causeErrorTag } from "@t3tools/shared/observability"; -import * as Crypto from "effect/Crypto"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; @@ -401,7 +401,7 @@ export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(func ): Effect.fn.Return< ServerProviderDraft, never, - ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto + ChildProcessSpawner.ChildProcessSpawner | SecureRandom.SecureRandom > { const checkedAt = DateTime.formatIso(yield* DateTime.now); const fallbackModels = grokModelsFromSettings(grokSettings.customModels); diff --git a/packages/provider-grok/src/server/textGeneration.ts b/packages/provider-grok/src/server/textGeneration.ts index 9907ad1441357..61a6b2d482f53 100644 --- a/packages/provider-grok/src/server/textGeneration.ts +++ b/packages/provider-grok/src/server/textGeneration.ts @@ -1,4 +1,4 @@ -import * as Crypto from "effect/Crypto"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; @@ -27,7 +27,7 @@ export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(functi grokSettings: GrokSettings, environment: NodeJS.ProcessEnv = process.env, ) { - const crypto = yield* Crypto.Crypto; + const random = yield* SecureRandom.SecureRandom; const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; const runGrokJson: TextGenerationOperations.Runner = Effect.fn("GrokTextGeneration.runGrokJson")( @@ -41,7 +41,7 @@ export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(functi cwd, clientInfo: { name: "t3-code-git-text", version: "0.0.0" }, }).pipe( - Effect.provideService(Crypto.Crypto, crypto), + Effect.provideService(SecureRandom.SecureRandom, random), Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, commandSpawner), ); diff --git a/packages/provider-kiro/package.json b/packages/provider-kiro/package.json new file mode 100644 index 0000000000000..b0cdc600f6072 --- /dev/null +++ b/packages/provider-kiro/package.json @@ -0,0 +1,40 @@ +{ + "name": "@t3tools/provider-kiro", + "private": true, + "type": "module", + "exports": { + "./client": { + "types": "./src/client.ts", + "import": "./src/client.ts" + }, + "./settings": { + "types": "./src/settings.ts", + "import": "./src/settings.ts" + }, + "./server": { + "types": "./src/server.ts", + "import": "./src/server.ts" + }, + "./testing": { + "types": "./src/testing.ts", + "import": "./src/testing.ts" + } + }, + "scripts": { + "typecheck": "tsc --noEmit", + "test": "vp test run --config ../../vite.config.ts --dir ." + }, + "dependencies": { + "@t3tools/contracts": "workspace:*", + "@t3tools/provider-acp": "workspace:*", + "@t3tools/provider-core": "workspace:*", + "@t3tools/shared": "workspace:*", + "effect": "catalog:" + }, + "devDependencies": { + "@effect/vitest": "catalog:", + "@types/node": "catalog:", + "effect-acp": "workspace:*", + "vite-plus": "catalog:" + } +} diff --git a/packages/provider-kiro/src/client.ts b/packages/provider-kiro/src/client.ts new file mode 100644 index 0000000000000..06f551688bce6 --- /dev/null +++ b/packages/provider-kiro/src/client.ts @@ -0,0 +1,43 @@ +import { ProviderDriverKind } from "@t3tools/contracts"; +import { defineProviderClient } from "@t3tools/provider-core/client"; + +import { KiroSettings } from "./settings.ts"; + +const TILE = + "M260 0H940A260 260 0 0 1 1200 260V940A260 260 0 0 1 940 1200H260A260 260 0 0 1 0 940V260A260 260 0 0 1 260 0Z"; +const GHOST = + "M398.554 818.914C316.315 1001.03 491.477 1046.74 620.672 940.156C658.687 1059.66 801.052 970.473 852.234 877.795C964.787 673.567 919.318 465.357 907.64 422.374C827.637 129.443 427.623 128.946 358.8 423.865C342.651 475.544 342.402 534.18 333.458 595.051C328.986 625.86 325.507 645.488 313.83 677.785C306.873 696.424 297.68 712.819 282.773 740.645C259.915 783.881 269.604 867.113 387.87 823.883L399.051 818.914H398.554Z"; +const LEFT_EYE = + "M636.123 549.353C603.328 549.353 598.359 510.097 598.359 486.742C598.359 465.623 602.086 448.977 609.293 438.293C615.504 428.852 624.697 424.131 636.123 424.131C647.555 424.131 657.492 428.852 664.447 438.541C672.398 449.474 676.623 466.12 676.623 486.742C676.623 525.998 661.471 549.353 636.375 549.353H636.123Z"; +const RIGHT_EYE = + "M771.24 549.353C738.445 549.353 733.477 510.097 733.477 486.742C733.477 465.623 737.203 448.977 744.41 438.293C750.621 428.852 759.814 424.131 771.24 424.131C782.672 424.131 792.609 428.852 799.564 438.541C807.516 449.474 811.74 466.12 811.74 486.742C811.74 525.998 796.588 549.353 771.492 549.353H771.24Z"; +const white = { light: "#FFFFFF", dark: "#FFFFFF" }; +const black = { light: "#000000", dark: "#000000" }; + +export const kiroClient = defineProviderClient({ + driverKind: ProviderDriverKind.make("kiro"), + label: "Kiro", + featured: false, + badgeLabel: "Early Access", + settingsSchema: KiroSettings, + environmentFields: [ + { + name: "KIRO_API_KEY", + label: "Kiro API key", + description: "Optional. Signs in without `kiro-cli login` (Kiro Pro and above).", + placeholder: "Paste API key", + sensitive: true, + }, + ], + icon: { + viewBox: "0 0 1200 1200", + fill: { light: "#9046FF", dark: "#9046FF" }, + paths: [ + // The ghost is a hole in the tile, so a monochrome icon still shows it. + { d: `${TILE}${GHOST}${LEFT_EYE}${RIGHT_EYE}`, fillRule: "evenodd" }, + { d: GHOST, fill: white }, + { d: LEFT_EYE, fill: black }, + { d: RIGHT_EYE, fill: black }, + ], + }, +}); diff --git a/packages/provider-kiro/src/server.ts b/packages/provider-kiro/src/server.ts new file mode 100644 index 0000000000000..e0dce55de5d68 --- /dev/null +++ b/packages/provider-kiro/src/server.ts @@ -0,0 +1,2 @@ +export { KiroDriver, type KiroDriverEnv } from "./server/driver.ts"; +export { type KiroAdapterV2DriverEnv } from "./server/adapter.ts"; diff --git a/packages/provider-kiro/src/server/acpSupport.ts b/packages/provider-kiro/src/server/acpSupport.ts new file mode 100644 index 0000000000000..43d8c06b77a98 --- /dev/null +++ b/packages/provider-kiro/src/server/acpSupport.ts @@ -0,0 +1,151 @@ +import type * as EffectAcpSchema from "effect-acp/compat"; +import type { ProviderApprovalOption, RuntimeMode } from "@t3tools/contracts"; +import type { KiroSettings } from "../settings.ts"; +import type * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import type * as Scope from "effect/Scope"; +import type * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; +import type * as EffectAcpErrors from "effect-acp/errors"; + +import { + acpPermissionDisposition, + type AcpPermissionDisposition, + type AcpRuntimePolicy, +} from "@t3tools/provider-acp/server/clientPolicy"; +import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; + +/** + * Kiro's default engine is a v2 server this driver does not speak, so V3 is + * requested. `--auth-method=cli` keeps access tokens inside Kiro. V3 rejects the + * v2 launch flags; mode and model are set per session with `session/set_config_option`. + */ +const KIRO_ACP_ARGS = ["acp", "--agent-engine=v3", "--auth-method=cli"] as const; + +/** + * Kiro's `autopilot` session option. Off (Supervised), Kiro also asks the user + * to review a turn's file changes before it ends. Sessions start "on", so T3 + * sets it from the thread's runtime mode. + */ +export const KIRO_AUTOPILOT_CONFIG_ID = "autopilot"; + +/** Kiro's model session option (`configId: "model"` in the V3 migration guide). */ +export const KIRO_MODEL_CONFIG_ID = "model"; + +/** + * Kiro's reasoning effort session option (`configId: "effortLevel"` in the V3 + * migration guide). Kiro advertises it only while a model with effort runs. + */ +export const KIRO_EFFORT_CONFIG_ID = "effortLevel"; + +/** + * Kiro's agent session option. Kiro V3 offers its agents (the bundled ones, + * `~/.kiro/agents`, and the workspace's `.kiro/agents`) as the choices of its + * `mode` select, and the thread's choice is stored under the same id. + */ +export const KIRO_AGENT_CONFIG_ID = "mode"; + +/** + * Kiro offers two permission postures, Supervised and Autopilot, which T3's + * Supervised and Full access select. Any other mode runs Supervised. + */ +export const KIRO_SUPPORTED_RUNTIME_MODES = [ + "approval-required", + "full-access", +] as const satisfies ReadonlyArray; + +/** + * Autopilot is on only for an unrestricted Full access thread. An explicit + * approval or sandbox override keeps Kiro Supervised, so its end-of-turn + * review still reaches the user and every tool prompt reaches T3's policy + * check (the same rule as Grok's `grokLaunchRuntimeMode`). + */ +export function kiroAutopilotValue(policy: { + readonly runtimeMode: RuntimeMode; + readonly approvalPolicy?: unknown; + readonly sandboxPolicy?: unknown; +}): "on" | "off" { + return policy.runtimeMode === "full-access" && + policy.approvalPolicy === undefined && + policy.sandboxPolicy === undefined + ? "on" + : "off"; +} + +type KiroAcpRuntimeSettings = Pick; + +export function buildKiroAcpSpawnInput( + settings: KiroAcpRuntimeSettings | null | undefined, + cwd: string, + environment?: NodeJS.ProcessEnv, +): AcpSessionRuntime.AcpSpawnInput { + return { + command: settings?.binaryPath || "kiro-cli", + args: [...KIRO_ACP_ARGS], + cwd, + ...(environment === undefined ? {} : { env: environment }), + }; +} + +/** + * Approval choices a Kiro permission request can honor; V3's options are + * authoritative. Its `allow_always` saves a consent rule for the workspace or + * wider, so it is offered, as "Always allow", only without a one-time choice. + */ +export function kiroApprovalOptions( + request: EffectAcpSchema.RequestPermissionRequest, +): ReadonlyArray { + const has = (kind: EffectAcpSchema.PermissionOption["kind"]) => + request.options.some((option) => option.kind === kind && option.optionId.trim().length > 0); + return [ + ...(has("allow_once") + ? [{ decision: "accept", label: "Allow once" } as const] + : has("allow_always") + ? [{ decision: "acceptForSession", label: "Always allow" } as const] + : []), + ...(has("reject_once") ? [{ decision: "decline", label: "Deny" } as const] : []), + { decision: "cancel", label: "Cancel" }, + ]; +} + +/** + * T3's answer to a Kiro permission request. A policy approval may only use + * Kiro's `allow_once`: its `allow_always` saves a consent rule for the whole + * workspace or wider, which would outlive the thread. When Kiro offers no + * one-time choice, the request goes to the user instead of persisting a grant. + */ +export function kiroPermissionDisposition( + policy: AcpRuntimePolicy, + request: EffectAcpSchema.RequestPermissionRequest, +): AcpPermissionDisposition { + const disposition = acpPermissionDisposition(policy, request); + const offersOnce = request.options.some( + (option) => option.kind === "allow_once" && option.optionId.trim().length > 0, + ); + return disposition === "allow" && !offersOnce ? "ask" : disposition; +} + +export interface KiroAcpRuntimeInput extends Omit< + AcpSessionRuntime.AcpSessionRuntimeOptions, + "authMethodId" | "spawn" +> { + readonly settings: KiroAcpRuntimeSettings | null | undefined; + readonly environment?: NodeJS.ProcessEnv; +} + +export const makeKiroAcpRuntime = Effect.fn("KiroAcpSupport.makeKiroAcpRuntime")(function* ( + input: KiroAcpRuntimeInput, +): Effect.fn.Return< + AcpSessionRuntime.AcpSessionRuntime["Service"], + EffectAcpErrors.AcpError, + ChildProcessSpawner.ChildProcessSpawner | SecureRandom.SecureRandom | Scope.Scope +> { + const { settings, environment, ...runtimeOptions } = input; + const context = yield* Layer.build( + AcpSessionRuntime.layer({ + ...runtimeOptions, + spawn: buildKiroAcpSpawnInput(settings, input.cwd, environment), + }), + ); + return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(Effect.provide(context)); +}); diff --git a/packages/provider-kiro/src/server/adapter.ts b/packages/provider-kiro/src/server/adapter.ts new file mode 100644 index 0000000000000..6815b60e8f227 --- /dev/null +++ b/packages/provider-kiro/src/server/adapter.ts @@ -0,0 +1,641 @@ +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { resolveSelfInvocation, type SelfInvocation } from "@t3tools/shared/nodeRuntime"; +import { + type ModelSelection, + ProviderDriverKind, + type OrchestrationV2ProviderCapabilities, +} from "@t3tools/contracts"; +import { KiroSettings } from "../settings.ts"; +import { getModelSelectionStringOptionValue } from "@t3tools/shared/model"; +import type * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Effect from "effect/Effect"; +import type * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; +import type * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; +import type * as Scope from "effect/Scope"; +import * as Stream from "effect/Stream"; +import type * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; +import type * as EffectAcpSchema from "effect-acp/compat"; +import * as EffectAcpErrors from "effect-acp/errors"; + +import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; +import { + AcpProviderCapabilitiesV2, + makeAcpAdapterV2, + type AcpAdapterV2Flavor, + type AcpAdapterV2RuntimeInput, + type AcpAdapterV2SubagentUpdate, +} from "@t3tools/provider-acp/server/adapter"; +import type { AcpToolCallState } from "@t3tools/provider-acp/server/runtimeModel"; +import { makeAcpNativeLoggerFactory } from "@t3tools/provider-acp/server/nativeLogging"; +import { + ProviderAdapterDriverCreateError, + type ProviderAdapterDriver, + type ProviderAdapterDriverCreateInput, +} from "@t3tools/provider-core/server/adapterDriver"; +import { makeProviderFailure } from "@t3tools/provider-core/server/failure"; +import type * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment"; +import type * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; +import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers"; +import type * as ProviderHost from "@t3tools/provider-core/server/ProviderHost"; +import { + KIRO_AGENT_CONFIG_ID, + KIRO_AUTOPILOT_CONFIG_ID, + KIRO_EFFORT_CONFIG_ID, + KIRO_MODEL_CONFIG_ID, + kiroApprovalOptions, + kiroAutopilotValue, + kiroPermissionDisposition, + makeKiroAcpRuntime, +} from "./acpSupport.ts"; + +export const KIRO_PROVIDER = ProviderDriverKind.make("kiro"); +/** T3's slug for "Kiro default", and Kiro's documented default model id. */ +const KIRO_DEFAULT_MODEL = "default"; +const KIRO_COMPACT_METHOD = "_kiro/session/compact"; +const KIRO_STEER_METHOD = "_session/steer"; +const KIRO_FALLBACK_DEFAULT_MODEL = "auto"; +const DEFAULT_KIRO_SETTINGS = Schema.decodeSync(KiroSettings)({}); + +const KiroProviderCapabilitiesV2 = { + ...AcpProviderCapabilitiesV2, + sessions: { + ...AcpProviderCapabilitiesV2.sessions, + supportsModelSwitchInSession: true, + }, + // Kiro 2.27 and later fork at a turn's prompt (`_meta.kiro.messageId`); see kiroForkFromTurn. + threads: { + ...AcpProviderCapabilitiesV2.threads, + canForkThread: true, + canForkFromTurn: true, + }, + // `_session/steer` waits for the running tool, then Kiro reads the message at its next step. + turns: { + ...AcpProviderCapabilitiesV2.turns, + supportsActiveSteering: true, + activeSteeringInterruptsTools: false, + // `_session/steer` takes a string, so a message with images restarts the turn. + activeSteeringAcceptsAttachments: false, + }, + tools: { + ...AcpProviderCapabilitiesV2.tools, + supportsMcpTools: true, + }, + subagents: { + ...AcpProviderCapabilitiesV2.subagents, + supportsSubagents: true, + emitsSubagentLifecycle: true, + }, +} satisfies OrchestrationV2ProviderCapabilities; + +const KiroCompactResult = Schema.Struct({ success: Schema.Boolean }); +const decodeKiroCompactResult = Schema.decodeUnknownOption(KiroCompactResult); + +/** Kiro answers a `/compact` prompt as chat, so T3 compacts with Kiro's own request. */ +const compactKiroSession = ( + runtime: AcpSessionRuntime.AcpSessionRuntime["Service"], + sessionId: string, +) => + runtime.request(KIRO_COMPACT_METHOD, { sessionId }).pipe( + Effect.flatMap((result) => + Option.exists(decodeKiroCompactResult(result), (decoded) => decoded.success) + ? Effect.void + : Effect.fail( + new EffectAcpErrors.AcpRequestError({ + code: -32603, + errorMessage: "Kiro could not compact the conversation.", + method: KIRO_COMPACT_METHOD, + data: result, + }), + ), + ), + ); + +const KiroSteerResult = Schema.Struct({ queued: Schema.Literal(true), messageId: Schema.String }); +const decodeKiroSteerResult = Schema.decodeUnknownOption(KiroSteerResult); +const KiroSteeringInjected = Schema.Struct({ + kiro: Schema.Struct({ kind: Schema.Literal("steering_injected"), messageId: Schema.String }), +}); +const decodeKiroSteeringInjected = Schema.decodeUnknownOption(KiroSteeringInjected); + +/** Kiro queues a steer, then reports `steering_injected` with its id once the model reads it. */ +const kiroSteering = { + send: ( + runtime: AcpSessionRuntime.AcpSessionRuntime["Service"], + sessionId: string, + text: string, + ) => + runtime.request(KIRO_STEER_METHOD, { sessionId, message: text }).pipe( + Effect.flatMap((result) => + Option.match(decodeKiroSteerResult(result), { + onSome: (decoded) => Effect.succeed(decoded.messageId), + onNone: () => + Effect.fail( + new EffectAcpErrors.AcpRequestError({ + code: -32603, + errorMessage: "Kiro did not queue the steering message.", + method: KIRO_STEER_METHOD, + data: result, + }), + ), + }), + ), + ), + injectedSteerId: (notification: EffectAcpSchema.SessionNotification) => + notification.update.sessionUpdate === "session_info_update" + ? Option.getOrUndefined(decodeKiroSteeringInjected(notification.update._meta))?.kiro.messageId + : undefined, +}; + +const decodeKiroForkCapability = Schema.decodeUnknownOption( + Schema.Struct({ kiro: Schema.Struct({ messageId: Schema.Literal(true) }) }), +); +const decodeKiroUserMessageId = Schema.decodeUnknownOption( + Schema.Struct({ + kiro: Schema.Struct({ + kind: Schema.Literal("user_message_id_assigned"), + userMessageId: Schema.String, + }), + }), +); + +/** + * Kiro assigns each prompt a `userMessageId`, and `session/fork` with that id keeps the + * session up to and including the reply to that prompt. + */ +const kiroForkFromTurn = { + supported: ( + initializeResult: AcpSessionRuntime.AcpSessionRuntimeStartResult["initializeResult"], + ) => + Option.isSome( + decodeKiroForkCapability( + initializeResult.agentCapabilities?.sessionCapabilities?.fork?._meta, + ), + ), + nativeTurnId: (notification: EffectAcpSchema.SessionNotification) => + notification.update.sessionUpdate === "session_info_update" + ? Option.getOrUndefined(decodeKiroUserMessageId(notification.update._meta))?.kiro + .userMessageId + : undefined, + forkMeta: (messageId: string) => ({ kiro: { messageId } }), +}; + +export interface KiroAdapterV2Options { + readonly instanceId: Parameters[0]["instanceId"]; + readonly settings: KiroSettings; + readonly environment: NodeJS.ProcessEnv; + readonly selfInvocation: SelfInvocation; + readonly nativeLogging?: Parameters[0]["nativeLogging"]; + /** + * Kiro's id for "Kiro default" (the provider snapshot's `--list-models` + * default). Absent, it is `auto`. + */ + readonly defaultModel?: Effect.Effect; + /** Replaces the `kiro-cli` launch (replay tests). Kiro's session setup still applies. */ + readonly makeRuntime?: ( + input: AcpAdapterV2RuntimeInput, + ) => Effect.Effect< + AcpSessionRuntime.AcpSessionRuntime["Service"], + EffectAcpErrors.AcpError, + ChildProcessSpawner.ChildProcessSpawner | SecureRandom.SecureRandom | Scope.Scope + >; + readonly assertComplete?: Effect.Effect; + readonly testHooks?: Parameters[0]["testHooks"]; +} + +/** Kiro's `model` option once it advertises one. */ +const findKiroModelOption = (configOptions: ReadonlyArray) => + configOptions.find((option) => option.id === KIRO_MODEL_CONFIG_ID || option.category === "model"); + +/** + * Kiro selects models only through its `model` config option; "default" is + * Kiro's own default. The write goes to `model` even before Kiro advertises it, + * and for unlisted ids: Kiro fails the next prompt on a model it can't use. + */ +const applyKiroModel = Effect.fn("KiroAdapterV2.applyKiroModel")(function* ( + runtime: AcpSessionRuntime.AcpSessionRuntime["Service"], + modelSelection: ModelSelection, + defaultModel: Effect.Effect, + agentSwitched: boolean, +) { + const modelOption = findKiroModelOption(yield* runtime.getConfigOptions); + const current = modelOption?.type === "select" ? modelOption.currentValue : undefined; + const selected = modelSelection.model.trim(); + const isDefault = selected.length === 0 || selected === KIRO_DEFAULT_MODEL; + // Before Kiro advertises `model` the session is new, so it already runs + // Kiro's default, unless an agent switch just moved it to the agent's model. + if (isDefault && modelOption?.type !== "select" && !agentSwitched) { + return current; + } + const requested = isDefault ? yield* defaultModel : selected; + if (requested === current) { + return current; + } + yield* runtime.setConfigOption(modelOption?.id ?? KIRO_MODEL_CONFIG_ID, requested, { + allowUnlistedValue: true, + }); + return requested; +}); + +/** + * Bound on waiting for Kiro to advertise the model T3 just wrote. Kiro 2.27.0 + * sent it 40-90 ms after the write's result. + */ +const KIRO_MODEL_ADVERT_BOUND = "2 seconds"; + +/** + * Writes the thread's effort to Kiro's `effortLevel` once Kiro advertises the + * written model, since Kiro ignores the option before then and resets it on a + * model change. Levels the model doesn't offer are not sent. A rejected write + * or no advert within the bound keeps Kiro's level rather than failing the turn. + */ +const applyKiroEffort = Effect.fn("KiroAdapterV2.applyKiroEffort")(function* ( + runtime: AcpSessionRuntime.AcpSessionRuntime["Service"], + modelSelection: ModelSelection, + appliedModel: string | undefined, +) { + const requested = getModelSelectionStringOptionValue(modelSelection, "reasoningEffort"); + if (requested === undefined) return; + const advertised = yield* runtime.configOptionChanges.pipe( + Stream.filter((configOptions) => { + const modelOption = findKiroModelOption(configOptions); + return ( + appliedModel === undefined || + (modelOption?.type === "select" && modelOption.currentValue === appliedModel) + ); + }), + Stream.runHead, + Effect.timeoutOption(KIRO_MODEL_ADVERT_BOUND), + Effect.map(Option.flatten), + ); + if (Option.isNone(advertised)) { + return yield* Effect.logWarning("Kiro did not advertise the model's reasoning effort", { + waitedForWrittenModel: appliedModel !== undefined, + }); + } + const effortOption = advertised.value.find((option) => option.id === KIRO_EFFORT_CONFIG_ID); + if (effortOption?.type !== "select" || !selectValues(effortOption).includes(requested)) { + return; + } + yield* runtime.setConfigOption(KIRO_EFFORT_CONFIG_ID, requested).pipe( + Effect.catchTags({ + // `requested` is one of the levels Kiro just advertised, so it is safe to log. + AcpRequestError: (error) => + Effect.logWarning("Kiro rejected the reasoning effort", { + value: requested, + code: error.code, + }), + }), + ); +}); + +/** + * Selects the thread's Kiro agent and reports whether a switch went out. It runs + * before the model write, because switching applies the agent's own model. An + * agent the session doesn't list is skipped: Kiro would accept it and not switch. + */ +const applyKiroAgent = Effect.fn("KiroAdapterV2.applyKiroAgent")(function* ( + runtime: AcpSessionRuntime.AcpSessionRuntime["Service"], + modelSelection: ModelSelection, +) { + const requested = getModelSelectionStringOptionValue(modelSelection, KIRO_AGENT_CONFIG_ID); + if (requested === undefined) return false; + const agentOption = (yield* runtime.getConfigOptions).find( + (option) => option.id === KIRO_AGENT_CONFIG_ID, + ); + if (agentOption?.type !== "select" || agentOption.currentValue === requested) return false; + if (!selectValues(agentOption).includes(requested)) { + yield* Effect.logWarning("Kiro does not list the thread's agent", { + listedAgents: selectValues(agentOption).length, + }); + return false; + } + yield* runtime.setConfigOption(KIRO_AGENT_CONFIG_ID, requested); + return true; +}); + +const applyKiroModelSelection = + (defaultModel: Effect.Effect): NonNullable => + ({ runtime, modelSelection }) => + applyKiroAgent(runtime, modelSelection).pipe( + Effect.flatMap((agentSwitched) => + applyKiroModel(runtime, modelSelection, defaultModel, agentSwitched), + ), + Effect.tap((appliedModel) => applyKiroEffort(runtime, modelSelection, appliedModel)), + ); + +function selectValues( + option: Extract, +): ReadonlyArray { + return option.options.flatMap((entry) => + "value" in entry ? [entry.value] : entry.options.map((choice) => choice.value), + ); +} + +const isAcpRequestError = Schema.is(EffectAcpErrors.AcpRequestError); + +/** + * Evidence that Kiro started the current prompt, so Stop's `session/cancel` is + * honored: a `turn_start` info update or output only a running prompt produces. + * Kiro doesn't promise `turn_start`, so Stop gives up after KIRO_CANCEL_HOLD_BOUND. + */ +function isKiroPromptActivity(update: EffectAcpSchema.SessionUpdate): boolean { + switch (update.sessionUpdate) { + case "agent_message_chunk": + case "agent_message": + case "agent_thought_chunk": + case "agent_thought": + case "tool_call": + case "tool_call_update": + case "tool_call_content_chunk": + case "plan_update": + return true; + case "session_info_update": { + const kiro = update._meta?.kiro; + return ( + typeof kiro === "object" && kiro !== null && "kind" in kiro && kiro.kind === "turn_start" + ); + } + default: + return false; + } +} + +/** Past the 0-0.5 s window where TinBane saw cancels dropped, and the 1.5 s cancel they saw honored. */ +const KIRO_CANCEL_HOLD_BOUND = "2 seconds"; + +/** + * Kiro 2.31 fetches an Identity Center account's cloud config as a tool call + * of its own around session start (reported by @hstern), which can land inside + * the user's turn. Only the call carries this id; its updates name the call. + */ +const KIRO_CLOUD_CONFIG_TOOL_ID = "fetch_cloud_config"; + +/** Drops Kiro's cloud-config tool call and every update that follows it. */ +function makeKiroCloudConfigFilter() { + const running = new Set(); + return (notification: EffectAcpSchema.SessionNotification): boolean => { + const { update } = notification; + if ( + update.sessionUpdate !== "tool_call" && + update.sessionUpdate !== "tool_call_update" && + update.sessionUpdate !== "tool_call_content_chunk" + ) { + return false; + } + const key = `${notification.sessionId}\n${update.toolCallId}`; + const kiro = update._meta?.kiro; + const toolId = + typeof kiro === "object" && kiro !== null && "toolId" in kiro ? kiro.toolId : null; + if (toolId === KIRO_CLOUD_CONFIG_TOOL_ID) running.add(key); + else if (!running.has(key)) return false; + if ("status" in update && (update.status === "completed" || update.status === "failed")) { + running.delete(key); + } + return true; + }; +} + +const KIRO_STEERING_NOTE = "[STEERING steer-"; +const decodeKiroSteeringInfo = Schema.decodeUnknownOption( + Schema.Struct({ kiro: Schema.Struct({ kind: Schema.String }) }), +); + +/** Length of the longest end of `text` that could still grow into the steering note. */ +function steeringNotePrefixLength(text: string): number { + for (let length = Math.min(text.length, KIRO_STEERING_NOTE.length - 1); length > 0; length -= 1) { + if (KIRO_STEERING_NOTE.startsWith(text.slice(-length))) return length; + } + return 0; +} + +/** + * After an injected steer, Kiro's model ends its reply with a `[STEERING steer-…: …]` + * note meant for Kiro's own UI. This drops it from the streamed text, holding back a + * chunk end that may be the start of the note until the next chunk shows otherwise. + */ +function makeKiroSteeringNoteFilter() { + const sessions = new Map(); + return ( + notification: EffectAcpSchema.SessionNotification, + ): EffectAcpSchema.SessionNotification => { + const { update } = notification; + if (update.sessionUpdate === "session_info_update") { + const kind = Option.getOrUndefined(decodeKiroSteeringInfo(update._meta))?.kiro.kind; + if (kind === "steering_injected") { + sessions.set(notification.sessionId, { held: "", inNote: false }); + } else if (kind === "steering_cleared") sessions.delete(notification.sessionId); + return notification; + } + const state = sessions.get(notification.sessionId); + if ( + state === undefined || + update.sessionUpdate !== "agent_message_chunk" || + update.content.type !== "text" + ) { + return notification; + } + let pending = state.held + update.content.text; + let visible = ""; + state.held = ""; + while (pending.length > 0) { + if (state.inNote) { + const end = pending.indexOf("]"); + if (end < 0) break; + pending = pending.slice(end + 1); + state.inNote = false; + continue; + } + const start = pending.indexOf(KIRO_STEERING_NOTE); + if (start >= 0) { + visible += pending.slice(0, start).trimEnd(); + pending = pending.slice(start + KIRO_STEERING_NOTE.length); + state.inNote = true; + continue; + } + const held = steeringNotePrefixLength(pending); + visible += pending.slice(0, pending.length - held); + state.held = pending.slice(pending.length - held); + break; + } + return { + ...notification, + update: { ...update, content: { ...update.content, text: visible } }, + }; + }; +} + +const decodeKiroAgentSubtask = Schema.decodeUnknownOption( + Schema.Struct({ + kiro: Schema.Struct({ agentSubtaskId: Schema.String, kind: Schema.optionalKey(Schema.String) }), + }), +); +const decodeKiroSubagentInput = Schema.decodeUnknownOption( + Schema.Struct({ name: Schema.String, prompt: Schema.String }), +); + +/** + * Kiro runs sub-agents inside the parent's session: frames from an + * `invoke_sub_agent` call carry `_meta.kiro.agentSubtaskId`, and routing them + * to that id as their session gives the shared adapter the child to project. + */ +function normalizeKiroSessionUpdate( + notification: EffectAcpSchema.SessionNotification, +): EffectAcpSchema.SessionNotification { + const { update } = notification; + const subtask = decodeKiroAgentSubtask("_meta" in update ? update._meta : undefined); + return Option.isSome(subtask) && subtask.value.kiro.kind !== "agent-subtask" + ? { ...notification, sessionId: subtask.value.kiro.agentSubtaskId } + : notification; +} + +/** The `invoke_sub_agent` call; it completes with the sub-agent's final response. */ +function extractKiroSubagentUpdate(tool: AcpToolCallState): AcpAdapterV2SubagentUpdate | undefined { + const subtask = decodeKiroAgentSubtask(tool.data.meta); + if (Option.isNone(subtask) || subtask.value.kiro.kind !== "agent-subtask") return undefined; + const input = decodeKiroSubagentInput(tool.data.rawInput); + const status = + tool.status === "failed" ? "failed" : tool.status === "completed" ? "completed" : "running"; + return { + nativeTaskId: tool.toolCallId, + childSessionId: subtask.value.kiro.agentSubtaskId, + prompt: Option.isSome(input) ? input.value.prompt : (tool.title ?? "Kiro sub-agent"), + title: Option.isSome(input) ? input.value.name : null, + model: null, + status, + result: typeof tool.data.rawOutput === "string" ? tool.data.rawOutput : null, + }; +} + +/** + * Kiro's prompt errors carry a message meant for the user (live 2.27: -32000 + * "The model 'x' is not available. Please select a different model and try + * again. (Request ID: …)"). Show it instead of the generic failure text; + * makeProviderFailure bounds and redacts it. + */ +function kiroPromptFailure(cause: unknown) { + return makeProviderFailure({ + cause, + ...(isAcpRequestError(cause) ? { message: cause.errorMessage, code: String(cause.code) } : {}), + class: "provider_error", + }); +} + +function makeKiroAcpAdapterFlavor(options: KiroAdapterV2Options): AcpAdapterV2Flavor { + const makeRuntime = + options.makeRuntime ?? + ((input: AcpAdapterV2RuntimeInput) => { + const { runtimePolicy: _runtimePolicy, processEnvironment, ...runtimeInput } = input; + return makeKiroAcpRuntime({ + ...runtimeInput, + settings: options.settings, + environment: { ...options.environment, ...processEnvironment }, + }); + }); + const stripSteeringNote = makeKiroSteeringNoteFilter(); + return { + driver: KIRO_PROVIDER, + runtimeHarness: "Kiro", + capabilities: KiroProviderCapabilitiesV2, + // Kiro V3 loads the user's hooks only when the client opts in. `v2` makes + // Kiro run them itself; `enabled` alone hands them to the client as + // `_kiro/hooks/*` requests, which T3 does not answer. + clientCapabilitiesMeta: { kiro: { hooks: { enabled: true, v2: true } } }, + makeRuntime, + promptFailure: kiroPromptFailure, + ignoreSessionUpdate: makeKiroCloudConfigFilter(), + normalizeSessionUpdate: (notification) => + stripSteeringNote(normalizeKiroSessionUpdate(notification)), + extractSubagentUpdate: extractKiroSubagentUpdate, + // See applyKiroModelSelection: `model` arrives after session/new. + modelOptionArrivesLate: true, + applyModelSelection: applyKiroModelSelection( + options.defaultModel ?? Effect.succeed(KIRO_FALLBACK_DEFAULT_MODEL), + ), + // The generic option loop runs after the model write, and an agent write + // there would put the agent's own model back. + ownedModelOptionIds: ["reasoningEffort", KIRO_AGENT_CONFIG_ID], + // With Autopilot off (Supervised) Kiro asks the user to accept a turn's + // changes before it ends. T3's runtime policy answers its per-tool prompts + // either way, and a runtime-mode change reopens the session to reapply it. + sessionConfigForPolicy: (policy) => [ + { id: KIRO_AUTOPILOT_CONFIG_ID, value: kiroAutopilotValue(policy) }, + ], + // See isKiroPromptActivity: Kiro 2.27.1 can drop a cancel sent just after + // `session/prompt` and run the turn to completion. + cancelAfterPromptStarts: { isStart: isKiroPromptActivity, bound: KIRO_CANCEL_HOLD_BOUND }, + permissionDisposition: kiroPermissionDisposition, + approvalOptions: kiroApprovalOptions, + compactSession: compactKiroSession, + steering: kiroSteering, + forkFromTurn: kiroForkFromTurn, + // Kiro V3 advertises `promptCapabilities.image`; the shared adapter reads it. + ...(options.assertComplete === undefined ? {} : { assertComplete: options.assertComplete }), + }; +} + +export const makeKiroAdapterV2 = Effect.fn("makeKiroAdapterV2")(function* ( + options: KiroAdapterV2Options, +) { + return yield* makeAcpAdapterV2({ + instanceId: options.instanceId, + flavor: makeKiroAcpAdapterFlavor(options), + selfInvocation: options.selfInvocation, + ...(options.nativeLogging === undefined ? {} : { nativeLogging: options.nativeLogging }), + ...(options.testHooks === undefined ? {} : { testHooks: options.testHooks }), + }); +}); + +export type KiroAdapterV2DriverEnv = + | ChildProcessSpawner.ChildProcessSpawner + | SecureRandom.SecureRandom + | FileSystem.FileSystem + | IdAllocator.IdAllocatorV2 + | Path.Path + | McpProviderSessions.McpProviderSessions + | ProviderEventLoggers.ProviderEventLoggers + | ProviderHost.ProviderHost; + +/** `defaultModel` reads Kiro's id for "Kiro default" from the provider snapshot. */ +export const makeKiroAdapterV2Driver = ( + defaultModel: Effect.Effect, +): ProviderAdapterDriver => ({ + driverKind: KIRO_PROVIDER, + configSchema: KiroSettings, + defaultConfig: (): KiroSettings => DEFAULT_KIRO_SETTINGS, + create: Effect.fn("KiroAdapterV2Driver.create")( + function* (input: ProviderAdapterDriverCreateInput) { + const hostEnvironment = yield* HostProcess.Environment; + const selfInvocation = yield* resolveSelfInvocation(); + const providerEventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers; + const makeNativeLogger = yield* makeAcpNativeLoggerFactory(); + return yield* makeKiroAdapterV2({ + instanceId: input.instanceId, + settings: { ...input.config, enabled: input.enabled }, + environment: yield* mergeProviderInstanceEnvironment(input.environment, hostEnvironment), + selfInvocation, + defaultModel, + nativeLogging: (threadId) => + makeNativeLogger({ + nativeEventLogger: providerEventLoggers.native, + provider: KIRO_PROVIDER, + threadId, + }), + }); + }, + (effect, input) => + effect.pipe( + Effect.mapError( + (cause) => + new ProviderAdapterDriverCreateError({ + driver: KIRO_PROVIDER, + instanceId: input.instanceId, + detail: "Failed to create Kiro ACP adapter.", + cause, + }), + ), + ), + ), +}); diff --git a/packages/provider-kiro/src/server/driver.test.ts b/packages/provider-kiro/src/server/driver.test.ts new file mode 100644 index 0000000000000..0df02740941d5 --- /dev/null +++ b/packages/provider-kiro/src/server/driver.test.ts @@ -0,0 +1,66 @@ +import { assert, describe, it } from "@effect/vitest"; +import * as Schema from "effect/Schema"; + +import { KiroSettings } from "../settings.ts"; +import { buildKiroAcpSpawnInput } from "./acpSupport.ts"; +import { kiroAuthFromWhoami } from "./status.ts"; + +const decodeSettings = Schema.decodeUnknownSync(KiroSettings); + +describe("KiroDriver", () => { + it("launches the V3 ACP engine with CLI-owned auth from the configured binary", () => { + assert.deepEqual(buildKiroAcpSpawnInput(decodeSettings({}), "/work"), { + command: "kiro-cli", + args: ["acp", "--agent-engine=v3", "--auth-method=cli"], + cwd: "/work", + }); + const custom = buildKiroAcpSpawnInput( + decodeSettings({ binaryPath: "/opt/kiro/bin/kiro-cli" }), + "/work", + { KIRO_API_KEY: "ksk_test" }, + ); + assert.equal(custom.command, "/opt/kiro/bin/kiro-cli"); + assert.deepEqual(custom.args, ["acp", "--agent-engine=v3", "--auth-method=cli"]); + assert.deepEqual(custom.env, { KIRO_API_KEY: "ksk_test" }); + }); + + // Outputs recorded from `kiro-cli whoami --format json` on Kiro CLI 2.27.0. + it("reads the sign-in state from kiro-cli whoami", () => { + assert.deepEqual(kiroAuthFromWhoami({ code: 1, stdout: '{"account":null}\n' }, {}), { + status: "unauthenticated", + }); + assert.deepEqual( + kiroAuthFromWhoami({ code: 0, stdout: '{"accountType":"ApiKey","email":null}\n' }, {}), + { status: "authenticated", type: "api_key", label: "Kiro API key" }, + ); + assert.deepEqual( + kiroAuthFromWhoami( + { code: 0, stdout: '{"accountType":"BuilderId","email":"dev@example.com"}\n' }, + {}, + ), + { status: "authenticated", label: "Kiro account", email: "dev@example.com" }, + ); + assert.deepEqual(kiroAuthFromWhoami({ code: 2, stdout: "error: service error" }, {}), { + status: "unknown", + }); + assert.deepEqual(kiroAuthFromWhoami(undefined, {}), { status: "unknown" }); + }); + + // Reported from Kiro CLI 2.27.1 with an IAM Identity Center login (exit 0; + // values are placeholders, layout unchanged). + it("keeps the account email when whoami appends an Identity Center profile", () => { + const stdout = [ + '{"accountType":"IamIdentityCenter","email":"jane.doe@example.com","region":"us-east-1","startUrl":"https://d-0123456789.awsapps.com/start"}', + "", + "Profile:", + "KiroProfile-us-east-1", + "arn:aws:codewhisperer:us-east-1:111122223333:profile/EXAMPLE12345", + "", + ].join("\n"); + assert.deepEqual(kiroAuthFromWhoami({ code: 0, stdout }, {}), { + status: "authenticated", + label: "Kiro account", + email: "jane.doe@example.com", + }); + }); +}); diff --git a/packages/provider-kiro/src/server/driver.ts b/packages/provider-kiro/src/server/driver.ts new file mode 100644 index 0000000000000..b0cfaa0248ec0 --- /dev/null +++ b/packages/provider-kiro/src/server/driver.ts @@ -0,0 +1,154 @@ +import { ProviderDriverKind, TextGenerationError } from "@t3tools/contracts"; +import { KiroSettings } from "../settings.ts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; + +import type * as ProviderHost from "@t3tools/provider-core/server/ProviderHost"; +import { + defaultProviderContinuationIdentity, + type ProviderDriver, + type ProviderInstance, +} from "@t3tools/provider-core/server/driver"; +import { ProviderDriverError } from "@t3tools/provider-core/server/errors"; +import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment"; +import { withInstanceIdentity } from "@t3tools/provider-core/server/instanceIdentity"; +import { makeManualOnlyProviderMaintenanceCapabilities } from "@t3tools/provider-core/server/maintenanceResolver"; +import { makeManagedServerProvider } from "@t3tools/provider-core/server/managedProvider"; +import { + haveProviderSnapshotSettingsChanged, + makeProviderSnapshotSettingsSource, + type ProviderSnapshotSettings, +} from "@t3tools/provider-core/server/snapshotSettings"; +import type { ProviderTextGeneration } from "@t3tools/provider-core/server/textGeneration"; +import { type KiroAdapterV2DriverEnv, makeKiroAdapterV2Driver } from "./adapter.ts"; +import { + buildInitialKiroProviderSnapshot, + checkKiroProviderStatus, + kiroDefaultModelId, +} from "./status.ts"; + +const DRIVER_KIND = ProviderDriverKind.make("kiro"); +const decodeKiroSettings = Schema.decodeSync(KiroSettings); +// Kiro updates itself in the background (`kiro-cli update` reports only), so +// T3 offers no one-click update. +const MAINTENANCE = makeManualOnlyProviderMaintenanceCapabilities({ + provider: DRIVER_KIND, + packageName: null, +}); + +const unsupportedTextGeneration: ProviderTextGeneration = (() => { + const unsupported = (operation: string) => + Effect.fail( + new TextGenerationError({ + operation, + detail: "Kiro does not provide application text generation.", + }), + ); + return { + generateCommitMessage: () => unsupported("generateCommitMessage"), + generatePrContent: () => unsupported("generatePrContent"), + generateBranchName: () => unsupported("generateBranchName"), + generateThreadTitle: () => unsupported("generateThreadTitle"), + generateReviewGuide: () => unsupported("generateReviewGuide"), + }; +})(); + +export type KiroDriverEnv = + | KiroAdapterV2DriverEnv + | ChildProcessSpawner.ChildProcessSpawner + | SecureRandom.SecureRandom + | ProviderHost.ProviderHost; + +export const KiroDriver: ProviderDriver = { + driverKind: DRIVER_KIND, + metadata: { + displayName: "Kiro", + supportsMultipleInstances: true, + }, + configSchema: KiroSettings, + defaultConfig: (): KiroSettings => decodeKiroSettings({}), + create: Effect.fn("KiroDriver.create")(function* ({ + instanceId, + displayName, + accentColor, + environment, + enabled, + config, + }) { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const crypto = yield* SecureRandom.SecureRandom; + const processEnv = yield* mergeProviderInstanceEnvironment( + environment, + yield* HostProcess.Environment, + ); + const continuationIdentity = defaultProviderContinuationIdentity({ + driverKind: DRIVER_KIND, + instanceId, + }); + const stampIdentity = withInstanceIdentity({ + instanceId, + driverKind: DRIVER_KIND, + displayName, + accentColor, + continuationGroupKey: continuationIdentity.continuationKey, + }); + const effectiveConfig = { ...config, enabled } satisfies KiroSettings; + const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig); + const snapshot = yield* makeManagedServerProvider>({ + resolveMaintenance: () => Effect.succeed(MAINTENANCE), + getSettings: snapshotSettings.getSettings, + streamSettings: snapshotSettings.streamSettings, + haveSettingsChanged: haveProviderSnapshotSettingsChanged, + initialSnapshot: (settings) => + buildInitialKiroProviderSnapshot(settings.provider).pipe(Effect.map(stampIdentity)), + checkProvider: checkKiroProviderStatus(effectiveConfig, processEnv).pipe( + Effect.map(stampIdentity), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.provideService(SecureRandom.SecureRandom, crypto), + ), + }).pipe( + Effect.mapError( + (cause) => + new ProviderDriverError({ + driver: DRIVER_KIND, + instanceId, + // The cause keeps the failure; the detail reaches the snapshot, so it stays fixed. + detail: "Failed to build Kiro snapshot.", + cause, + }), + ), + ); + + // "Kiro default" selects the default the snapshot read from Kiro's model list. + const orchestrationAdapter = yield* makeKiroAdapterV2Driver( + snapshot.getSnapshot.pipe(Effect.map((current) => kiroDefaultModelId(current.models))), + ) + .create({ instanceId, displayName, accentColor, environment, enabled, config }) + .pipe( + Effect.mapError( + (cause) => + new ProviderDriverError({ + driver: DRIVER_KIND, + instanceId, + detail: "Failed to build Kiro orchestration adapter.", + cause, + }), + ), + ); + + return { + instanceId, + driverKind: DRIVER_KIND, + continuationIdentity, + displayName, + accentColor, + enabled, + snapshot, + orchestrationAdapter, + textGeneration: unsupportedTextGeneration, + } satisfies ProviderInstance; + }), +}; diff --git a/packages/provider-kiro/src/server/status.ts b/packages/provider-kiro/src/server/status.ts new file mode 100644 index 0000000000000..39eed259b4be9 --- /dev/null +++ b/packages/provider-kiro/src/server/status.ts @@ -0,0 +1,458 @@ +import { + type ModelCapabilities, + ProviderDriverKind, + type ProviderOptionDescriptor, + type ServerProviderAuth, + type ServerProviderModel, +} from "@t3tools/contracts"; +import type { KiroSettings } from "../settings.ts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { createModelCapabilities } from "@t3tools/shared/model"; +import { resolveSpawnCommand } from "@t3tools/shared/shell"; +import type * as SecureRandom from "effect/crypto/SecureRandom"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Result from "effect/Result"; +import * as Schema from "effect/Schema"; +import { ChildProcess, type ChildProcessSpawner } from "effect/process"; + +import { + KIRO_AGENT_CONFIG_ID, + KIRO_SUPPORTED_RUNTIME_MODES, + makeKiroAcpRuntime, +} from "./acpSupport.ts"; +import { + AUTH_PROBE_TIMEOUT_MS, + buildServerProvider, + COMPACT_SLASH_COMMAND, + DEFAULT_TIMEOUT_MS, + isCommandMissingCause, + parseGenericCliVersion, + buildSelectOptionDescriptor, + type ProviderProbeResult, + providerModelsFromSettings, + type ServerProviderDraft, + spawnAndCollect, +} from "@t3tools/provider-core/server/snapshotProbe"; + +const KIRO_DRIVER_KIND = ProviderDriverKind.make("kiro"); +const KIRO_PRESENTATION = { + displayName: "Kiro", + showInteractionModeToggle: false, + supportedRuntimeModes: KIRO_SUPPORTED_RUNTIME_MODES, +} as const; +const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({ optionDescriptors: [] }); +const KIRO_DEFAULT_MODEL_SLUG = "default"; +const KIRO_FALLBACK_DEFAULT_MODEL = "auto"; +const KIRO_BUILT_IN_MODELS: ReadonlyArray = [ + { + slug: KIRO_DEFAULT_MODEL_SLUG, + name: "Kiro default", + isCustom: false, + capabilities: EMPTY_CAPABILITIES, + }, +]; +const KIRO_API_KEY_ENV = "KIRO_API_KEY"; + +/** + * The agent picker is not a model trait, but the composer reads options per + * model, so every model, custom ones included, carries it. + */ +const kiroModels = ( + settings: KiroSettings, + listed: ReadonlyArray = KIRO_BUILT_IN_MODELS, + agents?: ProviderOptionDescriptor, +) => + providerModelsFromSettings(listed, settings.customModels, EMPTY_CAPABILITIES).map((model) => { + const descriptors = model.capabilities?.optionDescriptors ?? []; + return agents === undefined || descriptors.some((descriptor) => descriptor.id === agents.id) + ? model + : { + ...model, + capabilities: createModelCapabilities({ optionDescriptors: [...descriptors, agents] }), + }; + }); + +const snapshot = ( + settings: KiroSettings, + checkedAt: string, + probe: ProviderProbeResult, + listed?: ReadonlyArray, + agents?: ProviderOptionDescriptor, +) => + buildServerProvider({ + // Gives the snapshot its version advisory; Kiro runs no enrichment pass. + driver: KIRO_DRIVER_KIND, + presentation: KIRO_PRESENTATION, + enabled: settings.enabled, + checkedAt, + models: kiroModels(settings, listed, agents), + // `/compact` runs `_kiro/session/compact`; see compactKiroSession. + slashCommands: [COMPACT_SLASH_COMMAND], + probe, + }); + +export const buildInitialKiroProviderSnapshot = Effect.fn( + "KiroProvider.buildInitialKiroProviderSnapshot", +)(function* (settings: KiroSettings): Effect.fn.Return { + const now = yield* DateTime.now; + return snapshot(settings, DateTime.formatIso(now), { + installed: settings.enabled, + version: null, + status: "warning", + auth: { status: "unknown" }, + message: settings.enabled + ? "Checking Kiro CLI availability..." + : "Kiro is disabled in T3 Code settings.", + }); +}); + +const runKiroCli = Effect.fn("KiroProvider.runKiroCli")(function* ( + settings: KiroSettings, + args: ReadonlyArray, + environment: NodeJS.ProcessEnv, +) { + const command = settings.binaryPath || "kiro-cli"; + const spawnCommand = yield* resolveSpawnCommand(command, args, { env: environment }); + return yield* spawnAndCollect( + command, + ChildProcess.make(spawnCommand.command, spawnCommand.args, { + env: environment, + shell: spawnCommand.shell, + }), + ); +}); + +const KiroWhoami = Schema.fromJsonString( + Schema.Struct({ + accountType: Schema.optional(Schema.NullOr(Schema.String)), + email: Schema.optional(Schema.NullOr(Schema.String)), + }), +); +const decodeKiroWhoami = Schema.decodeUnknownOption(KiroWhoami); + +/** + * Reads `kiro-cli whoami --format json`: `{"account":null}` with exit 1 means + * signed out. Only the first line is decoded, since an Identity Center login + * follows it with a plain-text `Profile:` block. + */ +export function kiroAuthFromWhoami( + output: { readonly code: number; readonly stdout: string } | undefined, + environment: NodeJS.ProcessEnv, +): ServerProviderAuth { + if (output === undefined) return { status: "unknown" }; + if (output.code !== 0) { + return output.stdout.includes('"account":null') + ? { status: "unauthenticated" } + : { status: "unknown" }; + } + const firstLine = output.stdout.trimStart().split("\n", 1)[0] ?? ""; + const account = Option.getOrUndefined(decodeKiroWhoami(firstLine.trim())); + if (account?.accountType === "ApiKey" || environment[KIRO_API_KEY_ENV]?.trim()) { + return { status: "authenticated", type: "api_key", label: "Kiro API key" }; + } + return { + status: "authenticated", + label: "Kiro account", + ...(account?.email ? { email: account.email } : {}), + }; +} + +const CLAUDE_EFFORT_LEVELS = ["low", "medium", "high", "xhigh", "max"]; +const CLAUDE_4_6_EFFORT_LEVELS = ["low", "medium", "high", "max"]; +const GPT_5_6_EFFORT_LEVELS = ["none", ...CLAUDE_EFFORT_LEVELS]; +const KIMI_K3_EFFORT_LEVELS = ["low", "high", "max"]; + +/** + * Reasoning levels per Kiro model id and its default level, copied from what + * Kiro 2.32.0 advertises, since `--list-models` names none. Unlisted models take + * no effort; the adapter sends only a level the live session offers. + */ +const KIRO_MODEL_EFFORT: Readonly< + Record; readonly defaultLevel: string }> +> = { + "claude-fable-5.1": { levels: CLAUDE_EFFORT_LEVELS, defaultLevel: "high" }, + "claude-opus-5.5": { levels: CLAUDE_EFFORT_LEVELS, defaultLevel: "medium" }, + "claude-opus-5": { levels: CLAUDE_EFFORT_LEVELS, defaultLevel: "high" }, + "claude-opus-4.8": { levels: CLAUDE_EFFORT_LEVELS, defaultLevel: "high" }, + "claude-opus-4.7": { levels: CLAUDE_EFFORT_LEVELS, defaultLevel: "xhigh" }, + "claude-opus-4.6": { levels: CLAUDE_4_6_EFFORT_LEVELS, defaultLevel: "high" }, + "claude-sonnet-5.5": { levels: CLAUDE_EFFORT_LEVELS, defaultLevel: "high" }, + "claude-sonnet-5": { levels: CLAUDE_EFFORT_LEVELS, defaultLevel: "high" }, + "claude-sonnet-4.6": { levels: CLAUDE_4_6_EFFORT_LEVELS, defaultLevel: "high" }, + "gpt-5.6-sol": { levels: GPT_5_6_EFFORT_LEVELS, defaultLevel: "high" }, + "gpt-5.6-terra": { levels: GPT_5_6_EFFORT_LEVELS, defaultLevel: "high" }, + "gpt-5.6-luna": { levels: GPT_5_6_EFFORT_LEVELS, defaultLevel: "high" }, + "kimi-k3": { levels: KIMI_K3_EFFORT_LEVELS, defaultLevel: "max" }, +}; +const KIRO_EFFORT_LABELS: Readonly> = { + none: "None", + low: "Low", + medium: "Medium", + high: "High", + xhigh: "Extra High", + max: "Max", +}; + +function kiroModelCapabilities(modelId: string): ModelCapabilities { + const effort = KIRO_MODEL_EFFORT[modelId]; + if (effort === undefined) return EMPTY_CAPABILITIES; + return createModelCapabilities({ + optionDescriptors: [ + buildSelectOptionDescriptor({ + id: "reasoningEffort", + label: "Reasoning", + options: effort.levels.map((level) => ({ + value: level, + label: KIRO_EFFORT_LABELS[level] ?? level, + isDefault: level === effort.defaultLevel, + })), + }), + ], + }); +} + +const KiroModelList = Schema.fromJsonString( + Schema.Struct({ + models: Schema.Array( + Schema.Struct({ + model_id: Schema.String, + model_name: Schema.optional(Schema.String), + }), + ), + default_model: Schema.optional(Schema.String), + }), +); +const decodeKiroModelList = Schema.decodeUnknownOption(KiroModelList); + +/** + * Reads `kiro-cli chat --list-models --format json`, the account's models. The + * default entry keeps its name but takes the "default" slug, with Kiro's id as its + * alias. Sessions advertise models only after they start; anything unparsable + * keeps the built-in list. + */ +function kiroModelsFromList( + output: { readonly code: number; readonly stdout: string } | undefined, +): ReadonlyArray | undefined { + if (output === undefined || output.code !== 0) return undefined; + const list = Option.getOrUndefined(decodeKiroModelList(output.stdout.trim())); + if (list === undefined || list.models.length === 0) return undefined; + const defaultId = list.default_model ?? KIRO_FALLBACK_DEFAULT_MODEL; + const listedDefault = list.models.find((model) => model.model_id === defaultId); + const defaultModel: ServerProviderModel = { + slug: KIRO_DEFAULT_MODEL_SLUG, + // Named after the model it runs, so a named default isn't hidden behind "Kiro default". + name: listedDefault ? (listedDefault.model_name ?? listedDefault.model_id) : "Kiro default", + aliases: [defaultId], + isCustom: false, + isDefault: true, + // A new session on Kiro's default gets no model write, so Kiro never + // advertises its effort option and a level could not be applied. + capabilities: EMPTY_CAPABILITIES, + }; + const models = list.models.map((model) => + model === listedDefault + ? defaultModel + : { + slug: model.model_id, + name: model.model_name ?? model.model_id, + isCustom: false, + capabilities: kiroModelCapabilities(model.model_id), + }, + ); + // New threads select "default", so it is listed even when Kiro's list leaves its default out. + return models.includes(defaultModel) ? models : [defaultModel, ...models]; +} + +/** + * Kiro's own id for "Kiro default": the alias the model list gave it, else + * `auto`, Kiro's documented default. + */ +export function kiroDefaultModelId(models: ReadonlyArray): string { + return ( + models.find((model) => model.slug === KIRO_DEFAULT_MODEL_SLUG)?.aliases?.[0] ?? + KIRO_FALLBACK_DEFAULT_MODEL + ); +} + +const KiroConfigTemplate = Schema.Struct({ + configOptions: Schema.Array( + Schema.Struct({ + id: Schema.String, + type: Schema.String, + currentValue: Schema.optional(Schema.Unknown), + options: Schema.optional( + Schema.Array( + Schema.Struct({ + value: Schema.String, + name: Schema.String, + description: Schema.optional(Schema.NullOr(Schema.String)), + }), + ), + ), + }), + ), +}); +const decodeKiroConfigTemplate = Schema.decodeUnknownOption(KiroConfigTemplate); + +/** + * The thread's agent picker, from Kiro's `_kiro/config/template` result, without + * opening a session. The template reads no workspace, so a project's + * `.kiro/agents` are not offered. + */ +export function kiroAgentDescriptor(template: unknown): ProviderOptionDescriptor | undefined { + const decoded = Option.getOrUndefined(decodeKiroConfigTemplate(template)); + const mode = decoded?.configOptions.find( + (option) => option.id === KIRO_AGENT_CONFIG_ID && option.type === "select", + ); + const defaultAgent = typeof mode?.currentValue === "string" ? mode.currentValue : undefined; + const choices = (mode?.options ?? []).flatMap((choice) => { + const id = choice.value.trim(); + const label = choice.name.trim() || id; + const description = choice.description?.trim(); + return id.length === 0 + ? [] + : [ + { + id, + label, + ...(description ? { description } : {}), + ...(id === defaultAgent ? { isDefault: true } : {}), + }, + ]; + }); + // One agent is nothing to choose between. + if (choices.length < 2) return undefined; + return { + id: KIRO_AGENT_CONFIG_ID, + label: "Agent", + type: "select", + options: choices, + ...(defaultAgent !== undefined && choices.some((choice) => choice.isDefault) + ? { currentValue: defaultAgent } + : {}), + }; +} + +/** + * Asks Kiro for its agents with `initialize` and `_kiro/config/template` and + * nothing more: no `session/new`, so no MCP server starts and no session is + * stored. The process runs in the server's working directory. + */ +const probeKiroAgents = Effect.fn("KiroProvider.probeKiroAgents")(function* ( + settings: KiroSettings, + environment: NodeJS.ProcessEnv, +) { + const runtime = yield* makeKiroAcpRuntime({ + settings, + environment, + cwd: yield* HostProcess.WorkingDirectory, + clientInfo: { name: "t3-code-provider-probe", version: "0.0.0" }, + }); + yield* runtime.initialize(); + return kiroAgentDescriptor(yield* runtime.request("_kiro/config/template", {})); +}, Effect.scoped); + +export const checkKiroProviderStatus = Effect.fn("checkKiroProviderStatus")(function* ( + settings: KiroSettings, + environment: NodeJS.ProcessEnv, +): Effect.fn.Return< + ServerProviderDraft, + never, + ChildProcessSpawner.ChildProcessSpawner | SecureRandom.SecureRandom +> { + const checkedAt = DateTime.formatIso(yield* DateTime.now); + if (!settings.enabled) { + return snapshot(settings, checkedAt, { + installed: false, + version: null, + status: "warning", + auth: { status: "unknown" }, + message: "Kiro is disabled in T3 Code settings.", + }); + } + + const versionResult = yield* runKiroCli(settings, ["--version"], environment).pipe( + Effect.timeoutOption(DEFAULT_TIMEOUT_MS), + Effect.result, + ); + if (Result.isFailure(versionResult) || Option.isNone(versionResult.success)) { + const missing = Result.isFailure(versionResult) && isCommandMissingCause(versionResult.failure); + return snapshot(settings, checkedAt, { + installed: !missing, + version: null, + status: "error", + auth: { status: "unknown" }, + message: missing + ? "Kiro CLI (`kiro-cli`) is not installed or not on PATH." + : "Failed to run `kiro-cli --version`.", + }); + } + const versionOutput = versionResult.success.value; + const version = parseGenericCliVersion(`${versionOutput.stdout}\n${versionOutput.stderr}`); + if (versionOutput.code !== 0) { + return snapshot(settings, checkedAt, { + installed: true, + version, + status: "error", + auth: { status: "unknown" }, + message: "Kiro CLI is installed but failed to run.", + }); + } + + const whoamiResult = yield* runKiroCli( + settings, + ["whoami", "--format", "json"], + environment, + ).pipe(Effect.timeoutOption(AUTH_PROBE_TIMEOUT_MS), Effect.result); + const auth = kiroAuthFromWhoami( + Result.isSuccess(whoamiResult) ? Option.getOrUndefined(whoamiResult.success) : undefined, + environment, + ); + if (auth.status === "unauthenticated") { + return snapshot(settings, checkedAt, { + installed: true, + version, + status: "error", + auth, + message: "Kiro CLI is installed but not signed in. Run `kiro-cli login`.", + }); + } + // Signed out, `--list-models` starts a browser login instead, and the agent + // probe fails to start, so both run only once `whoami` has confirmed the + // account. Without an agent list the composer shows no agent picker. + const [listed, agents] = + auth.status === "authenticated" + ? yield* Effect.all( + [ + runKiroCli(settings, ["chat", "--list-models", "--format", "json"], environment).pipe( + Effect.timeoutOption(AUTH_PROBE_TIMEOUT_MS), + Effect.map((output) => kiroModelsFromList(Option.getOrUndefined(output))), + Effect.orElseSucceed(() => undefined), + ), + probeKiroAgents(settings, environment).pipe( + Effect.timeoutOption(AUTH_PROBE_TIMEOUT_MS), + Effect.map(Option.getOrUndefined), + Effect.orElseSucceed(() => undefined), + ), + ], + { concurrency: "unbounded" }, + ) + : [undefined, undefined]; + return snapshot( + settings, + checkedAt, + { + installed: true, + version, + status: auth.status === "authenticated" ? "ready" : "warning", + auth, + ...(auth.status === "authenticated" + ? {} + : { message: "Could not confirm the Kiro sign-in. Run `kiro-cli whoami` to check." }), + }, + listed, + agents, + ); +}); diff --git a/packages/provider-kiro/src/settings.ts b/packages/provider-kiro/src/settings.ts new file mode 100644 index 0000000000000..4ae61a3910907 --- /dev/null +++ b/packages/provider-kiro/src/settings.ts @@ -0,0 +1,32 @@ +import { + CustomModelSetting, + makeBinaryPathSetting, + makeProviderSettingsSchema, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +export const KiroSettings = makeProviderSettingsSchema( + { + // Off by default like Grok: users opt in from Settings. + enabled: Schema.Boolean.pipe( + Schema.withDecodingDefault(Effect.succeed(false)), + Schema.annotateKey({ providerSettingsForm: { hidden: true } }), + ), + binaryPath: makeBinaryPathSetting("kiro-cli").pipe( + Schema.annotateKey({ + title: "Binary path", + description: "Path to the Kiro CLI binary.", + providerSettingsForm: { placeholder: "kiro-cli", clearWhenEmpty: "omit" }, + }), + ), + customModels: Schema.Array(CustomModelSetting).pipe( + Schema.withDecodingDefault(Effect.succeed([])), + Schema.annotateKey({ providerSettingsForm: { hidden: true } }), + ), + }, + { + order: ["binaryPath"], + }, +); +export type KiroSettings = typeof KiroSettings.Type; diff --git a/packages/provider-kiro/src/testing.ts b/packages/provider-kiro/src/testing.ts new file mode 100644 index 0000000000000..3f18a713ad8c3 --- /dev/null +++ b/packages/provider-kiro/src/testing.ts @@ -0,0 +1,12 @@ +export { KIRO_PROVIDER, makeKiroAdapterV2, type KiroAdapterV2Options } from "./server/adapter.ts"; +export { + kiroApprovalOptions, + kiroAutopilotValue, + kiroPermissionDisposition, + makeKiroAcpRuntime, +} from "./server/acpSupport.ts"; +export { + checkKiroProviderStatus, + kiroAgentDescriptor, + kiroDefaultModelId, +} from "./server/status.ts"; diff --git a/packages/provider-kiro/tsconfig.json b/packages/provider-kiro/tsconfig.json new file mode 100644 index 0000000000000..374bac55202dd --- /dev/null +++ b/packages/provider-kiro/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "types": ["node"] + }, + "include": ["src"] +} diff --git a/packages/provider-opencode/src/server/driver.test.ts b/packages/provider-opencode/src/server/driver.test.ts index fe0826e7a0026..71ab041def471 100644 --- a/packages/provider-opencode/src/server/driver.test.ts +++ b/packages/provider-opencode/src/server/driver.test.ts @@ -3,6 +3,7 @@ import * as NodeFS from "node:fs"; import * as NodeOS from "node:os"; import * as NodePath from "node:path"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import { DEFAULT_SERVER_SETTINGS, ProviderInstanceId } from "@t3tools/contracts"; @@ -59,7 +60,7 @@ const layer = Layer.mergeAll( ProviderEventLoggers.NoOpProviderEventLoggers, ), Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, openCode2Runtime), -).pipe(Layer.provideMerge(NodeServices.layer)); +).pipe(Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))); const create = (config: Partial, http: HttpClient.HttpClient) => OpenCodeDriver.create({ @@ -458,7 +459,7 @@ const resolveUpdate = (generation: "v1" | "v2", binaryPath: string) => ChildProcessSpawner.ChildProcessSpawner, ChildProcessSpawner.make(() => Effect.die("resolving an update must not spawn")), ), - Effect.provide(NodeServices.layer), + Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), ); it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( @@ -540,7 +541,7 @@ const layerUpdate = Layer.mergeAll( ProviderEventLoggers.NoOpProviderEventLoggers, ), Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, changingRuntime), -).pipe(Layer.provideMerge(NodeServices.layer)); +).pipe(Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))); it.layer(layerUpdate)("OpenCodeDriver updates", (it) => { it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( diff --git a/packages/provider-opencode/src/server/driver.ts b/packages/provider-opencode/src/server/driver.ts index 95da30946e138..4f5f0f8d5b3e4 100644 --- a/packages/provider-opencode/src/server/driver.ts +++ b/packages/provider-opencode/src/server/driver.ts @@ -1,6 +1,7 @@ import { ProviderDriverKind } from "@t3tools/contracts"; import { OpenCodeSettings } from "../settings.ts"; -import * as Crypto from "effect/Crypto"; +import * as Digest from "effect/crypto/Digest"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; @@ -159,7 +160,8 @@ export type OpenCodeDriverEnv = | OpenCodeAdapterV2.OpenCodeAdapterV2DriverEnv | ProviderHost.ProviderHost | ChildProcessSpawner.ChildProcessSpawner - | Crypto.Crypto + | Digest.Digest + | SecureRandom.SecureRandom | FileSystem.FileSystem | HttpClient.HttpClient | ProviderLatestVersions.ProviderLatestVersions @@ -193,7 +195,7 @@ export const OpenCodeDriver: ProviderDriver< const openCodeRuntime = yield* OpenCodeRuntime.OpenCodeRuntime; const httpClient = yield* HttpClient.HttpClient; const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions; - const crypto = yield* Crypto.Crypto; + const digest = yield* Digest.Digest; const host = yield* ProviderHost.ProviderHost; const processEnv = yield* mergeProviderInstanceEnvironment(environment); const continuationIdentity = defaultProviderContinuationIdentity({ @@ -344,7 +346,7 @@ export const OpenCodeDriver: ProviderDriver< Effect.provideService(FileSystem.FileSystem, fileSystem), Effect.provideService(Path.Path, pathService), Effect.provideService(HttpClient.HttpClient, httpClient), - Effect.provideService(Crypto.Crypto, crypto), + Effect.provideService(Digest.Digest, digest), ); const checkProvider = Effect.all( { diff --git a/packages/provider-opencode/src/server/status.test.ts b/packages/provider-opencode/src/server/status.test.ts index b96036669b599..802f544ae6f2d 100644 --- a/packages/provider-opencode/src/server/status.test.ts +++ b/packages/provider-opencode/src/server/status.test.ts @@ -1,6 +1,7 @@ import * as NodeAssert from "node:assert/strict"; import * as NodeSqlite from "node:sqlite"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { it } from "@effect/vitest"; import * as Deferred from "effect/Deferred"; @@ -73,7 +74,7 @@ it.effect("reads Go limits with the instance's XDG credentials and preserves res ); }), ), - Effect.provide(NodeServices.layer), + Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), ); NodeAssert.equal(limits.unavailable, undefined); NodeAssert.equal( @@ -223,7 +224,7 @@ it.effect( consoleStatus === 500 ? undefined : fingerprints.get(requested.at(-1)!), ); } - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect("prefers the selected stored Go key over the auth.json key OpenCode 2 imported", () => @@ -292,7 +293,7 @@ it.effect("prefers the selected stored Go key over the auth.json key OpenCode 2 NodeAssert.equal(limits.unavailable, undefined); NodeAssert.equal(limits.windows.length, 3); } - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect("does not read local credentials for external or disabled OpenCode instances", () => @@ -312,7 +313,7 @@ it.effect("does not read local credentials for external or disabled OpenCode ins HttpClient.HttpClient, HttpClient.make(() => Effect.die("unexpected usage request")), ), - Effect.provide(NodeServices.layer), + Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), ); NodeAssert.equal(limits.unavailable?.reason, "unsupported"); } @@ -345,7 +346,7 @@ it.effect("keeps Go entitlement absence distinct from failed or malformed usage Effect.succeed(HttpClientResponse.fromWeb(request, Response.json({}, { status }))), ), ), - Effect.provide(NodeServices.layer), + Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), ); NodeAssert.equal(limits.unavailable?.reason, reason); NodeAssert.equal(limits.credentialFingerprint, undefined); @@ -477,7 +478,7 @@ beforeEach(() => { }); const layerTest = Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, OpenCodeRuntimeTestDouble).pipe( - Layer.provideMerge(NodeServices.layer), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), ); const makeOpenCodeSettings = (overrides?: Partial): OpenCodeSettings => diff --git a/packages/provider-opencode/src/server/usageLimits.ts b/packages/provider-opencode/src/server/usageLimits.ts index e691dc211f921..0f97ea36cfefa 100644 --- a/packages/provider-opencode/src/server/usageLimits.ts +++ b/packages/provider-opencode/src/server/usageLimits.ts @@ -1,7 +1,7 @@ import * as NodeSqlite from "node:sqlite"; import type { ServerProviderUsageWindow } from "@t3tools/contracts"; -import * as Crypto from "effect/Crypto"; +import * as Digest from "effect/crypto/Digest"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -164,10 +164,10 @@ export const readOpenCodeGoUsageLimits = Effect.fn("readOpenCodeGoUsageLimits")( resetsAt: DateTime.formatIso(body.usage.monthly.resetsAt), }, ]; - const crypto = yield* Crypto.Crypto; + const digest = yield* Digest.Digest; // Unkeyed hashes match across environments; random Go keys resist offline guessing. - const credentialFingerprint = yield* crypto - .digest("SHA-256", new TextEncoder().encode(`opencode-go\0${apiKey}`)) + const credentialFingerprint = yield* digest + .digest(Digest.sha256, new TextEncoder().encode(`opencode-go\0${apiKey}`)) .pipe(Effect.map(Hex.encode), Effect.orDie); return { ...makeUsageLimits({ checkedAt, windows }), diff --git a/packages/provider-opencode/src/server/v2/OpenCode2Server.test.ts b/packages/provider-opencode/src/server/v2/OpenCode2Server.test.ts index d1e9693fb67b7..dec32dc90d006 100644 --- a/packages/provider-opencode/src/server/v2/OpenCode2Server.test.ts +++ b/packages/provider-opencode/src/server/v2/OpenCode2Server.test.ts @@ -1,3 +1,4 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import * as HostProcess from "@t3tools/shared/HostProcess"; @@ -111,7 +112,7 @@ describe("OpenCode2Server error details", () => { Layer.mergeAll( OpenCode2Client.layer.pipe(Layer.provide(httpClient)), OpenCodeRuntime.layer.pipe(Layer.provide(OpenCodeServerLedger.layerTest)), - ).pipe(Layer.provideMerge(NodeServices.layer)), + ).pipe(Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ), ); @@ -213,7 +214,11 @@ describe("OpenCode2Server spawned server", () => { Layer.mergeAll( OpenCode2Client.layer, OpenCodeRuntime.layer.pipe(Layer.provide(OpenCodeServerLedger.layerTest)), - ).pipe(Layer.provideMerge(Layer.mergeAll(NodeServices.layer, FetchHttpClient.layer))), + ).pipe( + Layer.provideMerge( + Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, FetchHttpClient.layer), + ), + ), ), ), ); diff --git a/packages/provider-opencode/src/server/v2/OpenCode2Server.ts b/packages/provider-opencode/src/server/v2/OpenCode2Server.ts index c8c5dd7b70b64..57ba94d3231aa 100644 --- a/packages/provider-opencode/src/server/v2/OpenCode2Server.ts +++ b/packages/provider-opencode/src/server/v2/OpenCode2Server.ts @@ -1,7 +1,7 @@ // One OpenCode 2 process serves all directories; share it across instance threads. import type { OpenCodeClient } from "@opencode/client/effect"; import * as Context from "effect/Context"; -import * as Crypto from "effect/Crypto"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as Base64Url from "effect/encoding/Base64Url"; import * as P from "effect/Predicate"; @@ -34,8 +34,8 @@ export class OpenCode2Server extends Context.Service< * otherwise, so T3 supplies its own and keeps it in memory. */ const generatePassword = Effect.gen(function* () { - const crypto = yield* Crypto.Crypto; - const bytes = yield* crypto.randomBytes(32).pipe(Effect.orDie); + const random = yield* SecureRandom.SecureRandom; + const bytes = yield* random.randomBytes(32); return Redacted.make(Base64Url.encode(bytes), { label: "OPENCODE_PASSWORD" }); }); diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index f49de61b24690..95700d31c8361 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -40,7 +40,7 @@ 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 Digest from "effect/crypto/Digest"; import * as Effect from "effect/Effect"; import * as Hex from "effect/encoding/Hex"; import * as Exit from "effect/Exit"; @@ -355,9 +355,9 @@ const rule = (action: string, effect: Rule["effect"]): Rule => ({ action, resour 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 crypto = yield* Crypto.Crypto; + const crypto = yield* Digest.Digest; const digest = yield* crypto - .digest("SHA-256", new TextEncoder().encode(threadId)) + .digest(Digest.sha256, new TextEncoder().encode(threadId)) .pipe(Effect.orDie); return `t3-code-${Hex.encode(digest).slice(0, 16)}`; }); @@ -524,6 +524,12 @@ const wakeTurnId = (sessionId: string, attemptId: string) => `${sessionId}:wake: const isWakeTurn = (turn: OrchestrationV2ProviderTurn) => turn.nativeTurnRef?.nativeId?.includes(":wake:") === true; +// OpenCode's claude-agent reports a spent Claude plan as provider.unknown with Claude's own text. +const claudeUsageLimit = (message: string | undefined) => + message !== undefined && /^You've hit your [^\n·]*\blimit\b/.test(message) + ? { resetAt: /\bResets at (\d{4}-\d\d-\d\dT[\d:.]+Z)\.?\s*$/.exec(message)?.[1] ?? null } + : undefined; + const INTERRUPT_TIMEOUT = "10 seconds"; const INSTRUCTIONS_KEY = "t3-code"; const RECONNECT_ATTEMPTS = 5; @@ -670,10 +676,10 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr const mcpSessions = yield* McpProviderSessions.McpProviderSessions; const fileSystem = yield* FileSystem.FileSystem; const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests; - const crypto = yield* Crypto.Crypto; + const crypto = yield* Digest.Digest; const driver = OPENCODE_PROVIDER; const mcpServerNameFor = (threadId: string) => - t3McpServerName(threadId).pipe(Effect.provideService(Crypto.Crypto, crypto)); + t3McpServerName(threadId).pipe(Effect.provideService(Digest.Digest, crypto)); const borrow = Effect.gen(function* () { const lent = yield* Deferred.make< @@ -2152,14 +2158,18 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr const { type, message, status, response } = event.data.error; // OpenCode types an empty balance as provider.quota too, but it answers // that with HTTP 402 and it never resets. Usage windows and budgets are 429. + const claudeLimit = claudeUsageLimit(message); const usageLimit = - (type === "provider.quota" && status !== 402) || type === "provider.rate-limit"; + (type === "provider.quota" && status !== 402) || + type === "provider.rate-limit" || + claudeLimit !== undefined; return yield* endExecution(state, turn, { status: "failed", failure: makeProviderFailure({ message: readableProviderErrorMessage(message, status, response?.body), code: type, class: usageLimit ? "usage_limit" : "provider_error", + resetAt: claudeLimit?.resetAt ?? null, }), }); } @@ -2925,12 +2935,19 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr ); }); - // The API accepts one message type; boundaries require both user and synthetic messages. - const userMessages = (sessionId: string) => - OpenCode2Client.paginate( - { sessionID: Session.ID.make(sessionId), limit: 100 }, - client.message.list, - ).pipe( + // Rollback must validate full history before native mutation; forks only need prompts. + const userMessages = (sessionId: string, types?: ReadonlyArray<"user" | "synthetic">) => + Stream.fromIterable(types ?? [undefined]).pipe( + Stream.flatMap((type) => + OpenCode2Client.paginate( + { + sessionID: Session.ID.make(sessionId), + limit: 100, + ...(type === undefined ? {} : { type }), + }, + client.message.list, + ), + ), Stream.runCollect, Effect.map( (messages) => @@ -4008,7 +4025,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr forkInput.sourceProviderTurns ?? [], source.id, selected, - yield* userMessages(sourceId), + yield* userMessages(sourceId, ["user", "synthetic"]), ); const forked = yield* client.session.fork({ sessionID: Session.ID.make(sourceId), diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index 5c94de3040209..0fb1768b24521 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -179,7 +179,7 @@ interface FakePi { readonly closeStdout: Effect.Effect; readonly lastSpawn: () => { readonly args: ReadonlyArray; - readonly env: NodeJS.ProcessEnv; + readonly env: NonNullable; }; } @@ -316,7 +316,7 @@ const makeFakePi: Effect.Effect = Effect.gen(function* () { } }); - let lastSpawn: { readonly args: ReadonlyArray; readonly env: NodeJS.ProcessEnv } = { + let lastSpawn: ReturnType = { args: [], env: {}, }; @@ -324,7 +324,7 @@ const makeFakePi: Effect.Effect = Effect.gen(function* () { Effect.sync(() => { if (ChildProcess.isStandardCommand(command)) { lastSpawn = { - args: command.args, + args: command.args.map(String), env: command.options.env ?? {}, }; } diff --git a/packages/secret-provider-core/src/server/SecretResolver.test.ts b/packages/secret-provider-core/src/server/SecretResolver.test.ts index 573fcfa4f655a..d654a1c942267 100644 --- a/packages/secret-provider-core/src/server/SecretResolver.test.ts +++ b/packages/secret-provider-core/src/server/SecretResolver.test.ts @@ -1,3 +1,4 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; import { @@ -63,7 +64,7 @@ const resolverLayer = ( SecretResolver.layer({ drivers: [driver], secretProviders: Effect.sync(secretProviders), - }).pipe(Layer.provide(NodeServices.layer)); + }).pipe(Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))); describe("SecretResolver", () => { it.effect("reads a reference once and holds it", () => { diff --git a/packages/secret-provider-core/src/server/driver.ts b/packages/secret-provider-core/src/server/driver.ts index 85deb93d8938b..75241c96da83b 100644 --- a/packages/secret-provider-core/src/server/driver.ts +++ b/packages/secret-provider-core/src/server/driver.ts @@ -1,5 +1,5 @@ import type { SecretProviderKind } from "@t3tools/contracts"; -import type * as Crypto from "effect/Crypto"; +import type * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import type * as FileSystem from "effect/FileSystem"; import * as Schema from "effect/Schema"; @@ -11,7 +11,7 @@ import type { SecretProviderDefinition } from "../shared/definition.ts"; export type SecretProviderDriverServices = | ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem - | Crypto.Crypto; + | SecureRandom.SecureRandom; export interface SecretProviderDriver { readonly kind: SecretProviderKind; diff --git a/packages/secret-provider-onepassword/src/server/driver.ts b/packages/secret-provider-onepassword/src/server/driver.ts index abf9d6da5ed88..8d309bbbd7366 100644 --- a/packages/secret-provider-onepassword/src/server/driver.ts +++ b/packages/secret-provider-onepassword/src/server/driver.ts @@ -1,7 +1,7 @@ import { spawnAndCollect } from "@t3tools/provider-core/server/snapshotProbe"; import { defineSecretProviderDriver } from "@t3tools/secret-provider-core/server/driver"; import { resolveSpawnCommand } from "@t3tools/shared/shell"; -import * as Crypto from "effect/Crypto"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -51,7 +51,7 @@ const readTogether = Effect.fn("OnePasswordDriver.readTogether")(function* ( references: ReadonlyArray, ) { const fileSystem = yield* FileSystem.FileSystem; - const separator = `__t3-secret-${yield* (yield* Crypto.Crypto).randomUUIDv4()}__`; + const separator = `__t3-secret-${yield* (yield* SecureRandom.SecureRandom).uuidV4()}__`; const templatePath = yield* fileSystem.makeTempFileScoped({ prefix: "t3code-op-inject-" }); yield* fileSystem.writeFileString( templatePath, diff --git a/packages/shared/src/composerContextReferences.test.ts b/packages/shared/src/composerContextReferences.test.ts index 40aa4f7743be6..a12eed6a83995 100644 --- a/packages/shared/src/composerContextReferences.test.ts +++ b/packages/shared/src/composerContextReferences.test.ts @@ -59,6 +59,10 @@ describe("labels and reference links", () => { collectComposerContextReferences(`[${"x".repeat(300)}](t3-context://v1/file/ctx_1)`)[0] ?.label, ).toHaveLength(200); + expect( + collectComposerContextReferences(`[${"x".repeat(199)}😀tail](t3-context://v1/file/ctx_1)`)[0] + ?.label, + ).toBe("x".repeat(199)); }); it("collects occurrences in document order with offsets, sharing a payload", () => { @@ -221,6 +225,29 @@ describe("provider projection", () => { expect(project("a\n")).toContain("3 | a\n4 | \n"); }); + it("keeps a review excerpt's trailing blank line and whitespace", () => { + const projected = projectComposerContextForProvider({ + text: "[Comment](t3-context://v1/review-comment/ctx_r)", + records: [ + { + version: 1, + contextId: ctx("ctx_r"), + kind: "review-comment", + label: "Comment", + sectionId: "turn:1", + sectionTitle: "Turn 1", + filePath: "src/app.ts", + startIndex: 1, + endIndex: 2, + rangeLabel: "2 to 3", + text: "Insert here.", + diff: "@@ -3,1 +2,2 @@\n+two\t\n \n", + }, + ], + }); + expect(projected).toContain("diff:\n @@ -3,1 +2,2 @@\n +two\t\n \n"); + }); + it("emits no terminal lines when the captured range is inverted", () => { const projected = projectComposerContextForProvider({ text: "[log](t3-context://v1/terminal/ctx_t)", diff --git a/packages/shared/src/composerContextReferences.ts b/packages/shared/src/composerContextReferences.ts index 914d65ec760c2..33e897379619e 100644 --- a/packages/shared/src/composerContextReferences.ts +++ b/packages/shared/src/composerContextReferences.ts @@ -67,11 +67,15 @@ export function parseComposerContextHref( } export function sanitizeComposerContextLabel(label: string, kind: ComposerContextKind): string { - const cleaned = label + const normalized = label .replace(/[[\]\\\r\n]/g, " ") .replace(/\s+/g, " ") - .trim() - .slice(0, COMPOSER_CONTEXT_LABEL_MAX_CHARS); + .trim(); + let end = COMPOSER_CONTEXT_LABEL_MAX_CHARS; + const before = normalized.charCodeAt(end - 1); + const after = normalized.charCodeAt(end); + if (before >= 0xd800 && before <= 0xdbff && after >= 0xdc00 && after <= 0xdfff) end--; + const cleaned = normalized.slice(0, end); return cleaned.length > 0 ? cleaned : kind; } @@ -289,7 +293,7 @@ function formatComposerContextProviderPayload(record: KnownComposerContextRecord ]; if (record.text.trim()) lines.push("comment:", indent(record.text.trim())); if (record.diff.trim()) { - lines.push(`${record.fenceLanguage ?? "diff"}:`, indent(record.diff.trimEnd())); + lines.push(`${record.fenceLanguage ?? "diff"}:`, indent(record.diff.replace(/\n+$/, ""))); } return lines.join("\n"); } diff --git a/packages/shared/src/inlineSkills.test.ts b/packages/shared/src/inlineSkills.test.ts index 572e1fe4b80fd..ef17246a6ec76 100644 --- a/packages/shared/src/inlineSkills.test.ts +++ b/packages/shared/src/inlineSkills.test.ts @@ -20,11 +20,16 @@ describe("replaceSpokenSkills", () => { expect([...matchInlineSkills(text, skills)].map((match) => match.skill.name)).toEqual([ "review", ]); + const sentences = replaceSpokenSkills("Use the review skill. Then run tests.", skills); + expect(sentences).toBe("Use $review. Then run tests."); + expect([...matchInlineSkills(sentences, skills)].map((match) => match.skill.name)).toEqual([ + "review", + ]); }); it("matches multi-word names, split words, and small recognition slips", () => { expect(replaceSpokenSkills("potato mode skill, fix the bug", skills)).toBe( - "$poteto-mode fix the bug", + "$poteto-mode, fix the bug", ); expect(replaceSpokenSkills("run skill post plan read on it", skills)).toBe( "run $postplan-read on it", diff --git a/packages/shared/src/inlineSkills.ts b/packages/shared/src/inlineSkills.ts index d090c7e5227d8..4fd845b93f418 100644 --- a/packages/shared/src/inlineSkills.ts +++ b/packages/shared/src/inlineSkills.ts @@ -9,7 +9,7 @@ export function formatProviderSkillDisplayName( } const SKILL_TOKEN_REGEX = - /(^|\s)\p{Sc}(?![0-9][0-9_]*(?:[kKmMbBtT]|[eE][0-9]+)?(?:\s|$))(?=[a-zA-Z0-9:_-]*[a-zA-Z])([a-zA-Z0-9][a-zA-Z0-9:_-]*)(?=\s|$)/gu; + /(^|\s)\p{Sc}(?![0-9][0-9_]*(?:[kKmMbBtT]|[eE][0-9]+)?(?:\s|$))(?=[a-zA-Z0-9:_-]*[a-zA-Z])([a-zA-Z0-9][a-zA-Z0-9:_-]*)(?=\s|[.,!?;:]|$)/gu; export function* matchInlineSkills( text: string, @@ -122,7 +122,10 @@ export function replaceSpokenSkills(text: string, skills: readonly InlineSkill[] if (words[first]!.start < consumedUntil) continue; replacements.push({ start: words[first]!.start, - end: words[match.last]!.end, + end: + words[match.last]!.start + + text.slice(words[match.last]!.start, words[match.last]!.end).replace(/[^\p{L}\p{N}]+$/u, "") + .length, token: `$${match.skill.name}`, }); consumedUntil = words[match.last]!.end; diff --git a/packages/shared/src/nodeSqliteClient.ts b/packages/shared/src/nodeSqliteClient.ts index 3190afbc7928a..9531354db1939 100644 --- a/packages/shared/src/nodeSqliteClient.ts +++ b/packages/shared/src/nodeSqliteClient.ts @@ -1242,6 +1242,7 @@ const make = Effect.fn("makeWithDatabase")(function* ( ); const client = yield* Client.make({ + driver: "node:sqlite", acquirer: transactionAcquirer, borrower, compiler, diff --git a/packages/shared/src/path.test.ts b/packages/shared/src/path.test.ts index 9b0ccd8826213..1d6348852722c 100644 --- a/packages/shared/src/path.test.ts +++ b/packages/shared/src/path.test.ts @@ -106,6 +106,21 @@ describe("workspaceRelativeFilePath", () => { ["/repo/project/../other/notes.md", "/repo/project", null], ["C:\\repo\\project\\src\\..\\..\\notes.md", "C:\\repo\\project", null], ["/repo/project/docs/a/../b.md", "/repo/project", "docs/a/../b.md"], + ["/repo/a\\b.txt", "/repo", "a\\b.txt"], + ["/repo/a/b.txt", "/repo", "a/b.txt"], + ["/repo/a\\", "/repo", "a\\"], + ["/repo/..\\notes.md", "/repo", "..\\notes.md"], + ["/repo/a\\/../../notes.md", "/repo", null], + ["/repo\\project/a.txt", "/repo\\project/", "a.txt"], + ["/repo/project/a.txt", "/repo\\project", null], + ["/repo\\project/a.txt", "/repo/project", null], + ["C:\\Repo\\src\\main.ts", "c:/repo/", "src/main.ts"], + ["/C:/Repo/src/main.ts", "c:\\repo", "src/main.ts"], + ["C:\\Repo\\src\\main.ts", "/c:/repo", "src/main.ts"], + ["\\\\SERVER\\Share\\Repo\\src\\main.ts", "\\\\server\\share\\repo", "src/main.ts"], + ["\\\\SERVER\\Share\\Repo\\src\\main.ts", "//server/share/repo", "src/main.ts"], + ["//server/share/a\\b.txt", "//server/share", "a\\b.txt"], + ["\\\\server\\share\\repo\\..\\notes.md", "\\\\server\\share\\repo", null], ])("relates %s to %s", (path, workspaceRoot, relativePath) => { expect(workspaceRelativeFilePath(path, workspaceRoot)).toBe(relativePath); }); diff --git a/packages/shared/src/path.ts b/packages/shared/src/path.ts index a7cce7cb88f09..e2c3cd3117aa2 100644 --- a/packages/shared/src/path.ts +++ b/packages/shared/src/path.ts @@ -95,11 +95,17 @@ export function workspaceRelativeFilePath( workspaceRoot: string | null | undefined, ): string | null { if (!workspaceRoot) return null; - const normalizedPath = stripSlashPrefixedWindowsDrive(path.replaceAll("\\", "/")); - const normalizedRoot = stripSlashPrefixedWindowsDrive( - workspaceRoot.replaceAll("\\", "/"), + const caseInsensitive = + isWindowsAbsolutePath(stripSlashPrefixedWindowsDrive(workspaceRoot)) || + (isNetworkPath(workspaceRoot) && isUncPath(path)); + const normalizedPath = caseInsensitive + ? stripSlashPrefixedWindowsDrive(path.replaceAll("\\", "/")) + : path; + const normalizedRoot = ( + caseInsensitive + ? stripSlashPrefixedWindowsDrive(workspaceRoot.replaceAll("\\", "/")) + : workspaceRoot ).replace(/\/+$/, ""); - const caseInsensitive = isWindowsAbsolutePath(stripSlashPrefixedWindowsDrive(workspaceRoot)); const pathForCompare = caseInsensitive ? normalizedPath.toLowerCase() : normalizedPath; const rootForCompare = caseInsensitive ? normalizedRoot.toLowerCase() : normalizedRoot; if (pathForCompare.replace(/\/+$/, "") === rootForCompare) return "."; diff --git a/packages/shared/src/relayClient.test.ts b/packages/shared/src/relayClient.test.ts index d2719c9ac33ff..5319fe5596379 100644 --- a/packages/shared/src/relayClient.test.ts +++ b/packages/shared/src/relayClient.test.ts @@ -1,4 +1,5 @@ import { sha256 } from "@noble/hashes/sha2"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { describe, expect, it } from "@effect/vitest"; import * as Clock from "effect/Clock"; @@ -88,7 +89,9 @@ const writeExecutable = (filePath: string, contents = "cloudflared") => }); type RelayClientTestServices = - | Layer.Success | typeof NodeServices.layer> + | Layer.Success< + ReturnType | typeof NodeServices.layer | typeof NodeCrypto.layer + > | HttpClient.HttpClient | ChildProcessSpawner.ChildProcessSpawner; @@ -141,6 +144,7 @@ const testReleaseAsset = { const layerInstallRuntime = (platform: NodeJS.Platform) => Layer.mergeAll( NodeServices.layer, + NodeCrypto.layer, layerHttpClient(testBinary), layerSpawner([]), layerHostRuntime({ PATH: "" }, platform), @@ -178,6 +182,7 @@ describe("RelayClient", () => { Effect.provide( Layer.mergeAll( NodeServices.layer, + NodeCrypto.layer, layerHttpClient(new Uint8Array()), layerSpawner([]), layerHostRuntime({ PATH: "" }), @@ -338,6 +343,7 @@ describe("RelayClient", () => { Effect.provide( Layer.mergeAll( NodeServices.layer, + NodeCrypto.layer, layerHttpClient(new Uint8Array()), layerSpawner([]), layerHostRuntime({ PATH: "" }), @@ -396,6 +402,7 @@ describe("RelayClient", () => { Effect.provide( Layer.mergeAll( NodeServices.layer, + NodeCrypto.layer, layerHttpClient(new TextEncoder().encode("test-binary")), layerSpawner([]), layerHostRuntime({ PATH: "" }), @@ -455,6 +462,7 @@ describe("RelayClient", () => { Effect.provide( Layer.mergeAll( NodeServices.layer, + NodeCrypto.layer, layerHttpClient(new TextEncoder().encode("test-cloudflared-binary")), layerSpawner([]), layerHostRuntime(), @@ -491,6 +499,7 @@ describe("RelayClient", () => { Effect.provide( Layer.mergeAll( NodeServices.layer, + NodeCrypto.layer, layerHttpClient(new TextEncoder().encode("tampered")), layerSpawner([]), layerHostRuntime(), @@ -526,6 +535,7 @@ describe("RelayClient", () => { Effect.provide( Layer.mergeAll( NodeServices.layer, + NodeCrypto.layer, layerHttpClient(bytes), layerSpawner(commands), layerHostRuntime(), @@ -598,6 +608,7 @@ describe("RelayClient", () => { Effect.provide( Layer.mergeAll( NodeServices.layer, + NodeCrypto.layer, layerHttpClient(new Uint8Array()), layerSpawner([]), layerHostRuntime(configEnv, platform), @@ -622,6 +633,7 @@ describe("RelayClient", () => { Effect.provide( Layer.mergeAll( NodeServices.layer, + NodeCrypto.layer, layerHttpClient(new Uint8Array()), layerSpawner([], options.versions), layerHostRuntime({ PATH: "" }), diff --git a/packages/shared/src/relayClient.ts b/packages/shared/src/relayClient.ts index 4b277a1196e03..ea461340681b3 100644 --- a/packages/shared/src/relayClient.ts +++ b/packages/shared/src/relayClient.ts @@ -8,7 +8,8 @@ import type { } from "@t3tools/contracts"; import * as Config from "effect/Config"; import * as Context from "effect/Context"; -import * as Crypto from "effect/Crypto"; +import * as Digest from "effect/crypto/Digest"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Data from "effect/Data"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; @@ -249,12 +250,14 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function RelayClientShape, never, | ChildProcessSpawner.ChildProcessSpawner - | Crypto.Crypto + | SecureRandom.SecureRandom + | Digest.Digest | FileSystem.FileSystem | HttpClient.HttpClient | Path.Path > { - const crypto = yield* Crypto.Crypto; + const random = yield* SecureRandom.SecureRandom; + const digest = yield* Digest.Digest; const fileSystem = yield* FileSystem.FileSystem; const httpClient = yield* HttpClient.HttpClient; const path = yield* Path.Path; @@ -463,7 +466,7 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function ), ); yield* report("verifying"); - const checksum = yield* crypto.digest("SHA-256", bytes).pipe( + const checksum = yield* digest.digest(Digest.sha256, bytes).pipe( Effect.mapError( (cause) => new RelayClientInstallError({ @@ -497,7 +500,7 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function const acquireInstallLock = Effect.fn("cloudflared.acquireInstallLock")(function* ( lockPath: string, ) { - const owner = `${process.pid}-${yield* crypto.randomUUIDv4()}`; + const owner = `${process.pid}-${yield* random.uuidV4()}`; const candidate = yield* Effect.acquireRelease( fileSystem.makeTempDirectory({ directory: path.dirname(lockPath), prefix: ".lock-" }), (directory) => @@ -634,7 +637,7 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function }); } - const stagedPath = `${managedPath}.${yield* crypto.randomUUIDv4()}.tmp`; + const stagedPath = `${managedPath}.${yield* random.uuidV4()}.tmp`; yield* report("activating"); yield* renameWhenUnlocked(executablePath, stagedPath).pipe( wrapInstallFailure("write_failed", "Could not stage the relay client."), diff --git a/packages/source-control-core/src/server/PullRequestProvider.ts b/packages/source-control-core/src/server/PullRequestProvider.ts index a175c365d080e..3156efdd7d80f 100644 --- a/packages/source-control-core/src/server/PullRequestProvider.ts +++ b/packages/source-control-core/src/server/PullRequestProvider.ts @@ -47,6 +47,7 @@ export class PullRequestProviderError extends Schema.TaggedError { const createdAt = "2026-10-10T19:52:40Z"; @@ -34,3 +40,24 @@ describe("forgejoComment", () => { assert.strictEqual(mapped.editedAt, "2026-10-10T20:04:50.000Z"); }); }); + +describe("forgejoReview", () => { + it.each([ + ["REQUEST_CHANGES", false, "CHANGES_REQUESTED"], + ["REQUEST_CHANGES", true, "DISMISSED"], + ["APPROVED", true, "DISMISSED"], + ])("reads %s with dismissed %s as %s", (state, dismissed, reviewState) => { + const mapped = forgejoReview( + decodeForgejoReview({ + id: 8, + body: "", + user: { login: "maria" }, + state, + dismissed, + submitted_at: "2026-10-10T19:52:40Z", + comments_count: 0, + }), + ); + assert.strictEqual(mapped.reviewState, reviewState); + }); +}); diff --git a/packages/source-control-forgejo/src/server/forgejoPullRequestJson.ts b/packages/source-control-forgejo/src/server/forgejoPullRequestJson.ts index 2d9c381eb14c9..7a7daeac64f00 100644 --- a/packages/source-control-forgejo/src/server/forgejoPullRequestJson.ts +++ b/packages/source-control-forgejo/src/server/forgejoPullRequestJson.ts @@ -77,6 +77,7 @@ export const ForgejoReview = Schema.Struct({ body: Schema.String, user: Schema.NullOr(ForgejoUser), state: Schema.String, + dismissed: Schema.optional(Schema.Boolean), submitted_at: Schema.String, html_url: Schema.optional(Schema.String), comments_count: Schema.Int, @@ -173,11 +174,13 @@ export function forgejoReview(review: typeof ForgejoReview.Type): PullRequestCom url: review.html_url || null, path: null, reviewState: - review.state === "REQUEST_CHANGES" - ? "CHANGES_REQUESTED" - : review.state === "COMMENT" - ? "COMMENTED" - : review.state, + review.dismissed === true + ? "DISMISSED" + : review.state === "REQUEST_CHANGES" + ? "CHANGES_REQUESTED" + : review.state === "COMMENT" + ? "COMMENTED" + : review.state, }; } diff --git a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.test.ts b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.test.ts index 113a388e853bb..cb2bf219c0b5e 100644 --- a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.test.ts +++ b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.test.ts @@ -1103,6 +1103,8 @@ describe("GitCafePullRequestProvider", () => { const detail = yield* provider.getChangeRequest(target); assert.strictEqual(detail.state, "merged"); assert.strictEqual(detail.mergedAt, mergedAt); + const preview = yield* provider.getChangeRequestPreview!(target); + assert.strictEqual(preview.state, "merged"); }).pipe(Effect.provide(server.layer)); }); diff --git a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts index e87a4e154d69b..7f8b4bab29da6 100644 --- a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts +++ b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts @@ -897,7 +897,7 @@ export const make = Effect.gen(function* () { ), getChangeRequestPreview: (input) => readPull("getChangeRequestPreview", input).pipe( - Effect.map((pull) => Json.toChangeRequest(pull, input)), + Effect.map((pull) => ({ ...Json.toChangeRequest(pull, input), ...settledMerge(pull) })), ), getChangeRequestSummary: Effect.fn("GitCafePullRequestProvider.getChangeRequestSummary")( function* (input) { diff --git a/packages/source-control-github/scripts/measure-pr-preview.ts b/packages/source-control-github/scripts/measure-pr-preview.ts index 6f03586958cca..749fd9d53b9f4 100644 --- a/packages/source-control-github/scripts/measure-pr-preview.ts +++ b/packages/source-control-github/scripts/measure-pr-preview.ts @@ -2,6 +2,7 @@ // Real GitHub reads share repository-permission caches, excluding browser and service caches. // HTTP client request counts are exact; GraphQL cost uses changes in `x-ratelimit-used`, // which are approximate when other clients spend the same token's quota. +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit"; import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost"; @@ -97,7 +98,7 @@ const sourceControlHost = Layer.unwrap( }, }); }), -).pipe(Layer.provideMerge(NodeServices.layer)); +).pipe(Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))); const services = GitHubPullRequestApi.layer.pipe( Layer.provideMerge(GitHubAppAccess.layer), diff --git a/packages/source-control-github/src/server/GitHubCredentials.ts b/packages/source-control-github/src/server/GitHubCredentials.ts index 41641790aac52..db3aee2df2c4b 100644 --- a/packages/source-control-github/src/server/GitHubCredentials.ts +++ b/packages/source-control-github/src/server/GitHubCredentials.ts @@ -1,7 +1,7 @@ import { normalizeHost } from "@t3tools/source-control-core/server/pullRequestUtils"; import * as Cache from "effect/Cache"; import * as Context from "effect/Context"; -import * as Crypto from "effect/Crypto"; +import * as Digest from "effect/crypto/Digest"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Hex from "effect/encoding/Hex"; @@ -16,7 +16,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost"; import { readSourceControlHostSettings } from "@t3tools/source-control-core/shared/definition"; -import type { ServerSettings } from "@t3tools/contracts"; +import { settingsSecretLiteral, type ServerSettings } from "@t3tools/contracts"; import * as GitHubClient from "../shared/definition.ts"; @@ -135,12 +135,12 @@ export function environmentToken( export const make = Effect.gen(function* () { const sourceControlHost = yield* SourceControlHost.SourceControlHost; const process = sourceControlHost.process; - const crypto = yield* Crypto.Crypto; + const crypto = yield* Digest.Digest; const environment = yield* HostProcess.Environment; const workingDirectory = yield* HostProcess.WorkingDirectory; const fingerprintOf = (host: string, token: string) => - crypto.digest("SHA-256", new TextEncoder().encode(token)).pipe( + crypto.digest(Digest.sha256, new TextEncoder().encode(token)).pipe( Effect.map((digest) => `${host}:${Hex.encode(digest)}`), Effect.orDie, ); @@ -194,8 +194,10 @@ export const make = Effect.gen(function* () { ); const savedToken = (host: string) => - sourceControlHost.settings.get.pipe( - Effect.map((settings) => readSettings(settings).tokens[host]?.trim() || null), + sourceControlHost.settings.getWithSecrets(GitHubClient.definition.kind).pipe( + Effect.map( + (settings) => settingsSecretLiteral(readSettings(settings).tokens[host]).trim() || null, + ), Effect.orElseSucceed(() => null), ); diff --git a/packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts b/packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts index dc8ca69770e46..48f3021d1fe38 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts @@ -69,6 +69,44 @@ it.effect("maps credential verification failures without relabeling operation fa }), ); +it.effect.each([ + { status: 403, githubErrorTypes: [], reason: "forbidden" }, + { status: 503, githubErrorTypes: [], reason: "failed" }, + { status: 200, githubErrorTypes: ["FORBIDDEN"], reason: "forbidden" }, + { status: 200, githubErrorTypes: ["INTERNAL"], reason: "failed" }, + { status: 200, githubErrorTypes: ["FORBIDDEN", "NOT_FOUND"], reason: "forbidden" }, + { status: 200, githubErrorTypes: ["FORBIDDEN", "INTERNAL"], reason: "failed" }, + { status: 200, githubErrorTypes: ["FORBIDDEN", null], reason: "failed" }, +])("classifies GitHub response $status as $reason", ({ status, githubErrorTypes, reason }) => + Effect.gen(function* () { + const provider = yield* make.pipe( + Effect.provide( + Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({ + revalidateChecks: (_input, read) => read, + getPullRequestDetail: () => + Effect.fail( + new GitHubRequestPolicy.GitHubApiResponseError({ + host: "github.com", + operation: "detail", + status, + githubErrorTypes, + }), + ), + }), + ), + ); + const error = yield* provider + .getChangeRequest({ + cwd: "/w", + repository: "acme/web", + host: "github.com", + number: 7, + }) + .pipe(Effect.flip); + expect(error.reason).toBe(reason); + }), +); + it.effect("advertises standalone branch deletion for source repository writers", () => Effect.gen(function* () { let action: string | undefined; diff --git a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts b/packages/source-control-github/src/server/GitHubPullRequestProvider.ts index a99aa87c9652d..b998d2be735a6 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestProvider.ts @@ -120,6 +120,15 @@ function gitHubProviderFailure( }; case "SourceControlRateLimitPausedError": return { reason: "rate-limited", retryAt: error.retryAt }; + case "GitHubApiResponseError": + return { + reason: + error.status === 403 || + (error.githubErrorTypes?.includes("FORBIDDEN") && + error.githubErrorTypes.every((type) => type === "FORBIDDEN" || type === "NOT_FOUND")) + ? "forbidden" + : "failed", + }; case "GitHubApiNotFoundError": return error.credential === undefined || error.credential === "app" ? { reason: "not-found" } diff --git a/packages/source-control-github/src/server/GitHubRequestPolicy.ts b/packages/source-control-github/src/server/GitHubRequestPolicy.ts index 158a0982d96f2..0d48932db327b 100644 --- a/packages/source-control-github/src/server/GitHubRequestPolicy.ts +++ b/packages/source-control-github/src/server/GitHubRequestPolicy.ts @@ -85,6 +85,7 @@ export class GitHubApiResponseError extends Schema.TaggedError current.sourceControlHosts[GitHubClient.definition.kind]), Effect.orElseSucceed(() => undefined), ), @@ -237,7 +237,8 @@ export const makeDiscovery = Effect.gen(function* () { }, spec: { ...discovery, parseAuth: (input) => parseGitHubAuth(input, settings) }, }); - const savedToken = (settings.tokens["github.com"] ?? "").trim() !== ""; + const token = settings.tokens["github.com"]; + const savedToken = settingsSecretLiteral(token).trim() !== ""; const signedIn = appSignIn.enabled && !savedToken && (settings.signIns["github.com"] ?? "").trim() !== ""; const variable = environmentTokenVariable(environment); diff --git a/packages/source-control-github/src/server/gitHubDiscovery.test.ts b/packages/source-control-github/src/server/gitHubDiscovery.test.ts index cd8a838b23723..b108d71f75584 100644 --- a/packages/source-control-github/src/server/gitHubDiscovery.test.ts +++ b/packages/source-control-github/src/server/gitHubDiscovery.test.ts @@ -1,10 +1,14 @@ -import { SourceControlProviderKind } from "@t3tools/contracts"; +import { ServerSettings, SourceControlProviderKind } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { assert, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as Redacted from "effect/Redacted"; +import * as Schema from "effect/Schema"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost"; +import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost"; import * as GitHubCredentials from "./GitHubCredentials.ts"; import * as GitHubAppSignIn from "./GitHubAppSignIn.ts"; @@ -79,3 +83,79 @@ it.effect("asks for no credential when the identity resolver left the base URL e assert.deepStrictEqual(hosts, []); }), ); + +const decodeSettings = Schema.decodeSync(ServerSettings); +const referencedTokenSettings = decodeSettings({ + sourceControlHosts: { + github: { tokens: { "github.com": { provider: "vault", reference: "op://v/gh" } } }, + }, +}); + +it.effect.each([ + { name: "readable", token: "resolved-token", source: "the token saved in Settings" }, + { name: "unreadable", token: "", source: "GH_TOKEN from the server environment" }, +])("checks the $name GitHub token reference against the API", (scenario) => + Effect.gen(function* () { + const paths: Array = []; + const discovery = yield* GitHubSourceControlProvider.makeDiscovery.pipe( + Effect.provide( + Layer.mergeAll( + Layer.mock(GitHubRest.GitHubRest)({ + rest: (input) => { + paths.push(input.path); + return Effect.succeed({ + status: 200, + headers: {}, + body: JSON.stringify({ login: "octocat" }), + truncated: false, + invalidUtf8: false, + }); + }, + }), + Layer.mock(GitHubAppSignIn.GitHubAppSignIn)({ enabled: false }), + Layer.effect( + SourceControlHost.SourceControlHost, + Effect.gen(function* () { + const host = yield* SourceControlHost.SourceControlHost; + return { + ...host, + settings: { + ...host.settings, + getWithSecrets: () => + Effect.succeed( + decodeSettings({ + sourceControlHosts: { + github: { tokens: { "github.com": scenario.token } }, + }, + }), + ), + }, + }; + }), + ).pipe( + Layer.provide( + TestSourceControlHost.layer({ + settings: referencedTokenSettings, + process: { + run: () => + Effect.succeed( + TestSourceControlHost.processOutput("", { + exitCode: ChildProcessSpawner.ExitCode(1), + }), + ), + }, + }), + ), + ), + ), + ), + Effect.provideService(HostProcess.Environment, { GH_TOKEN: "environment-token" }), + ); + if (discovery.type !== "managed-cli") return assert.fail("expected a managed CLI"); + const item = yield* discovery.probe("/repo"); + assert.deepStrictEqual(paths, ["user"]); + assert.strictEqual(item.auth.status, "authenticated"); + assert.deepStrictEqual(item.auth.account, Option.some("octocat")); + assert.include(Option.getOrThrow(item.auth.detail), scenario.source); + }), +); diff --git a/packages/source-control-github/src/server/gitHubGraphQlClient.test.ts b/packages/source-control-github/src/server/gitHubGraphQlClient.test.ts index 667dc4f8f4c22..769a8ce65f259 100644 --- a/packages/source-control-github/src/server/gitHubGraphQlClient.test.ts +++ b/packages/source-control-github/src/server/gitHubGraphQlClient.test.ts @@ -302,6 +302,7 @@ describe("call", () => { errors: [ { type: "NOT_FOUND", message: "Could not resolve" }, { type: "FORBIDDEN", message: "Resource not accessible" }, + { message: "Unknown error" }, ], }), ); @@ -310,7 +311,8 @@ describe("call", () => { expect(error).toMatchObject({ _tag: "GitHubApiResponseError", status: 200, - githubErrors: ["Could not resolve", "Resource not accessible"], + githubErrors: ["Could not resolve", "Resource not accessible", "Unknown error"], + githubErrorTypes: ["NOT_FOUND", "FORBIDDEN", null], }); }).pipe(Effect.provide(layer)); }, diff --git a/packages/source-control-github/src/server/gitHubGraphQlClient.ts b/packages/source-control-github/src/server/gitHubGraphQlClient.ts index 7030abb1742e2..484e808b0cd49 100644 --- a/packages/source-control-github/src/server/gitHubGraphQlClient.ts +++ b/packages/source-control-github/src/server/gitHubGraphQlClient.ts @@ -248,6 +248,9 @@ const fromClientError = ( ...context, status: reason.status ?? 200, githubErrors: reason.errors.map((graphQlError) => graphQlError.message), + githubErrorTypes: reason.errors.map((graphQlError) => + typeof graphQlError["type"] === "string" ? graphQlError["type"] : null, + ), }); }; diff --git a/packages/source-control-gitlab/src/shared/definition.test.ts b/packages/source-control-gitlab/src/shared/definition.test.ts index 7f9e94fa90887..f57c6274deeb8 100644 --- a/packages/source-control-gitlab/src/shared/definition.test.ts +++ b/packages/source-control-gitlab/src/shared/definition.test.ts @@ -61,6 +61,22 @@ describe("GitLab change request URLs", () => { number: 4, }), ).toBe("https://gitlab.com/group/sub/project/-/merge_requests/4"); + expect( + definition.changeRequestUrl({ + host: "gitlab.internal", + repository: "team/app", + number: 5, + remoteUrl: "http://gitlab.internal:8080/team/app.git", + }), + ).toBe("http://gitlab.internal:8080/team/app/-/merge_requests/5"); + expect( + definition.changeRequestUrl({ + host: "gitlab.internal", + repository: "team/app", + number: 5, + remoteUrl: "git@gitlab.internal:team/app.git", + }), + ).toBe("https://gitlab.internal/team/app/-/merge_requests/5"); expect( definition.changeRequestUrl({ host: "gitlab.com", diff --git a/packages/source-control-gitlab/src/shared/definition.ts b/packages/source-control-gitlab/src/shared/definition.ts index 2d280f01c62f2..10972a3e772b8 100644 --- a/packages/source-control-gitlab/src/shared/definition.ts +++ b/packages/source-control-gitlab/src/shared/definition.ts @@ -8,6 +8,7 @@ import { parseChangeRequestPath, parseCommitPath, projectChangeRequestHost, + remoteWebOrigin, } from "@t3tools/source-control-core/shared/definition"; import { icon } from "./icon.ts"; @@ -38,10 +39,10 @@ export const definition = defineSourceControl({ publishHost: () => "gitlab.com", newRepositoryOwner: (account) => ({ owner: account }), defaultCloneTransport: "ssh", - changeRequestUrl: ({ host, repository, number, webUrl }) => + changeRequestUrl: ({ host, repository, number, remoteUrl, webUrl }) => webUrl ? changeRequestUrlBelow(webUrl, `-/merge_requests/${number}`) - : `https://${host}/${repository}/-/merge_requests/${number}`, + : `${remoteWebOrigin(host, remoteUrl)}/${repository}/-/merge_requests/${number}`, parseChangeRequestUrl: (url) => parseChangeRequestPath(url, CHANGE_REQUEST_PATH), commitUrl: (input) => buildCommitUrl(input, "-/commit"), parseCommitUrl: (url) => parseCommitPath(url, COMMIT_PATH), diff --git a/packages/ssh/src/command.test.ts b/packages/ssh/src/command.test.ts index 9503e4d0606d5..9c6d5ed79ec06 100644 --- a/packages/ssh/src/command.test.ts +++ b/packages/ssh/src/command.test.ts @@ -1,4 +1,5 @@ import { assert, describe, it } from "@effect/vitest"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -51,7 +52,7 @@ describe("ssh command", () => { it.effect("passes an option-shaped alias to ssh as the destination", () => { const spawned: Array> = []; const spawner = ChildProcessSpawner.make((command) => { - if (ChildProcess.isStandardCommand(command)) spawned.push(command.args); + if (ChildProcess.isStandardCommand(command)) spawned.push(command.args.map(String)); return Effect.succeed(makeFailedProcess({ stdout: "", stderr: "bad hostname\n" })); }); return runSshCommand( @@ -64,7 +65,7 @@ describe("ssh command", () => { }), Effect.provide( Layer.merge( - NodeServices.layer, + Layer.mergeAll(NodeServices.layer, NodeCrypto.layer), Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner), ), ), @@ -92,7 +93,7 @@ describe("ssh command", () => { }), "326264c4f08c8a0c", ); - }).pipe(Effect.provide(NodeServices.layer)), + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.live.each([ @@ -140,7 +141,7 @@ describe("ssh command", () => { ? `[truncated]\n${redacted.slice(-4_000)}` : `${redacted.slice(0, 4_000)}\n[truncated]`, ); - }).pipe(Effect.provide(NodeServices.layer)), + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.live("enables server-alive checks for long remote commands", () => @@ -160,7 +161,7 @@ describe("ssh command", () => { Effect.succeed(makeFailedProcess({ stdout: '{"credential":"pairing-secret"}\n' })), ); const layerSpawner = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner); - const layerProcess = Layer.mergeAll(NodeServices.layer, layerSpawner); + const layerProcess = Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, layerSpawner); return Effect.gen(function* () { const result = yield* Effect.result( diff --git a/packages/ssh/src/command.ts b/packages/ssh/src/command.ts index 5011eea7cd7d9..eafda87d4ff70 100644 --- a/packages/ssh/src/command.ts +++ b/packages/ssh/src/command.ts @@ -1,6 +1,6 @@ import type { DesktopSshEnvironmentTarget } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; -import * as Crypto from "effect/Crypto"; +import * as Digest from "effect/crypto/Digest"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Hex from "effect/encoding/Hex"; @@ -76,11 +76,12 @@ export function targetConnectionKey(target: DesktopSshEnvironmentTarget): string export const remoteStateKey = Effect.fn("ssh/command.remoteStateKey")(function* ( target: DesktopSshEnvironmentTarget, -): Effect.fn.Return { - const crypto = yield* Crypto.Crypto; - const digest = yield* crypto - .digest("SHA-256", encoder.encode(targetConnectionKey(target))) - .pipe(Effect.orDie); +): Effect.fn.Return { + const digestService = yield* Digest.Digest; + const digest = yield* digestService.digest( + Digest.sha256, + encoder.encode(targetConnectionKey(target)), + ); return Hex.encode(digest).slice(0, 16); }); diff --git a/packages/ssh/src/tunnel.test.ts b/packages/ssh/src/tunnel.test.ts index 6cea42d131a6d..b0ff65cba3af3 100644 --- a/packages/ssh/src/tunnel.test.ts +++ b/packages/ssh/src/tunnel.test.ts @@ -1,4 +1,5 @@ import { assert, describe, it } from "@effect/vitest"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import * as NetService from "@t3tools/shared/Net"; import * as Deferred from "effect/Deferred"; @@ -76,7 +77,7 @@ const testNetService = NetService.NetService.of({ }); function commandArgs(command: ChildProcess.Command): ReadonlyArray { - return command._tag === "StandardCommand" ? command.args : []; + return command._tag === "StandardCommand" ? command.args.map(String) : []; } const ARCHIVE = { archiveVersion: "1.2.3-preview.20260911.4" } as const; @@ -119,7 +120,10 @@ describe("ssh tunnel scripts", () => { }), ); const layerSpawner = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner); - const layerProcess = Layer.merge(NodeServices.layer, layerSpawner); + const layerProcess = Layer.merge( + Layer.mergeAll(NodeServices.layer, NodeCrypto.layer), + layerSpawner, + ); return Effect.gen(function* () { const result = yield* SshTunnel.launchOrReuseRemoteServer(target, undefined, ARCHIVE); @@ -149,7 +153,10 @@ describe("ssh tunnel scripts", () => { ), ); const layerSpawner = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner); - const layerProcess = Layer.merge(NodeServices.layer, layerSpawner); + const layerProcess = Layer.merge( + Layer.mergeAll(NodeServices.layer, NodeCrypto.layer), + layerSpawner, + ); return Effect.gen(function* () { const result = yield* SshTunnel.issueRemotePairingToken(target, undefined, ARCHIVE); assert.equal(result.credential, "LCL4R2TPHDKQ"); @@ -175,6 +182,7 @@ describe("ssh tunnel scripts", () => { ); const layer = Layer.mergeAll( NodeServices.layer, + NodeCrypto.layer, Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner), Layer.succeed(HttpClient.HttpClient, hangingHttpClient), Layer.succeed(NetService.NetService, testNetService), @@ -232,6 +240,7 @@ describe("ssh tunnel scripts", () => { ); const layer = Layer.mergeAll( NodeServices.layer, + NodeCrypto.layer, Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner), Layer.succeed(HttpClient.HttpClient, hangingHttpClient), Layer.succeed(NetService.NetService, testNetService), @@ -296,6 +305,7 @@ describe("ssh tunnel scripts", () => { ); const layer = Layer.mergeAll( NodeServices.layer, + NodeCrypto.layer, Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner), Layer.succeed(HttpClient.HttpClient, testHttpClient), Layer.succeed(NetService.NetService, testNetService), @@ -400,6 +410,7 @@ describe("ssh tunnel scripts", () => { ); const layer = Layer.mergeAll( NodeServices.layer, + NodeCrypto.layer, Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner), Layer.succeed(HttpClient.HttpClient, testHttpClient), Layer.succeed(NetService.NetService, testNetService), diff --git a/packages/ssh/src/tunnel.ts b/packages/ssh/src/tunnel.ts index d2ee6b39a9a2c..6a08b20a4256a 100644 --- a/packages/ssh/src/tunnel.ts +++ b/packages/ssh/src/tunnel.ts @@ -9,7 +9,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 Digest from "effect/crypto/Digest"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; @@ -86,7 +86,7 @@ interface SshTunnelEntry { type SshEnvironmentEffectContext = | ChildProcessSpawner.ChildProcessSpawner - | Crypto.Crypto + | Digest.Digest | FileSystem.FileSystem | Path.Path | HttpClient.HttpClient @@ -867,7 +867,7 @@ export const launchOrReuseRemoteServer = Effect.fn("ssh/tunnel.launchOrReuseRemo ): Effect.fn.Return< { readonly remotePort: number; readonly remoteServerKind: "external" | "managed" | null }, SshCommandError | SshInvalidTargetError | SshLaunchError, - ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | FileSystem.FileSystem | Path.Path + ChildProcessSpawner.ChildProcessSpawner | Digest.Digest | FileSystem.FileSystem | Path.Path > { const stateKey = yield* remoteStateKey(target); yield* Effect.logInfo("ssh.remoteServer.launch.start", { @@ -929,7 +929,7 @@ export const issueRemotePairingToken = Effect.fn("ssh/tunnel.issueRemotePairingT readonly credential: string; }, SshCommandError | SshInvalidTargetError | SshPairingError, - ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | FileSystem.FileSystem | Path.Path + ChildProcessSpawner.ChildProcessSpawner | Digest.Digest | FileSystem.FileSystem | Path.Path > { const stateKey = yield* remoteStateKey(target); yield* Effect.logDebug("ssh.remoteServer.pairingToken.start", { @@ -981,7 +981,7 @@ const stopRemoteServer = Effect.fn("ssh/tunnel.stopRemoteServer")(function* ( ): Effect.fn.Return< void, SshCommandError | SshInvalidTargetError, - ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | FileSystem.FileSystem | Path.Path + ChildProcessSpawner.ChildProcessSpawner | Digest.Digest | FileSystem.FileSystem | Path.Path > { const stateKey = yield* remoteStateKey(target); yield* Effect.logInfo("ssh.remoteServer.stop.start", { @@ -1007,7 +1007,7 @@ const readRemoteServerLogTail = Effect.fn("ssh/tunnel.readRemoteServerLogTail")( ): Effect.fn.Return< string, SshCommandError | SshInvalidTargetError, - ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | FileSystem.FileSystem | Path.Path + ChildProcessSpawner.ChildProcessSpawner | Digest.Digest | FileSystem.FileSystem | Path.Path > { const result = yield* runSshCommand(target, { remoteCommandArgs: ["sh", "-s"], @@ -1110,7 +1110,7 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input: SshTunnelEntry, SshCommandError | SshInvalidTargetError | SshReadinessError, | ChildProcessSpawner.ChildProcessSpawner - | Crypto.Crypto + | Digest.Digest | FileSystem.FileSystem | Path.Path | HttpClient.HttpClient @@ -1555,7 +1555,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 digestService = yield* Digest.Digest; const fileSystemService = yield* FileSystem.FileSystem; const pathService = yield* Path.Path; yield* Scope.addFinalizer( @@ -1595,7 +1595,7 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma }, ).pipe( Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawnerService), - Effect.provideService(Crypto.Crypto, cryptoService), + Effect.provideService(Digest.Digest, digestService), Effect.provideService(FileSystem.FileSystem, fileSystemService), Effect.provideService(Path.Path, pathService), ); @@ -1778,7 +1778,7 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma }); /** - * @effect-expect-leaking ChildProcessSpawner | Crypto | FileSystem | HttpClient | NetService | Path | SshPasswordPrompt + * @effect-expect-leaking ChildProcessSpawner | Digest | FileSystem | HttpClient | NetService | Path | SshPasswordPrompt */ export class SshEnvironmentManager extends Context.Service< SshEnvironmentManager, diff --git a/packages/tailscale/src/tailscale.test.ts b/packages/tailscale/src/tailscale.test.ts index d1b90208443a3..96f6e7721ed66 100644 --- a/packages/tailscale/src/tailscale.test.ts +++ b/packages/tailscale/src/tailscale.test.ts @@ -338,7 +338,8 @@ describe("tailscale", () => { return Effect.gen(function* () { yield* readTailscaleStatus.pipe(Effect.provide(layer)); yield* readTailscaleSshEnabled.pipe(Effect.provide(layer)); - assert.deepEqual(killGraces, [500, 500]); + yield* ensureTailscaleServe({ localPort: 45_678 }).pipe(Effect.provide(layer)); + assert.deepEqual(killGraces, [500, 500, 500]); }); }); }); diff --git a/packages/tailscale/src/tailscale.ts b/packages/tailscale/src/tailscale.ts index cb5748d21e7b0..4eb20f1150b6c 100644 --- a/packages/tailscale/src/tailscale.ts +++ b/packages/tailscale/src/tailscale.ts @@ -397,12 +397,14 @@ const runTailscaleCommand = Effect.fn("tailscale.runTailscaleCommand")(function* }; const timeout = Duration.fromInputUnsafe(timeoutInput); return yield* Effect.gen(function* () { - const child = yield* spawner.spawn(ChildProcess.make(executable, args)).pipe( - Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })), - Effect.catchDefect((cause) => - Effect.fail(new TailscaleCommandSpawnError({ ...commandContext, cause })), - ), - ); + const child = yield* spawner + .spawn(ChildProcess.make(executable, args, { forceKillAfter: TAILSCALE_KILL_GRACE })) + .pipe( + Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })), + Effect.catchDefect((cause) => + Effect.fail(new TailscaleCommandSpawnError({ ...commandContext, cause })), + ), + ); const [stderr, exitCode] = yield* Effect.all( [collectStderr(child.stderr), child.exitCode.pipe(Effect.map(Number))], { concurrency: "unbounded" }, diff --git a/patches/alchemy@2.0.0-beta.84.patch b/patches/@alchemy.run__test@2.0.0-beta.85.patch similarity index 87% rename from patches/alchemy@2.0.0-beta.84.patch rename to patches/@alchemy.run__test@2.0.0-beta.85.patch index 469138523d0a3..0bd798963482f 100644 --- a/patches/alchemy@2.0.0-beta.84.patch +++ b/patches/@alchemy.run__test@2.0.0-beta.85.patch @@ -1,7 +1,7 @@ -diff --git a/lib/Test/Vitest.js b/lib/Test/Vitest.js +diff --git a/lib/Vitest.js b/lib/Vitest.js index 48cce71..ae67044 100644 ---- a/lib/Test/Vitest.js -+++ b/lib/Test/Vitest.js +--- a/lib/Vitest.js ++++ b/lib/Vitest.js @@ -3,7 +3,7 @@ import { it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; diff --git a/patches/@effect__vitest@4.0.5.patch b/patches/@effect__vitest@4.1.2.patch similarity index 88% rename from patches/@effect__vitest@4.0.5.patch rename to patches/@effect__vitest@4.1.2.patch index 754ab2eed6bcd..b5cc33ca3f821 100644 --- a/patches/@effect__vitest@4.0.5.patch +++ b/patches/@effect__vitest@4.1.2.patch @@ -1,5 +1,5 @@ diff --git a/dist/index.d.ts b/dist/index.d.ts -index 845cb4c..24ede42 100644 +index 0db951b..d6b6a6b 100644 --- a/dist/index.d.ts +++ b/dist/index.d.ts @@ -10,14 +10,14 @@ import type * as Effect from "effect/Effect"; @@ -20,7 +20,7 @@ index 845cb4c..24ede42 100644 * Vitest test API without additional fixtures. * diff --git a/dist/index.js b/dist/index.js -index 178cc74..9289296 100644 +index d10d1e7..6839558 100644 --- a/dist/index.js +++ b/dist/index.js @@ -5,7 +5,7 @@ import * as internal from "./internal/internal.js"; @@ -33,18 +33,18 @@ index 178cc74..9289296 100644 * Invokes the Effect Vitest equality-tester registration hook. * diff --git a/dist/internal/internal.js b/dist/internal/internal.js -index 7138319..4092c67 100644 +index 6c1b1c1..cdc3b26 100644 --- a/dist/internal/internal.js +++ b/dist/internal/internal.js -@@ -12,7 +12,7 @@ import * as Schedule from "effect/Schedule"; +@@ -13,7 +13,7 @@ import * as Schedule from "effect/Schedule"; import * as Scope from "effect/Scope"; import * as TestClock from "effect/testing/TestClock"; import * as TestConsole from "effect/testing/TestConsole"; -import * as V from "vitest"; +import * as V from "vite-plus/test"; const getCurrentSuite = V.TestRunner.getCurrentSuite; - const runPromise = /*#__PURE__*/Effect.fnUntraced(function* (effect, _ctx) { - const exit = yield* Effect.exit(effect); + const runPromise = (effect, ctx) => Effect.runPromise( + // Only the test is interruptible: once the signal aborts, the fiber stops diff --git a/dist/utils.js b/dist/utils.js index b97edbe..7dfd64a 100644 --- a/dist/utils.js @@ -59,7 +59,7 @@ index b97edbe..7dfd64a 100644 // Primitives // ---------------------------- diff --git a/package.json b/package.json -index b78f4d6..8c43672 100644 +index 068e75e..d14a80e 100644 --- a/package.json +++ b/package.json @@ -37,7 +37,6 @@ @@ -67,11 +67,11 @@ index b78f4d6..8c43672 100644 }, "peerDependencies": { - "vitest": ">=5.0.0 <6.0.0", - "effect": "^4.0.5" + "effect": "^4.1.2" }, "devDependencies": { diff --git a/src/index.ts b/src/index.ts -index 9d65132..4aadda8 100644 +index cb3bf6f..8024206 100644 --- a/src/index.ts +++ b/src/index.ts @@ -10,7 +10,7 @@ import type * as Effect from "effect/Effect" @@ -93,10 +93,10 @@ index 9d65132..4aadda8 100644 /** * Vitest test API without additional fixtures. diff --git a/src/internal/internal.ts b/src/internal/internal.ts -index b43385b..4da79fd 100644 +index e6ab75a..3b938a4 100644 --- a/src/internal/internal.ts +++ b/src/internal/internal.ts -@@ -14,7 +14,7 @@ import type * as Schema from "effect/Schema" +@@ -15,7 +15,7 @@ import type * as Schema from "effect/Schema" import * as Scope from "effect/Scope" import * as TestClock from "effect/testing/TestClock" import * as TestConsole from "effect/testing/TestConsole" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 17a2aeb3594ed..a91bfecd29af3 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -165,29 +165,32 @@ settings: catalogs: default: '@alchemy.run/axiom': - specifier: 2.0.0-beta.84 - version: 2.0.0-beta.84 + specifier: 2.0.0-beta.85 + version: 2.0.0-beta.85 '@alchemy.run/cloudflare': - specifier: 2.0.0-beta.84 - version: 2.0.0-beta.84 + specifier: 2.0.0-beta.85 + version: 2.0.0-beta.85 '@alchemy.run/drizzle': - specifier: 2.0.0-beta.84 - version: 2.0.0-beta.84 + specifier: 2.0.0-beta.85 + version: 2.0.0-beta.85 '@alchemy.run/planetscale': - specifier: 2.0.0-beta.84 - version: 2.0.0-beta.84 + specifier: 2.0.0-beta.85 + version: 2.0.0-beta.85 + '@alchemy.run/test': + specifier: 2.0.0-beta.85 + version: 2.0.0-beta.85 '@distilled.cloud/cloudflare': - specifier: 1.0.0-rc.17 - version: 1.0.0-rc.17 + specifier: 1.0.0-rc.18 + version: 1.0.0-rc.18 '@effect/graphql-generator': - specifier: 4.0.5 - version: 4.0.5 + specifier: 4.1.2 + version: 4.1.2 '@effect/openapi-generator': - specifier: 4.0.5 - version: 4.0.5 + specifier: 4.1.2 + version: 4.1.2 '@effect/sql-sqlite-do': - specifier: 4.0.5 - version: 4.0.5 + specifier: 4.1.2 + version: 4.1.2 '@noble/curves': specifier: 1.9.1 version: 1.9.1 @@ -270,7 +273,7 @@ overrides: micromark-extension-llm-math: 3.1.0 micromark: 4.0.2 mdast-util-to-hast: 13.2.1 - alchemy: 2.0.0-beta.84 + alchemy: 2.0.0-beta.85 expo-audio: 58.0.9 expo-network: 58.0.3 '@clerk/expo-native-components': 0.4.0 @@ -320,11 +323,12 @@ overrides: '@clerk/expo': 4.14.0 '@clerk/react': 6.18.0 '@clerk/shared': 4.41.0 - '@effect/atom-react': 4.0.5 - '@effect/platform-node': 4.0.5 - '@effect/platform-node-shared': 4.0.5 - '@effect/sql-pg': 4.0.5 - '@effect/vitest': 4.0.5 + '@effect/atom-react': 4.1.2 + '@effect/platform-bun': 4.1.2 + '@effect/platform-node': 4.1.2 + '@effect/platform-node-shared': 4.1.2 + '@effect/sql-pg': 4.1.2 + '@effect/vitest': 4.1.2 '@effect/vitest>vitest': '-' '@expo/dom-webview': 58.0.2 '@expo/metro-config': 58.0.14 @@ -339,9 +343,9 @@ overrides: '@tailwindcss/oxide': 4.3.3 '@tailwindcss/vite': 4.3.3 '@types/node': 24.12.4 - effect: 4.0.5 - '@opencode/protocol>effect': 4.0.5 - '@opencode/schema>effect': 4.0.5 + effect: 4.1.2 + '@opencode/protocol>effect': 4.1.2 + '@opencode/schema>effect': 4.1.2 node-abi: 4.33.0 electron-webauthn>@electron-webauthn/macos: 1.3.1 '@electron-webauthn/macos>objc-js': 1.5.0 @@ -359,8 +363,9 @@ packageExtensionsChecksum: sha256-EowbsmlBFaoO0Ypufw901RnvdyjKG5dcdk2FRbc7Dr0= pnpmfileChecksum: sha256-STsbxG7+RxOFI611PrDEj1TonJgqKKllY9hYCFMLYiU= patchedDependencies: + '@alchemy.run/test@2.0.0-beta.85': 29c0539ea71d9cc372f0b16558640599beb9bc609605feb2a493da268d72713e '@clerk/expo-native-components@0.4.0': 7a808b92da8460750b85818552e13be3fb73d111691c7db76965970351e124e4 - '@effect/vitest@4.0.5': 2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02 + '@effect/vitest@4.1.2': 299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7 '@expo/fingerprint@0.21.5': 8fba80d6bbce46c72de427fe8c7907462d262a0bfe50c6b2b7ee9c4e0c61e5e1 '@expo/metro-config@58.0.14': 90fa980e8b6480631fb2fbb04559834e3c612db40c550cd828f11be297d8d760 '@expo/ui@58.0.20': 64559cb60723e19a8a72256d4c78d1315d937a7af3b32d19860ea596f88736ce @@ -371,7 +376,6 @@ patchedDependencies: '@react-native-ai/apple@0.12.0': 2d09870c2848d185cb05b53ed823a46e12dba519324d8dd8e584e28731990f9d '@react-native-menu/menu@2.0.0': 910ec1bf22aa85a96fcf12299cd823bc30f702dd9b2d77b564d10b9ed709f7f6 '@react-navigation/native-stack@7.21.0': 990d575444c4af2ce8218b3b7a8280fe244c03abbdb32b822a2e862f791dbf42 - alchemy@2.0.0-beta.84: 824006659fa28ca31e490ce1fc3611f77436005ce9fa0f638be46564133cf042 app-builder-lib@26.16.1: 0fbe9ae51783f5768ebe197d12d1fdb7d477a08c92e5db2f6356bcce62613c53 dbus-next@0.10.2: cfff57561b0ee59b5addb3b2e6c6f20906e967507a530ab67e8db8108e520ba4 expo-audio@58.0.9: 530af071088a809fe1a97ce2b2269c78335fbb5dcd3893d6937ff5c304c85a0a @@ -430,8 +434,8 @@ importers: specifier: 0.13.0 version: 0.13.0 '@effect/platform-node': - specifier: 4.0.5 - version: 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6) + specifier: 4.1.2 + version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@napi-rs/keyring': specifier: ^1.3.0 version: 1.3.0 @@ -454,8 +458,8 @@ importers: specifier: 0.10.2 version: 0.10.2(patch_hash=cfff57561b0ee59b5addb3b2e6c6f20906e967507a530ab67e8db8108e520ba4) effect: - specifier: 4.0.5 - version: 4.0.5 + specifier: 4.1.2 + version: 4.1.2 electron: specifier: 44.10.0 version: 44.10.0(supports-color@8.1.1) @@ -482,8 +486,8 @@ importers: version: 7.4.2 devDependencies: '@effect/vitest': - specifier: 4.0.5 - version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + specifier: 4.1.2 + version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.1.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -537,8 +541,8 @@ importers: specifier: 0.4.0 version: 0.4.0(patch_hash=7a808b92da8460750b85818552e13be3fb73d111691c7db76965970351e124e4)(@tsc-rs/typescript@0.8.0)(expo@58.0.14)(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)(supports-color@8.1.1) '@effect/atom-react': - specifier: 4.0.5 - version: 4.0.5(effect@4.0.5)(react@19.3.0)(scheduler@0.28.0) + specifier: 4.1.2 + version: 4.1.2(effect@4.1.2)(react@19.3.0)(scheduler@0.28.0) '@expo-google-fonts/dm-sans': specifier: ^0.4.2 version: 0.4.2 @@ -615,8 +619,8 @@ importers: specifier: 8.0.3 version: 8.0.3 effect: - specifier: 4.0.5 - version: 4.0.5 + specifier: 4.1.2 + version: 4.1.2 expo: specifier: 58.0.14 version: 58.0.14(277a83826bb26ba15256633fefeb0bc2) @@ -799,11 +803,11 @@ importers: specifier: ^7.29.7 version: 7.29.7(supports-color@8.1.1) '@effect/platform-node': - specifier: 4.0.5 - version: 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6) + specifier: 4.1.2 + version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': - specifier: 4.0.5 - version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + specifier: 4.1.2 + version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.1.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@pierre/trees': specifier: 1.0.0-beta.6 version: 1.0.0-beta.6(@pierre/theme@2.0.0)(@shikijs/themes@4.2.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(shiki@4.2.0) @@ -835,17 +839,17 @@ importers: apps/server: dependencies: '@anthropic-ai/claude-agent-sdk': - specifier: ^0.3.276 - version: 0.3.276(@anthropic-ai/sdk@0.93.0(zod@4.6.5))(@modelcontextprotocol/sdk@1.29.0(supports-color@8.1.1)(zod@4.6.5))(zod@4.6.5) + specifier: ^0.3.284 + version: 0.3.284(@anthropic-ai/sdk@0.93.0(zod@4.6.5))(@modelcontextprotocol/sdk@1.29.0(supports-color@8.1.1)(zod@4.6.5))(zod@4.6.5) '@cursor/sdk': - specifier: 1.0.38 - version: 1.0.38(zod@4.6.5) + specifier: 1.2.0 + version: 1.2.0(zod@4.6.5) '@effect/platform-node': - specifier: 4.0.5 - version: 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6) + specifier: 4.1.2 + version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/platform-node-shared': - specifier: 4.0.5 - version: 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(utf-8-validate@6.0.6) + specifier: 4.1.2 + version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6) '@ff-labs/fff-node': specifier: 0.11.0 version: 0.11.0(patch_hash=cc71fcec015f4d39bc96ae2e2bf6b0ca678124c722c66a7841efce9d34b5983c) @@ -873,6 +877,9 @@ importers: '@t3tools/provider-grok': specifier: workspace:* version: link:../../packages/provider-grok + '@t3tools/provider-kiro': + specifier: workspace:* + version: link:../../packages/provider-kiro '@t3tools/provider-muse': specifier: workspace:* version: link:../../packages/provider-muse @@ -913,8 +920,8 @@ importers: specifier: 8.0.3 version: 8.0.3 effect: - specifier: 4.0.5 - version: 4.0.5 + specifier: 4.1.2 + version: 4.1.2 ffi-rs: specifier: 1.3.2 version: 1.3.2 @@ -954,10 +961,10 @@ importers: devDependencies: '@effect/graphql-generator': specifier: 'catalog:' - version: 4.0.5(@effect/platform-node@4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.0.5) + version: 4.1.2(@effect/platform-node@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.2) '@effect/vitest': - specifier: 4.0.5 - version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + specifier: 4.1.2 + version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.1.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@opencode-ai/sdk': specifier: ^1.3.15 version: 1.15.13 @@ -1055,8 +1062,8 @@ importers: specifier: ^3.2.2 version: 3.2.2(react@19.3.0) '@effect/atom-react': - specifier: 4.0.5 - version: 4.0.5(effect@4.0.5)(react@19.3.0)(scheduler@0.28.0) + specifier: 4.1.2 + version: 4.1.2(effect@4.1.2)(react@19.3.0)(scheduler@0.28.0) '@fontsource-variable/inter': specifier: ^5.3.0 version: 5.3.0 @@ -1157,8 +1164,8 @@ importers: specifier: ^3.4.16 version: 3.4.16 effect: - specifier: 4.0.5 - version: 4.0.5 + specifier: 4.1.2 + version: 4.1.2 entities: specifier: 8.1.0 version: 8.1.0 @@ -1260,11 +1267,11 @@ importers: version: 5.0.14(@types/react@19.3.0)(react@19.3.0)(use-sync-external-store@1.6.0(react@19.3.0)) devDependencies: '@effect/platform-node': - specifier: 4.0.5 - version: 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6) + specifier: 4.1.2 + version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': - specifier: 4.0.5 - version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + specifier: 4.1.2 + version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.1.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@tailwindcss/vite': specifier: 4.3.3 version: 4.3.3(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0)) @@ -1329,8 +1336,8 @@ importers: evals: dependencies: '@effect/platform-node': - specifier: 4.0.5 - version: 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6) + specifier: 4.1.2 + version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@t3tools/contracts': specifier: workspace:* version: link:../packages/contracts @@ -1341,12 +1348,12 @@ importers: specifier: workspace:* version: link:../packages/shared effect: - specifier: 4.0.5 - version: 4.0.5 + specifier: 4.1.2 + version: 4.1.2 devDependencies: '@effect/vitest': - specifier: 4.0.5 - version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + specifier: 4.1.2 + version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.1.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1361,28 +1368,28 @@ importers: dependencies: '@alchemy.run/axiom': specifier: 'catalog:' - version: 2.0.0-beta.84(74118100341fd69edb1510aa7b7f1bd2) + version: 2.0.0-beta.85(alchemy@2.0.0-beta.85(@effect/platform-bun@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.2)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.2) '@alchemy.run/cloudflare': specifier: 'catalog:' - version: 2.0.0-beta.84(24ce6902b7189b66a257867375b8f56d) + version: 2.0.0-beta.85(3c6bb1d0d4de1cb5d4932cf1224d79e6) '@alchemy.run/drizzle': specifier: 'catalog:' - version: 2.0.0-beta.84(621723465c0c1236eb5d87515baf6818) + version: 2.0.0-beta.85(0f2f0b2f6e85ad5bbc9df78a7c15a609) '@alchemy.run/planetscale': specifier: 'catalog:' - version: 2.0.0-beta.84(1b64d144d22bc50b8239f5331dd49513) + version: 2.0.0-beta.85(@effect/sql-pg@4.1.2(effect@4.1.2))(alchemy@2.0.0-beta.85(@effect/platform-bun@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.2)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.2)(pg@8.23.0) '@clerk/backend': specifier: 3.25.0 version: 3.25.0(react-dom@19.3.0(react@19.3.0))(react@19.3.0) '@distilled.cloud/cloudflare': specifier: 'catalog:' - version: 1.0.0-rc.17(effect@4.0.5) + version: 1.0.0-rc.18(effect@4.1.2) '@effect/sql-pg': - specifier: 4.0.5 - version: 4.0.5(effect@4.0.5) + specifier: 4.1.2 + version: 4.1.2(effect@4.1.2) '@effect/sql-sqlite-do': specifier: 'catalog:' - version: 4.0.5(effect@4.0.5) + version: 4.1.2(effect@4.1.2) '@noble/curves': specifier: 'catalog:' version: 1.9.1 @@ -1399,24 +1406,27 @@ importers: specifier: workspace:* version: link:../../packages/shared alchemy: - specifier: 2.0.0-beta.84 - version: 2.0.0-beta.84(patch_hash=824006659fa28ca31e490ce1fc3611f77436005ce9fa0f638be46564133cf042)(@effect/platform-node@4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@effect/vitest@4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(effect@4.0.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + specifier: 2.0.0-beta.85 + version: 2.0.0-beta.85(@effect/platform-bun@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.2)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) drizzle-orm: specifier: 1.0.0-rc.5-ab785fc - version: 1.0.0-rc.5-ab785fc(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.0.6(effect@4.0.5))(@effect/sql-pg@4.0.5(effect@4.0.5))(@effect/sql-sqlite-bun@4.0.0-rc.112(effect@4.0.5))(@effect/sql-sqlite-do@4.0.5(effect@4.0.5))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.0.5)(expo-sqlite@58.0.13(expo@58.0.14)(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.5) + version: 1.0.0-rc.5-ab785fc(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.2))(@effect/sql-pg@4.1.2(effect@4.1.2))(@effect/sql-sqlite-do@4.1.2(effect@4.1.2))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.2)(expo-sqlite@58.0.13(expo@58.0.14)(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.5) effect: - specifier: 4.0.5 - version: 4.0.5 + specifier: 4.1.2 + version: 4.1.2 devDependencies: + '@alchemy.run/test': + specifier: 'catalog:' + version: 2.0.0-beta.85(patch_hash=29c0539ea71d9cc372f0b16558640599beb9bc609605feb2a493da268d72713e)(071253407c4f3cb63d401833ee1dda26) '@cloudflare/workers-types': specifier: ^4.20260601.1 version: 4.20260604.1 '@effect/platform-node': - specifier: 4.0.5 - version: 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6) + specifier: 4.1.2 + version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': - specifier: 4.0.5 - version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + specifier: 4.1.2 + version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.1.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@electric-sql/pglite': specifier: 0.3.15 version: 0.3.15 @@ -1440,16 +1450,16 @@ importers: dependencies: '@alchemy.run/axiom': specifier: 'catalog:' - version: 2.0.0-beta.84(74118100341fd69edb1510aa7b7f1bd2) + version: 2.0.0-beta.85(alchemy@2.0.0-beta.85(@effect/platform-bun@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.2)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.2) '@alchemy.run/cloudflare': specifier: 'catalog:' - version: 2.0.0-beta.84(24ce6902b7189b66a257867375b8f56d) + version: 2.0.0-beta.85(3c6bb1d0d4de1cb5d4932cf1224d79e6) alchemy: - specifier: 2.0.0-beta.84 - version: 2.0.0-beta.84(patch_hash=824006659fa28ca31e490ce1fc3611f77436005ce9fa0f638be46564133cf042)(@effect/platform-node@4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@effect/vitest@4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(effect@4.0.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + specifier: 2.0.0-beta.85 + version: 2.0.0-beta.85(@effect/platform-bun@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.2)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) effect: - specifier: 4.0.5 - version: 4.0.5 + specifier: 4.1.2 + version: 4.1.2 jose: specifier: 'catalog:' version: 6.2.2 @@ -1458,11 +1468,11 @@ importers: specifier: ^4.20260601.1 version: 4.20260604.1 '@effect/platform-node': - specifier: 4.0.5 - version: 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6) + specifier: 4.1.2 + version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': - specifier: 4.0.5 - version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + specifier: 4.1.2 + version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.1.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1479,15 +1489,15 @@ importers: specifier: ^1.63.0 version: 1.89.0 effect: - specifier: 4.0.5 - version: 4.0.5 + specifier: 4.1.2 + version: 4.1.2 devDependencies: '@effect/platform-node': - specifier: 4.0.5 - version: 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6) + specifier: 4.1.2 + version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': - specifier: 4.0.5 - version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + specifier: 4.1.2 + version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.1.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) vite-plus: specifier: 1.4.0 version: 1.4.0(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) @@ -1515,6 +1525,9 @@ importers: '@t3tools/provider-grok': specifier: workspace:* version: link:../provider-grok + '@t3tools/provider-kiro': + specifier: workspace:* + version: link:../provider-kiro '@t3tools/provider-muse': specifier: workspace:* version: link:../provider-muse @@ -1534,8 +1547,8 @@ importers: specifier: workspace:* version: link:../source-control-definitions effect: - specifier: 4.0.5 - version: 4.0.5 + specifier: 4.1.2 + version: 4.1.2 jszip: specifier: 3.10.1 version: 3.10.1 @@ -1544,8 +1557,8 @@ importers: version: 0.180.0 devDependencies: '@effect/vitest': - specifier: 4.0.5 - version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + specifier: 4.1.2 + version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.1.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/three': specifier: 0.180.0 version: 0.180.0 @@ -1556,12 +1569,12 @@ importers: packages/contracts: dependencies: effect: - specifier: 4.0.5 - version: 4.0.5 + specifier: 4.1.2 + version: 4.1.2 devDependencies: '@effect/vitest': - specifier: 4.0.5 - version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + specifier: 4.1.2 + version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.1.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) vite-plus: specifier: 1.4.0 version: 1.4.0(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) @@ -1569,18 +1582,18 @@ importers: packages/effect-acp: dependencies: effect: - specifier: 4.0.5 - version: 4.0.5 + specifier: 4.1.2 + version: 4.1.2 devDependencies: '@effect/openapi-generator': specifier: 'catalog:' - version: 4.0.5(@effect/platform-node@4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.0.5)(encoding@0.1.13) + version: 4.1.2(@effect/platform-node@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.2)(encoding@0.1.13) '@effect/platform-node': - specifier: 4.0.5 - version: 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6) + specifier: 4.1.2 + version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': - specifier: 4.0.5 - version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + specifier: 4.1.2 + version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.1.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1591,18 +1604,18 @@ importers: packages/effect-codex-app-server: dependencies: effect: - specifier: 4.0.5 - version: 4.0.5 + specifier: 4.1.2 + version: 4.1.2 devDependencies: '@effect/openapi-generator': specifier: 'catalog:' - version: 4.0.5(@effect/platform-node@4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.0.5)(encoding@0.1.13) + version: 4.1.2(@effect/platform-node@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.2)(encoding@0.1.13) '@effect/platform-node': - specifier: 4.0.5 - version: 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6) + specifier: 4.1.2 + version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': - specifier: 4.0.5 - version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + specifier: 4.1.2 + version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.1.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1625,15 +1638,15 @@ importers: specifier: 8.0.3 version: 8.0.3 effect: - specifier: 4.0.5 - version: 4.0.5 + specifier: 4.1.2 + version: 4.1.2 devDependencies: '@effect/platform-node': - specifier: 4.0.5 - version: 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6) + specifier: 4.1.2 + version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': - specifier: 4.0.5 - version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + specifier: 4.1.2 + version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.1.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1662,15 +1675,15 @@ importers: specifier: workspace:* version: link:../shared effect: - specifier: 4.0.5 - version: 4.0.5 + specifier: 4.1.2 + version: 4.1.2 devDependencies: '@effect/platform-node': - specifier: 4.0.5 - version: 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6) + specifier: 4.1.2 + version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': - specifier: 4.0.5 - version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + specifier: 4.1.2 + version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.1.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1693,15 +1706,15 @@ importers: specifier: workspace:* version: link:../shared effect: - specifier: 4.0.5 - version: 4.0.5 + specifier: 4.1.2 + version: 4.1.2 devDependencies: '@effect/platform-node': - specifier: 4.0.5 - version: 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6) + specifier: 4.1.2 + version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': - specifier: 4.0.5 - version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + specifier: 4.1.2 + version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.1.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1712,8 +1725,8 @@ importers: packages/provider-cursor: dependencies: '@cursor/sdk': - specifier: 1.0.38 - version: 1.0.38(zod@4.6.5) + specifier: 1.2.0 + version: 1.2.0(zod@4.6.5) '@napi-rs/keyring': specifier: ^1.3.0 version: 1.3.0 @@ -1727,18 +1740,18 @@ importers: specifier: workspace:* version: link:../shared effect: - specifier: 4.0.5 - version: 4.0.5 + specifier: 4.1.2 + version: 4.1.2 yaml: specifier: ^2.9.0 version: 2.9.0 devDependencies: '@effect/platform-node': - specifier: 4.0.5 - version: 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6) + specifier: 4.1.2 + version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': - specifier: 4.0.5 - version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + specifier: 4.1.2 + version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.1.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1764,15 +1777,15 @@ importers: specifier: workspace:* version: link:../shared effect: - specifier: 4.0.5 - version: 4.0.5 + specifier: 4.1.2 + version: 4.1.2 devDependencies: '@effect/platform-node': - specifier: 4.0.5 - version: 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6) + specifier: 4.1.2 + version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': - specifier: 4.0.5 - version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + specifier: 4.1.2 + version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.1.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1798,15 +1811,15 @@ importers: specifier: workspace:* version: link:../shared effect: - specifier: 4.0.5 - version: 4.0.5 + specifier: 4.1.2 + version: 4.1.2 devDependencies: '@effect/platform-node': - specifier: 4.0.5 - version: 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6) + specifier: 4.1.2 + version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': - specifier: 4.0.5 - version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + specifier: 4.1.2 + version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.1.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1820,6 +1833,37 @@ importers: specifier: 1.4.0 version: 1.4.0(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + packages/provider-kiro: + dependencies: + '@t3tools/contracts': + specifier: workspace:* + version: link:../contracts + '@t3tools/provider-acp': + specifier: workspace:* + version: link:../provider-acp + '@t3tools/provider-core': + specifier: workspace:* + version: link:../provider-core + '@t3tools/shared': + specifier: workspace:* + version: link:../shared + effect: + specifier: 4.1.2 + version: 4.1.2 + devDependencies: + '@effect/vitest': + specifier: 4.1.2 + version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.1.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + '@types/node': + specifier: 24.12.4 + version: 24.12.4 + effect-acp: + specifier: workspace:* + version: link:../effect-acp + vite-plus: + specifier: 1.4.0 + version: 1.4.0(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + packages/provider-muse: dependencies: '@muse-code/sdk': @@ -1835,15 +1879,15 @@ importers: specifier: workspace:* version: link:../shared effect: - specifier: 4.0.5 - version: 4.0.5 + specifier: 4.1.2 + version: 4.1.2 devDependencies: '@effect/platform-node': - specifier: 4.0.5 - version: 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6) + specifier: 4.1.2 + version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': - specifier: 4.0.5 - version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + specifier: 4.1.2 + version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.1.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1861,7 +1905,7 @@ importers: version: 1.15.13 '@opencode/client': specifier: 2.0.28 - version: 2.0.28(effect@4.0.5) + version: 2.0.28(effect@4.1.2) '@opencode/protocol': specifier: 2.0.28 version: 2.0.28 @@ -1878,15 +1922,15 @@ importers: specifier: workspace:* version: link:../shared effect: - specifier: 4.0.5 - version: 4.0.5 + specifier: 4.1.2 + version: 4.1.2 devDependencies: '@effect/platform-node': - specifier: 4.0.5 - version: 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6) + specifier: 4.1.2 + version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': - specifier: 4.0.5 - version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + specifier: 4.1.2 + version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.1.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1909,15 +1953,15 @@ importers: specifier: workspace:* version: link:../shared effect: - specifier: 4.0.5 - version: 4.0.5 + specifier: 4.1.2 + version: 4.1.2 devDependencies: '@effect/platform-node': - specifier: 4.0.5 - version: 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6) + specifier: 4.1.2 + version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': - specifier: 4.0.5 - version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + specifier: 4.1.2 + version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.1.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1931,8 +1975,8 @@ importers: packages/provider-testing: dependencies: '@effect/platform-node': - specifier: 4.0.5 - version: 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6) + specifier: 4.1.2 + version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@t3tools/contracts': specifier: workspace:* version: link:../contracts @@ -1943,8 +1987,8 @@ importers: specifier: workspace:* version: link:../shared effect: - specifier: 4.0.5 - version: 4.0.5 + specifier: 4.1.2 + version: 4.1.2 devDependencies: '@types/node': specifier: 24.12.4 @@ -1956,15 +2000,15 @@ importers: specifier: workspace:* version: link:../contracts effect: - specifier: 4.0.5 - version: 4.0.5 + specifier: 4.1.2 + version: 4.1.2 devDependencies: '@effect/platform-node': - specifier: 4.0.5 - version: 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6) + specifier: 4.1.2 + version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': - specifier: 4.0.5 - version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + specifier: 4.1.2 + version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.1.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1996,15 +2040,15 @@ importers: specifier: workspace:* version: link:../shared effect: - specifier: 4.0.5 - version: 4.0.5 + specifier: 4.1.2 + version: 4.1.2 devDependencies: '@effect/platform-node': - specifier: 4.0.5 - version: 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6) + specifier: 4.1.2 + version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': - specifier: 4.0.5 - version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + specifier: 4.1.2 + version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.1.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -2024,8 +2068,8 @@ importers: specifier: workspace:* version: link:../contracts effect: - specifier: 4.0.5 - version: 4.0.5 + specifier: 4.1.2 + version: 4.1.2 ffi-rs: specifier: 1.3.2 version: 1.3.2 @@ -2076,11 +2120,11 @@ importers: version: 2.9.0 devDependencies: '@effect/platform-node': - specifier: 4.0.5 - version: 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6) + specifier: 4.1.2 + version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': - specifier: 4.0.5 - version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + specifier: 4.1.2 + version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.1.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/mdast': specifier: ^4.0.4 version: 4.0.4 @@ -2109,15 +2153,15 @@ importers: specifier: 8.0.3 version: 8.0.3 effect: - specifier: 4.0.5 - version: 4.0.5 + specifier: 4.1.2 + version: 4.1.2 devDependencies: '@effect/platform-node': - specifier: 4.0.5 - version: 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6) + specifier: 4.1.2 + version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': - specifier: 4.0.5 - version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + specifier: 4.1.2 + version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.1.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2143,15 +2187,15 @@ importers: specifier: workspace:* version: link:../source-control-core effect: - specifier: 4.0.5 - version: 4.0.5 + specifier: 4.1.2 + version: 4.1.2 devDependencies: '@effect/platform-node': - specifier: 4.0.5 - version: 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6) + specifier: 4.1.2 + version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': - specifier: 4.0.5 - version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + specifier: 4.1.2 + version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.1.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2171,12 +2215,12 @@ importers: specifier: workspace:* version: link:../shared effect: - specifier: 4.0.5 - version: 4.0.5 + specifier: 4.1.2 + version: 4.1.2 devDependencies: '@effect/vitest': - specifier: 4.0.5 - version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + specifier: 4.1.2 + version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.1.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -2223,15 +2267,15 @@ importers: specifier: workspace:* version: link:../source-control-core effect: - specifier: 4.0.5 - version: 4.0.5 + specifier: 4.1.2 + version: 4.1.2 devDependencies: '@effect/platform-node': - specifier: 4.0.5 - version: 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6) + specifier: 4.1.2 + version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': - specifier: 4.0.5 - version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + specifier: 4.1.2 + version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.1.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2257,12 +2301,12 @@ importers: specifier: workspace:* version: link:../source-control-core effect: - specifier: 4.0.5 - version: 4.0.5 + specifier: 4.1.2 + version: 4.1.2 devDependencies: '@effect/vitest': - specifier: 4.0.5 - version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + specifier: 4.1.2 + version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.1.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2288,18 +2332,18 @@ importers: specifier: workspace:* version: link:../source-control-core effect: - specifier: 4.0.5 - version: 4.0.5 + specifier: 4.1.2 + version: 4.1.2 devDependencies: '@effect/graphql-generator': specifier: 'catalog:' - version: 4.0.5(@effect/platform-node@4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.0.5) + version: 4.1.2(@effect/platform-node@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.2) '@effect/platform-node': - specifier: 4.0.5 - version: 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6) + specifier: 4.1.2 + version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': - specifier: 4.0.5 - version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + specifier: 4.1.2 + version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.1.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2322,12 +2366,12 @@ importers: specifier: workspace:* version: link:../source-control-core effect: - specifier: 4.0.5 - version: 4.0.5 + specifier: 4.1.2 + version: 4.1.2 devDependencies: '@effect/vitest': - specifier: 4.0.5 - version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + specifier: 4.1.2 + version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.1.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2341,8 +2385,8 @@ importers: packages/source-control-testing: dependencies: '@effect/platform-node': - specifier: 4.0.5 - version: 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6) + specifier: 4.1.2 + version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@t3tools/contracts': specifier: workspace:* version: link:../contracts @@ -2353,8 +2397,8 @@ importers: specifier: workspace:* version: link:../source-control-core effect: - specifier: 4.0.5 - version: 4.0.5 + specifier: 4.1.2 + version: 4.1.2 devDependencies: '@types/node': specifier: 24.12.4 @@ -2369,15 +2413,15 @@ importers: specifier: workspace:* version: link:../shared effect: - specifier: 4.0.5 - version: 4.0.5 + specifier: 4.1.2 + version: 4.1.2 devDependencies: '@effect/platform-node': - specifier: 4.0.5 - version: 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6) + specifier: 4.1.2 + version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': - specifier: 4.0.5 - version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + specifier: 4.1.2 + version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.1.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -2391,12 +2435,12 @@ importers: specifier: workspace:* version: link:../shared effect: - specifier: 4.0.5 - version: 4.0.5 + specifier: 4.1.2 + version: 4.1.2 devDependencies: '@effect/vitest': - specifier: 4.0.5 - version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + specifier: 4.1.2 + version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.1.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -2407,8 +2451,8 @@ importers: scripts: dependencies: '@effect/platform-node': - specifier: 4.0.5 - version: 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6) + specifier: 4.1.2 + version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@electron/asar': specifier: ^4.3.0 version: 4.3.0 @@ -2428,8 +2472,8 @@ importers: specifier: 0.21.32 version: 0.21.32 effect: - specifier: 4.0.5 - version: 4.0.5 + specifier: 4.1.2 + version: 4.1.2 playwright-core: specifier: 1.60.0 version: 1.60.0 @@ -2444,8 +2488,8 @@ importers: version: 0.35.4(@types/node@24.12.4) devDependencies: '@effect/vitest': - specifier: 4.0.5 - version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + specifier: 4.1.2 + version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.1.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/plist': specifier: 'catalog:' version: 3.0.5 @@ -2489,25 +2533,25 @@ packages: resolution: {integrity: sha512-IpefF5ssZVOZCD4Wu7zxt6PwZoGT2HLVjxpJ10Bjx6EAmRfLYJPjyrfxb0RYDlwvXnDb9nkQ7Do/oJVDuRFzew==} engines: {node: '>=18'} - '@alchemy.run/acme@2.0.0-beta.84': - resolution: {integrity: sha512-ma7HaEN5K7hsNlSkK7CEGn+08hKi4xP1puEAoSO7UACXc/j/2gZKljuztADyCOKOdp8nIMJ/zH12Qs7J11E8cQ==} + '@alchemy.run/acme@2.0.0-beta.85': + resolution: {integrity: sha512-hOV18VHG6ivrbPnk35hoqlCQPc6bR8b9soGmHlSkbnPIgVZUg7jpliF9AztSSJbJK4GHcBFc9hWetwCRHzGYAg==} peerDependencies: - alchemy: 2.0.0-beta.84 - effect: 4.0.5 + alchemy: 2.0.0-beta.85 + effect: 4.1.2 - '@alchemy.run/axiom@2.0.0-beta.84': - resolution: {integrity: sha512-7kZpp2Trdw7pp/27EWspAcXxcNQfxyFLwY0P/WjnDHg/WqNK0AHFNBGgQoY6jI/vA8YO5DxdzfzI53Tj6hCRZA==} + '@alchemy.run/axiom@2.0.0-beta.85': + resolution: {integrity: sha512-dpBBDxZaRlRIiszRYTUB9M3e3yN6hvkyYTpc0E66tJfcESY6rwp2O2fl38Mun5iLEyGJb2Gvv4HqPiURYWzrHw==} peerDependencies: - alchemy: 2.0.0-beta.84 - effect: 4.0.5 + alchemy: 2.0.0-beta.85 + effect: 4.1.2 - '@alchemy.run/cloudflare-runtime@2.0.0-beta.84': - resolution: {integrity: sha512-wmlfbJHBEpyKpKosIKi6yte0T6WKofed0rDHR1zk7tZdqwUKNNSRcbR9ejfJ4mty7lkQH0fLKn4vcmfnlX9KDQ==} + '@alchemy.run/cloudflare-runtime@2.0.0-beta.85': + resolution: {integrity: sha512-OyGH/j5R9QaUdMjvm3y6pIUpMa7T9SvVYvlVd+fWo/eltOf+k/KQxC12QHC2fe22GVs3apL28l9f4VUH8N9aEA==} peerDependencies: - '@distilled.cloud/cloudflare': 1.0.0-rc.17 - '@effect/platform-bun': ^4.0.5 - '@effect/platform-node': 4.0.5 - effect: 4.0.5 + '@distilled.cloud/cloudflare': 1.0.0-rc.18 + '@effect/platform-bun': 4.1.2 + '@effect/platform-node': 4.1.2 + effect: 4.1.2 rolldown: 1.2.13 vite: ^7.0.0 || ^8.0.0 peerDependenciesMeta: @@ -2520,16 +2564,16 @@ packages: vite: optional: true - '@alchemy.run/cloudflare@2.0.0-beta.84': - resolution: {integrity: sha512-8AEp0664arL1BLPIxQJ/lgIUPRvsk0SxC/6fW6S3Gt2SOauUF2YpUsgRr94m4pTX453gacMXwJ/kw8lgOv+TMw==} + '@alchemy.run/cloudflare@2.0.0-beta.85': + resolution: {integrity: sha512-gS/LYJIpEiRthx+Eqr/+O9TseXB7PGuWWkOc96oHfqwDHu+8zUzaY1pwsc0qQ1eAlgd/xy8YWnM6JThc6eXOUQ==} peerDependencies: - '@alchemy.run/domain': 2.0.0-beta.84 - '@alchemy.run/frontend-frameworks': 2.0.0-beta.84 - '@effect/platform-bun': ^4.0.5 - '@effect/platform-node': 4.0.5 - alchemy: 2.0.0-beta.84 - effect: 4.0.5 - vite: ^8.0.7 + '@alchemy.run/domain': 2.0.0-beta.85 + '@alchemy.run/frontend-frameworks': 2.0.0-beta.85 + '@effect/platform-bun': 4.1.2 + '@effect/platform-node': 4.1.2 + alchemy: 2.0.0-beta.85 + effect: 4.1.2 + vite: ^7.0.0 || ^8.0.0 peerDependenciesMeta: '@alchemy.run/domain': optional: true @@ -2542,27 +2586,27 @@ packages: vite: optional: true - '@alchemy.run/docker@2.0.0-beta.84': - resolution: {integrity: sha512-VaUNlldyPcCrrGDCfFUJD+pvNt3Rpbly+0lzZ4S8AfkpxMD4rZy7GdXcfPzeA26tcDzfsDVax7BGlArzupEc0g==} + '@alchemy.run/docker@2.0.0-beta.85': + resolution: {integrity: sha512-AhVdcCTu/paBdDUtGc2U4WEa8+gczkkf7oH7XEeIVjlQ+xX3hmYWlspdfejoJ9pb2JT4myfvp5EeXi/Jcp+W2g==} peerDependencies: - '@effect/platform-bun': ^4.0.5 - alchemy: 2.0.0-beta.84 - effect: 4.0.5 + '@effect/platform-bun': 4.1.2 + alchemy: 2.0.0-beta.85 + effect: 4.1.2 peerDependenciesMeta: '@effect/platform-bun': optional: true - '@alchemy.run/drizzle@2.0.0-beta.84': - resolution: {integrity: sha512-C+3k4J9wE64+z4NmDB+CBIjc/xiT0Dw63Dgo5v98yh1QKCdXeo3ypBgCSQTdrvimXJEYjwF+HDfAqP84M8/8Hw==} + '@alchemy.run/drizzle@2.0.0-beta.85': + resolution: {integrity: sha512-65goZGSiDgTMBH1XXjhgP/wKd5mfhaGe9RjQHiGCwWVtwExbfc+qhYd2n7AzwkgXWWcgW7A43pv4nvtzcPsNWw==} peerDependencies: - '@alchemy.run/cloudflare': 2.0.0-beta.84 - '@effect/sql-libsql': ^4.0.5 - '@effect/sql-mysql2': ^4.0.5 - '@effect/sql-pg': 4.0.5 - alchemy: 2.0.0-beta.84 - drizzle-kit: 1.0.0-rc.5-ab785fc - drizzle-orm: 1.0.0-rc.5-ab785fc - effect: 4.0.5 + '@alchemy.run/cloudflare': 2.0.0-beta.85 + '@effect/sql-libsql': ^4.1.0 + '@effect/sql-mysql2': ^4.1.0 + '@effect/sql-pg': 4.1.2 + alchemy: 2.0.0-beta.85 + drizzle-kit: 1.0.0-rc.5 + drizzle-orm: 1.0.0-rc.5 + effect: 4.1.2 peerDependenciesMeta: '@alchemy.run/cloudflare': optional: true @@ -2575,14 +2619,14 @@ packages: drizzle-kit: optional: true - '@alchemy.run/node-utils@2.0.0-beta.84': - resolution: {integrity: sha512-UdvCtwEeLmRNN89gVjkMIQTqzkE+xPQb26dPsQM6JzDdHUyqaTyg64U4RmfUjUul0sWQbbVIeAO475GQYbGELw==} + '@alchemy.run/node-utils@2.0.0-beta.85': + resolution: {integrity: sha512-2gxqMNMoJdx13w7wlDJw+gaXQ8e1VxQFsKldOvweqpd7JEgB5TGn3oO8r1sb/GB9+UzqXdh8tKp2MOVgFOrmbg==} - '@alchemy.run/planetscale@2.0.0-beta.84': - resolution: {integrity: sha512-j0Y4oreytRcH/fickgRPP6+i4KC8vTX/gEz58WVho+hHcajgxGAcxnrSUCoV4YgKFOigR5ONkq+OhbR5a+VPVw==} + '@alchemy.run/planetscale@2.0.0-beta.85': + resolution: {integrity: sha512-rBG26S6nGVF3fzCTnvMKu/Un/5H+YepOIJyld+1JeaAKV78z3U+bYtR+dSWR6KcW8tG8xX9pj83sisZdp0iNog==} peerDependencies: - alchemy: 2.0.0-beta.84 - effect: 4.0.5 + alchemy: 2.0.0-beta.85 + effect: 4.1.2 mysql2: ^3.24.2 pg: ^8.22.0 peerDependenciesMeta: @@ -2603,14 +2647,14 @@ packages: react-devtools-core: optional: true - '@alchemy.run/sql@2.0.0-beta.84': - resolution: {integrity: sha512-GdP9zDnm6b25p8DZfeg8HbPk66pfIuTA+IHFSC/I8iKbjUE49WoqBmdSUSJtL4ZmTvndTDCYZ7Y9PehBjNTL+w==} + '@alchemy.run/sql@2.0.0-beta.85': + resolution: {integrity: sha512-8827sU12RJRNjj+HM9XMxnw86gxzrg5c4dAon7KEs9xgV96OW2RaJlcrL9bJ4L2QZWzRTayHh5S1KKio4uUAOw==} peerDependencies: - '@effect/sql-libsql': ^4.0.5 - '@effect/sql-mysql2': ^4.0.5 - '@effect/sql-pg': 4.0.5 - alchemy: 2.0.0-beta.84 - effect: 4.0.5 + '@effect/sql-libsql': ^4.1.0 + '@effect/sql-mysql2': ^4.1.0 + '@effect/sql-pg': 4.1.2 + alchemy: 2.0.0-beta.85 + effect: 4.1.2 mysql2: ^3.24.2 pg: ^8.22.0 peerDependenciesMeta: @@ -2625,8 +2669,28 @@ packages: pg: optional: true - '@anthropic-ai/claude-agent-sdk@0.3.276': - resolution: {integrity: sha512-Dic43v4uuGLhibPAArWy3RSfq3zHdn+4Oh2AI2/18a5tlbNKkvChEpazyp8c+grUJvzxkzt0jETCa1wrADbkyw==} + '@alchemy.run/test@2.0.0-beta.85': + resolution: {integrity: sha512-/dwCV4a30g75dgasqLzOnSHKU3qGInmd87C9QZja8rhr7ooZNF8kl60W0JmPhZqotICzdt9R7bI35MsUFxlLGg==} + engines: {bun: '>=1.3'} + hasBin: true + peerDependencies: + '@effect/vitest': 4.1.2 + '@opentui/core': ^0.6.6 + alchemy: 2.0.0-beta.85 + effect: 4.1.2 + vitest: ^5.0.4 + peerDependenciesMeta: + '@effect/vitest': + optional: true + '@opentui/core': + optional: true + alchemy: + optional: true + vitest: + optional: true + + '@anthropic-ai/claude-agent-sdk@0.3.284': + resolution: {integrity: sha512-NSoJwEq6nFSf8dtaacYx37QdGgqApI3eHFUlxclMLYi8irb6ZJwEaUnPnLUCyAyg9W/tMkgZC0GXWLRCc01I0w==} engines: {node: '>=18.0.0'} peerDependencies: '@anthropic-ai/sdk': '>=0.93.0' @@ -3394,32 +3458,32 @@ packages: workerd: optional: true - '@cloudflare/workerd-darwin-64@1.20261012.1': - resolution: {integrity: sha512-dkTL9aY3V4D40b+jBpGPCistWUPFQ/M61wlWi6i1o8MvHFFgEw7EQkcaYEv6Yd3bkPDD/3TFT4hRsMb2xVZSwQ==} + '@cloudflare/workerd-darwin-64@1.20261026.1': + resolution: {integrity: sha512-5IGoYEBQdJeHUn3mOalHQOtt2NXBKvvsqiK2cwIl9OZB6DtpmEmGDzbeFmOgsEQcGrK9f4KnLbr0SQUglnibIQ==} engines: {node: '>=16'} cpu: [x64] os: [darwin] - '@cloudflare/workerd-darwin-arm64@1.20261012.1': - resolution: {integrity: sha512-2/nVGcKXjNNI+DhxKSepTKvFng9H7aN2WXv6Zu67iqgI6JrxypNt5kTPv4ZHosxrcfyKMci/2RfN7GIrN0BitQ==} + '@cloudflare/workerd-darwin-arm64@1.20261026.1': + resolution: {integrity: sha512-ewhmUr/1S8/ik7MjPcQqq7Kx91I6AVLSlTTblbU8OkZ4CiPy92N3WBNMZ06BUkJaFS+XThbXyN/4FDF6xIFo5w==} engines: {node: '>=16'} cpu: [arm64] os: [darwin] - '@cloudflare/workerd-linux-64@1.20261012.1': - resolution: {integrity: sha512-uMe7ONHnLxStD1Ye0YFHBO36uj4cStv5P53rW+5GVWXFT8BRjqVixlH0IqCAHe1Pmcwyd1+7fVoGde89MZSCJg==} + '@cloudflare/workerd-linux-64@1.20261026.1': + resolution: {integrity: sha512-S65mog+1LKp5KT3u+Q3bWg7VQhqqfLL8aM2o2gfchbXwKOX13ZKWuCq4ZxTAxFhG7M31LfEL1iV6K+myFpjhaA==} engines: {node: '>=16'} cpu: [x64] os: [linux] - '@cloudflare/workerd-linux-arm64@1.20261012.1': - resolution: {integrity: sha512-I0VMdcXk7ygG5vYDce0ePTBFdnBXC0i9WiBY5mWiv0iTinbfea6/rHqSQ7B1UMpjgrYVs9E0m4bZ9ufsk5GCFA==} + '@cloudflare/workerd-linux-arm64@1.20261026.1': + resolution: {integrity: sha512-sM+rsagLWdSGb8GP5Qz40nmufbx8EawRD+jw+ySzdiv3owLOLlP0Z1Nzl4s5gtZ6OPCHSVsQxdWNCDfnJLbiVA==} engines: {node: '>=16'} cpu: [arm64] os: [linux] - '@cloudflare/workerd-windows-64@1.20261012.1': - resolution: {integrity: sha512-c5hQvNx574UEoknaCFvMa/NdLrrYiALNbe6sx1okW8uOiRYWxrFuA8WpXFnBJ5XJypm0TEAHYaUTGv3rRLpY7Q==} + '@cloudflare/workerd-windows-64@1.20261026.1': + resolution: {integrity: sha512-7T6udxUWajK0NIpLkmX5FU7i7MnoFYWA3CXmywvO1SmWdabuNCqcB4Wc+88QBIbYhbmAbW+7yfIe7No2nmdoSA==} engines: {node: '>=16'} cpu: [x64] os: [win32] @@ -3522,38 +3586,38 @@ packages: resolution: {integrity: sha512-bPlN9S9O1A0euCpEWE4qnvB5YDuyYVsUTrxSgmAM1Is0j4tICHoVyOVAXfWMP/kS9ZrjvyIXWV2PmomiAXXqOw==} engines: {node: '>=20.19.0'} - '@cursor/sdk-darwin-arm64@1.0.38': - resolution: {integrity: sha512-pXxj4pjbIoDo6ZjgksSf4VTD4EJz6BGDKvFjDVVUMg0PmLCVbceOnp0pqfRO8SVpdUSE45GFrXuLnSZgLag/xw==} + '@cursor/sdk-darwin-arm64@1.2.0': + resolution: {integrity: sha512-UkZ/RdxKCpOQ85nRgzSq+g0h+gIw36/lCEvQvomhs5EkSFZW3OwbeEzkAU3UYglZ7t3RNHj3mc5C5cdDtHguvw==} cpu: [arm64] os: [darwin] hasBin: true - '@cursor/sdk-darwin-x64@1.0.38': - resolution: {integrity: sha512-rutfTMq1f9WZckPFH8R5bzNzHaZg7I/TijVUkfD3GbqIqqc5OKHzdTMqZf+AFAqRDQccGJn4GLWcnQ9wTwIVNA==} + '@cursor/sdk-darwin-x64@1.2.0': + resolution: {integrity: sha512-mJTFdX+qv9dHAm59tT7uq7ci7+BDvFoNk4gdF2zGp9SLULicY+FdFD64p1qLen1bX5Y2soZaX5mWBy7BfObjcg==} cpu: [x64] os: [darwin] hasBin: true - '@cursor/sdk-linux-arm64@1.0.38': - resolution: {integrity: sha512-CqmUnM8W8W2mKucSrdHO0kn4ems82siWuo7kvVJvXCtPkaziVNC++dro5h9hSh2oVgRbB91sWQ4lzsHVIDpkvA==} + '@cursor/sdk-linux-arm64@1.2.0': + resolution: {integrity: sha512-Rs+cd5snuhxMAHkpqRfEGPB1qAsfqSOYJh5SOHZTOWy2LkRVO62WHwd4x80C2emj+dosTV5WAcuF2kMKKcrDJg==} cpu: [arm64] os: [linux] hasBin: true - '@cursor/sdk-linux-x64@1.0.38': - resolution: {integrity: sha512-RL6OJTAF3oozMG+HNtykySQ5BOP94yJNWP65wZ2yzMLTAW9ao80++OnaWJya1lndLacHLYP+QZT4igm5TT+BWQ==} + '@cursor/sdk-linux-x64@1.2.0': + resolution: {integrity: sha512-ainsGAFtkWTBZrLABp82Hvfv7VB/FxmZHE42qMVotFTRDwOY2iduvhSig910bVxv+kw3S00Srmu/9CxklLwhbw==} cpu: [x64] os: [linux] hasBin: true - '@cursor/sdk-win32-x64@1.0.38': - resolution: {integrity: sha512-IUfuCk/S/qzEB+tfT4yWH6iSMz56Lvakn1zNjdk+oAsZ7RJWtWkZcea6eqMSRB1WLmTeQG0uetXKX330w+xI0A==} + '@cursor/sdk-win32-x64@1.2.0': + resolution: {integrity: sha512-p3rkyta6R/nXIukd3/ifJq32otkkGoUi41T2jxnHbPHMhzE2F8OuJQGBVmORuQLMr+bIGGVZmCxertgs4WgzcQ==} cpu: [x64] os: [win32] hasBin: true - '@cursor/sdk@1.0.38': - resolution: {integrity: sha512-8UwPKaprIXvlVR71yHyNNTyFwZCOzfHW7W+FKjPdDS9Ym9FDZc51Jwsu9lAhxHf7n0US3t0pybkDaNFdldrQ+A==} + '@cursor/sdk@1.2.0': + resolution: {integrity: sha512-Nqm2U0zTWrYEDCv3Rdwsfa1gYZWsg+JnY+I2F8BwWSAr3FNo0TZWwyHWoWngZgriF1w02fJ4gjJWaul9zysvgQ==} engines: {node: '>=22.13'} peerDependencies: zod: ^3.25.0 || ^4.0.0 @@ -3574,40 +3638,45 @@ packages: '@dimforge/rapier3d-compat@0.12.0': resolution: {integrity: sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow==} - '@distilled.cloud/acme@1.0.0-rc.17': - resolution: {integrity: sha512-s6qWikqh+kdcl0dKOXvYS+++das2f073hkQtHZ9Htt7Oi0hcAFIk7i4is0h4GBjsJX/8bCx0D6EtUVeXUuQI9g==} + '@distilled.cloud/acme@1.0.0-rc.18': + resolution: {integrity: sha512-OWO6NG9IcpDqZCzlrN5T4MIQqSbpZ5cw61Ru/dYn1vr3AIyx3Vlg+Ew8NhlunpURr4wqDUW2/7QW3fKbrmfwLg==} + peerDependencies: + effect: 4.1.2 + + '@distilled.cloud/aws4signer@1.0.0-rc.18': + resolution: {integrity: sha512-eYJi2rsblwjxpa0kj2qUQYqY9cEwD6ow0njiFL6I5ZnlOqrE8I3aLiWvScoc3s9bQUQD5nFdmSnORoPJ5GsHKg==} peerDependencies: - effect: 4.0.5 + effect: 4.1.2 - '@distilled.cloud/aws4signer@1.0.0-rc.17': - resolution: {integrity: sha512-4wOoFuiadiKOEfDcL0VwGwg4XmZ3vmMxrNJAnTKf87k2WN2Shs7KeUp4GS1TzGGO3NrrpvVw8RFK+dOomDMj5w==} + '@distilled.cloud/aws@1.0.0-rc.18': + resolution: {integrity: sha512-VZDlOGEXvXvTdY/0sTEoTWnPCGde+fjvq1ZIW3wgiZK/X8ChbbonGArg+Sc9OO4E9tr1WBymASrZ906uLnLWFw==} peerDependencies: - effect: 4.0.5 + effect: 4.1.2 - '@distilled.cloud/axiom@1.0.0-rc.17': - resolution: {integrity: sha512-QRjfgxQsajursE+ar/urY1d3qrjmyjjZEnxNZnlJc7G/2o1p863ClcIwlyAe6u8CfeGf6HL/tc3GVmD4yHek2g==} + '@distilled.cloud/axiom@1.0.0-rc.18': + resolution: {integrity: sha512-8z6PPKm3OlEI9ovuSgqnQBYrGU5Fg8LVrk/Xs85NBDH8kJ69ttdJ8vaSb6hILi9hHluefvYO7SJ1XTOXxH+vCw==} peerDependencies: - effect: 4.0.5 + effect: 4.1.2 - '@distilled.cloud/cloudflare@1.0.0-rc.17': - resolution: {integrity: sha512-xT7EFAAUUd9AZetUjXsiwMkpGatdxGNuMZrhuX5cG4MicmJizn9gn5xdqNsojkj4qzv08qIVL9j1XGV20IoYuA==} + '@distilled.cloud/cloudflare@1.0.0-rc.18': + resolution: {integrity: sha512-UJB7pitkg7msm7BGTuAE8yYx4GzKdPLRtiOm3G3XHw07xLUlqEiEr4xpSf0CeziWzDygjI53FSkpC2qyVZr49g==} peerDependencies: - effect: 4.0.5 + effect: 4.1.2 - '@distilled.cloud/core@1.0.0-rc.17': - resolution: {integrity: sha512-BHcVEtqIbyyqU3S3o8DjUtqoAJ4FLnsb4BX3nTK2+mcDARS2Puc+Qak6sn+b+W5CRKOOWyrhltbc+kaYDUwxeQ==} + '@distilled.cloud/core@1.0.0-rc.18': + resolution: {integrity: sha512-Iui60+sNl1CwUu7NKGLuFf3VC4H9xYzfm0Fc8ZQvd87qwf1sDMB3EAWZrq/QFgrwzSY16z2mJ0PNHaBUnGet8A==} peerDependencies: - effect: 4.0.5 + effect: 4.1.2 - '@distilled.cloud/iceberg@1.0.0-rc.17': - resolution: {integrity: sha512-hO9Kqc91dq7SLBCagxlr2RDSTbp7/urqjfxNitSNaaOyKIsUr85llsADT/rS6H85ezOsGf2vSP5y1Qk0kQWLCg==} + '@distilled.cloud/iceberg@1.0.0-rc.18': + resolution: {integrity: sha512-XjUJ/vEOylhIZbAm85O9H6YqXKWGfVROT5BE9BGA/RXvo0bLK2+sUcjC6BoN77a99lImJkrXJuvbHBhNebObEA==} peerDependencies: - effect: 4.0.5 + effect: 4.1.2 - '@distilled.cloud/planetscale@1.0.0-rc.17': - resolution: {integrity: sha512-njhj8KAcjSUShf5WK1J7GaLQb496QefHgKBQnQ5g+AJr0u9VPYcugdhuslWsd+L634GL13IHjXVnB2Fp36uy9w==} + '@distilled.cloud/planetscale@1.0.0-rc.18': + resolution: {integrity: sha512-GSpQVfwYq2QKjjQpjiMl4IUBgyS7doNX4mnIzIRzM44BMMtTwx0gMcBj7b7PVAA0O7MyKLKV134Ba1+w3u71kw==} peerDependencies: - effect: 4.0.5 + effect: 4.1.2 '@dnd-kit/accessibility@3.1.1': resolution: {integrity: sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==} @@ -3640,64 +3709,64 @@ packages: '@drizzle-team/brocli@0.12.0': resolution: {integrity: sha512-mlUE+rZ8CatQekLhnaiN91Iemdd+e2gFKooGlnRB3oPTL3VghLfX24dx7HrzMNeC1JrIB/0kpsfyty3f5HNfxQ==} - '@effect/atom-react@4.0.5': - resolution: {integrity: sha512-tqTSiy0rWBitej7kPfvTSw29q4ipof52+txDg6bIBJx0ksHVzVXaFTsssDa+AZBeImafK0xmjm9m1XzPfE6k2A==} + '@effect/atom-react@4.1.2': + resolution: {integrity: sha512-XRAm4lks2kzNFQIz9QTGKR02CaDTR9VJNRXDjDAR8OzM15ybrK4YkB7OlFZ9U+hxXe3DXJZx7RU1/xI2Em2PGQ==} peerDependencies: - effect: 4.0.5 + effect: 4.1.2 react: '>=19.0.0 <20.0.0' scheduler: '>=0.25.0 <0.29.0' - '@effect/graphql-generator@4.0.5': - resolution: {integrity: sha512-2QtEQxP4RRANWVJVe/wQBmG6SGePDfhgqpOeyfa7JlTsbnJbf3J25lmTz/faO3fGgicTVTTMruHTY6CR16KILg==} + '@effect/graphql-generator@4.1.2': + resolution: {integrity: sha512-V6y46lsINE3mHzNTYlYY4UA5RJZkywYAorPL0Bl7U4ggGk8P8gqVcc8iGnUoHzlR97TKbNucOSYvCiFv2oidVg==} hasBin: true peerDependencies: - '@effect/platform-node': 4.0.5 - effect: 4.0.5 + '@effect/platform-node': 4.1.2 + effect: 4.1.2 - '@effect/openapi-generator@4.0.5': - resolution: {integrity: sha512-pksR5BhRKQQfDcpA8AbxCiAFLAbdnZseiRmgr1UtVi1x/IyEuS8WmXoFD1C424TEyS+n2Q6lPpR0ue/WQ743aw==} + '@effect/openapi-generator@4.1.2': + resolution: {integrity: sha512-seh1li7cp6XE734rWmsQ/lQ2RFp1YCMb1PP6pZ7CvFAeoAUsgM4J2z8iCllY8yE2VnswWWw9GQ/XKHLm/gpGzg==} hasBin: true peerDependencies: - '@effect/platform-node': 4.0.5 - effect: 4.0.5 + '@effect/platform-node': 4.1.2 + effect: 4.1.2 - '@effect/platform-node-shared@4.0.5': - resolution: {integrity: sha512-a8rCdEkfZBGe9C6bsIjxVZuRp73svIyK5IHwHdDAVsvZXjrbkxusfI+rZ8WlX31RP1mKizwI/E72GQTNfdMWHw==} - engines: {node: '>=18.0.0'} + '@effect/platform-bun@4.1.2': + resolution: {integrity: sha512-waEAa84CITqjctgw9VdhlL9PyXRHICG3KAWTFRDPUE2XL/pfMPhO7V9oFdfx22dbAhhUzV+MHs0d9hnmy/DQ7w==} peerDependencies: - effect: 4.0.5 + effect: 4.1.2 - '@effect/platform-node@4.0.5': - resolution: {integrity: sha512-v4KD5fWvEUa4QmWFpZFbBsRhmfnTP6ETCME2r9ifyXVDPjhfpxpTZl41prjgQFMqZBHdWWCl7YC5ImbXv5ui5g==} - engines: {node: '>=18.0.0'} + '@effect/platform-node-shared@4.1.2': + resolution: {integrity: sha512-wSwl9A/G1hcVvF8nLI+YfB3EyOIDvWS6+lsTZBkmgDnPBL7m8YWZF+1HD+mdEsb52SUGfukip46Q3gRwSdk3QA==} + engines: {node: '>=22.19.0'} peerDependencies: - effect: 4.0.5 - redis: '>=5.0.0 <7.0.0' + effect: 4.1.2 - '@effect/sql-d1@4.0.6': - resolution: {integrity: sha512-W149Svo5pR+7eoKtTmMX3aFCJKQmvMdypKhMlFekKvy2UjY6h5Af8d+9YeBeOXkYtDQjxNs4l6iv7EqbF6XBbg==} + '@effect/platform-node@4.1.2': + resolution: {integrity: sha512-ye0UjxORdd5Qu3paZ1LljgGOALWHt7muP9VTpjUSCNfcesiB/Hm7wPJIvZeu4gnwpTe5BtEnO1VHngWqjJp8mA==} + engines: {node: '>=22.19.0'} peerDependencies: - effect: 4.0.5 + effect: 4.1.2 + redis: '>=5.1.0 <7.0.0' - '@effect/sql-pg@4.0.5': - resolution: {integrity: sha512-F9tG76H+aryhYcp5pvgd+MwWrNltv3XAuLcZSBsOOX6q+PEl+IM4zkQKzx0TF9OsEMH/SQ+3gZRdYWOsDF+vJQ==} + '@effect/sql-d1@4.1.1': + resolution: {integrity: sha512-CQMOiw9bmj4ifsUA4KLwIgBJBMpPHaF3OYdXnA9oOxeEmD61+XDLkJUSA2mG7BWCIEZc7MquGxl3HuUVOeqtSA==} peerDependencies: - effect: 4.0.5 + effect: 4.1.2 - '@effect/sql-sqlite-bun@4.0.0-rc.112': - resolution: {integrity: sha512-EqR8pWZo3VzedRvP6qo5HcfqNmFvSa+sQLWQl3oBMx2KY1FCc8NYjep79wYjNkW0qABnffrPUXCMTOncd1A+5g==} + '@effect/sql-pg@4.1.2': + resolution: {integrity: sha512-0UehR7B5W8dC+dX6fDeWStLbVbBb2M4pk4HBATEeH0cmV4Odl2lckTg0jFmLuadekTLa4OyB+bZQo1yTG1y2Mw==} peerDependencies: - effect: 4.0.5 + effect: 4.1.2 - '@effect/sql-sqlite-do@4.0.5': - resolution: {integrity: sha512-TGlU65ZJJMa81I7EoicQXxhRsJDxDPz6A/PNOPzMYRgmCdLs6EsTTXIkKZ+8apb7pl2o0OKVcrT6i6mGlluyLg==} + '@effect/sql-sqlite-do@4.1.2': + resolution: {integrity: sha512-1qlYhIvNsvYxvfp1183FPMGnHN/9TAGtlMLsBB7OrVE5R/9bWnWyahMxGID79sJ6csW3Azeyxk3ZwRdWXLvNTQ==} peerDependencies: - effect: 4.0.5 + effect: 4.1.2 - '@effect/vitest@4.0.5': - resolution: {integrity: sha512-q64paZ/i4V2NiRhTyqCmT2KiDbFjlxc2EZrZca8GGt+Nf8844946HyJM5bPk/q+YeRkFSxIrlCs+J+LSfky/wA==} + '@effect/vitest@4.1.2': + resolution: {integrity: sha512-JJPwAHkJHxvM/woW9mMW/khjasAHcmwWdOMAgMy16rfqsxcVhFDnrRsvN9VI2+kMv8zDCCyBE2q1n5hzZlfE0w==} peerDependencies: - effect: 4.0.5 + effect: 4.1.2 '@electric-sql/pglite@0.3.15': resolution: {integrity: sha512-Cj++n1Mekf9ETfdc16TlDi+cDDQF0W7EcbyRHYOAeZdsAe8M/FJg18itDTSwyHfar2WIezawM9o0EKaRGVKygQ==} @@ -5167,7 +5236,7 @@ packages: '@opencode/client@2.0.28': resolution: {integrity: sha512-YV0Yxk93/K2h4Xy/sEW/4ZYGMwn7ltxG2Y/Vdy2VCIZ2z0/r9MI6x5/XawSNfCvImBxuHkQNbYtu9Rgp3ArJ4g==} peerDependencies: - effect: 4.0.5 + effect: 4.1.2 solid-js: '>=1.9.0' peerDependenciesMeta: effect: @@ -7566,16 +7635,15 @@ packages: ajv@8.20.0: resolution: {integrity: sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==} - alchemy@2.0.0-beta.84: - resolution: {integrity: sha512-GAcfT/fvolC5C4t6yKx2P3e4rYmaM3aXhtnwK2FnGDFUCdv5zIQatiVXtoNuABzFgMn6UIj9jxrCWWweXoWgmA==} + alchemy@2.0.0-beta.85: + resolution: {integrity: sha512-dRSyfVDfU3wevBT0Iam6PUjQTn6PY6Lyd2BOeg9ToE208ifrx0sdmNUag8lLeiHisxlhaJJRyOtqKcWZ7lY0Pw==} hasBin: true peerDependencies: - '@alchemy.run/frontend-frameworks': 2.0.0-beta.84 - '@effect/platform-bun': ^4.0.5 - '@effect/platform-node': 4.0.5 - '@effect/vitest': 4.0.5 - effect: 4.0.5 - vite: ^8.0.7 + '@alchemy.run/frontend-frameworks': 2.0.0-beta.85 + '@effect/platform-bun': 4.1.2 + '@effect/platform-node': 4.1.2 + effect: 4.1.2 + vite: ^7.0.0 || ^8.0.0 ws: 8.22.0 peerDependenciesMeta: '@alchemy.run/frontend-frameworks': @@ -7584,8 +7652,6 @@ packages: optional: true '@effect/platform-node': optional: true - '@effect/vitest': - optional: true vite: optional: true ws: @@ -8391,7 +8457,7 @@ packages: '@effect/sql-d1': '>=4.0.0-beta.105 || >=4.0.0' '@effect/sql-libsql': '>=4.0.0-beta.105 || >=4.0.0' '@effect/sql-mysql2': '>=4.0.0-beta.105 || >=4.0.0' - '@effect/sql-pg': 4.0.5 + '@effect/sql-pg': 4.1.2 '@effect/sql-pglite': '>=4.0.0-beta.105 || >=4.0.0' '@effect/sql-sqlite-bun': '>=4.0.0-beta.105 || >=4.0.0' '@effect/sql-sqlite-do': '>=4.0.0-beta.105 || >=4.0.0' @@ -8422,7 +8488,7 @@ packages: arktype: '>=2.0.0' better-sqlite3: '>=9.3.0' bun-types: '*' - effect: 4.0.5 + effect: 4.1.2 expo-sqlite: '>=14.0.0' minipg: '>=0.2.0' mssql: ^11.0.1 @@ -8549,8 +8615,8 @@ packages: ee-first@1.1.1: resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==} - effect@4.0.5: - resolution: {integrity: sha512-BY4/28NlpOd99yzmV741xbVGmp+1U7tks4oB7F/Png64bTa5tm5eCA6W0RiXsnuLDDoJpjfVSo4Dnq4BZb/89Q==} + effect@4.1.2: + resolution: {integrity: sha512-d3Oah1WyKxFLFh19yWheS5IXIVaITzxZ71JkE1rkUozq/6EcJSU5nPk5bF2QrSygZ3SQoiNQB8TsxFriyMeMaQ==} ejs@3.1.10: resolution: {integrity: sha512-UeJmFfOrAQS8OJWPZ4qtgHyWExa088/MtK5UEyoJGFH67cDEXkZSviOiKRCZ4Xij0zxI3JECgYs3oKx+AizQBA==} @@ -12285,8 +12351,8 @@ packages: engines: {node: '>=20.11'} hasBin: true - workerd@1.20261012.1: - resolution: {integrity: sha512-tEHoMPsMga0seVjxfsR8Pd3f8IRqYwkq++dTUKI5Gdgj6zuSDluYwisydq+dn90SsIACwBquJUQ1nBpcOqaWTA==} + workerd@1.20261026.1: + resolution: {integrity: sha512-zMkGDn4DHj7AEDrD0FT3VuaVf9QKWbE3Xg6j8oGt1vE+UtDY5gubW5jcyEYXULy5ojCYwVbmEyDkiukWY7gtVg==} engines: {node: '>=16'} hasBin: true @@ -12484,35 +12550,36 @@ snapshots: dependencies: json-schema: 0.4.0 - '@alchemy.run/acme@2.0.0-beta.84(74118100341fd69edb1510aa7b7f1bd2)': + '@alchemy.run/acme@2.0.0-beta.85(alchemy@2.0.0-beta.85(@effect/platform-bun@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.2)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.2)': dependencies: - '@distilled.cloud/acme': 1.0.0-rc.17(effect@4.0.5) - alchemy: 2.0.0-beta.84(patch_hash=824006659fa28ca31e490ce1fc3611f77436005ce9fa0f638be46564133cf042)(@effect/platform-node@4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@effect/vitest@4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(effect@4.0.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.0.5 + '@distilled.cloud/acme': 1.0.0-rc.18(effect@4.1.2) + alchemy: 2.0.0-beta.85(@effect/platform-bun@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.2)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.2 - '@alchemy.run/axiom@2.0.0-beta.84(74118100341fd69edb1510aa7b7f1bd2)': + '@alchemy.run/axiom@2.0.0-beta.85(alchemy@2.0.0-beta.85(@effect/platform-bun@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.2)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.2)': dependencies: - '@distilled.cloud/axiom': 1.0.0-rc.17(effect@4.0.5) - '@distilled.cloud/core': 1.0.0-rc.17(effect@4.0.5) - alchemy: 2.0.0-beta.84(patch_hash=824006659fa28ca31e490ce1fc3611f77436005ce9fa0f638be46564133cf042)(@effect/platform-node@4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@effect/vitest@4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(effect@4.0.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.0.5 + '@distilled.cloud/axiom': 1.0.0-rc.18(effect@4.1.2) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.2) + alchemy: 2.0.0-beta.85(@effect/platform-bun@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.2)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.2 - '@alchemy.run/cloudflare-runtime@2.0.0-beta.84(@distilled.cloud/cloudflare@1.0.0-rc.17(effect@4.0.5))(@effect/platform-node@4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(effect@4.0.5)(rolldown@1.2.13)': + '@alchemy.run/cloudflare-runtime@2.0.0-beta.85(@distilled.cloud/cloudflare@1.0.0-rc.18(effect@4.1.2))(@effect/platform-bun@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6))(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.2)(rolldown@1.2.13)': dependencies: - '@alchemy.run/node-utils': 2.0.0-beta.84 - '@cloudflare/unenv-preset': 2.16.2(unenv@2.0.0-rc.24)(workerd@1.20261012.1) - '@distilled.cloud/cloudflare': 1.0.0-rc.17(effect@4.0.5) + '@alchemy.run/node-utils': 2.0.0-beta.85 + '@cloudflare/unenv-preset': 2.16.2(unenv@2.0.0-rc.24)(workerd@1.20261026.1) + '@distilled.cloud/cloudflare': 1.0.0-rc.18(effect@4.1.2) '@puppeteer/browsers': 3.2.6(yauzl@3.4.0) capnp-es: 0.0.16(@tsc-rs/typescript@0.8.0) - effect: 4.0.5 + effect: 4.1.2 magic-string: 0.30.21 mime: 4.1.1 sharp: 0.35.5(@types/node@24.12.4) unenv: 2.0.0-rc.24 - workerd: 1.20261012.1 + workerd: 1.20261026.1 yauzl: 3.4.0 optionalDependencies: - '@effect/platform-node': 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6) + '@effect/platform-bun': 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6) + '@effect/platform-node': 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) rolldown: 1.2.13 vite: '@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0)' transitivePeerDependencies: @@ -12520,24 +12587,27 @@ snapshots: - proxy-agent - typescript - '@alchemy.run/cloudflare@2.0.0-beta.84(24ce6902b7189b66a257867375b8f56d)': - dependencies: - '@alchemy.run/acme': 2.0.0-beta.84(74118100341fd69edb1510aa7b7f1bd2) - '@alchemy.run/cloudflare-runtime': 2.0.0-beta.84(@distilled.cloud/cloudflare@1.0.0-rc.17(effect@4.0.5))(@effect/platform-node@4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(effect@4.0.5)(rolldown@1.2.13) - '@alchemy.run/docker': 2.0.0-beta.84(74118100341fd69edb1510aa7b7f1bd2) - '@alchemy.run/sql': 2.0.0-beta.84(1b64d144d22bc50b8239f5331dd49513) - '@distilled.cloud/aws4signer': 1.0.0-rc.17(effect@4.0.5) - '@distilled.cloud/cloudflare': 1.0.0-rc.17(effect@4.0.5) - '@distilled.cloud/core': 1.0.0-rc.17(effect@4.0.5) - '@distilled.cloud/iceberg': 1.0.0-rc.17(effect@4.0.5) - '@effect/sql-d1': 4.0.6(effect@4.0.5) - alchemy: 2.0.0-beta.84(patch_hash=824006659fa28ca31e490ce1fc3611f77436005ce9fa0f638be46564133cf042)(@effect/platform-node@4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@effect/vitest@4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(effect@4.0.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.0.5 + '@alchemy.run/cloudflare@2.0.0-beta.85(3c6bb1d0d4de1cb5d4932cf1224d79e6)': + dependencies: + '@alchemy.run/acme': 2.0.0-beta.85(alchemy@2.0.0-beta.85(@effect/platform-bun@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.2)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.2) + '@alchemy.run/cloudflare-runtime': 2.0.0-beta.85(@distilled.cloud/cloudflare@1.0.0-rc.18(effect@4.1.2))(@effect/platform-bun@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6))(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.2)(rolldown@1.2.13) + '@alchemy.run/docker': 2.0.0-beta.85(@effect/platform-bun@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6))(alchemy@2.0.0-beta.85(@effect/platform-bun@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.2)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.2) + '@alchemy.run/sql': 2.0.0-beta.85(@effect/sql-pg@4.1.2(effect@4.1.2))(alchemy@2.0.0-beta.85(@effect/platform-bun@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.2)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.2)(pg@8.23.0) + '@distilled.cloud/aws': 1.0.0-rc.18(effect@4.1.2) + '@distilled.cloud/aws4signer': 1.0.0-rc.18(effect@4.1.2) + '@distilled.cloud/cloudflare': 1.0.0-rc.18(effect@4.1.2) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.2) + '@distilled.cloud/iceberg': 1.0.0-rc.18(effect@4.1.2) + '@effect/sql-d1': 4.1.1(effect@4.1.2) + alchemy: 2.0.0-beta.85(@effect/platform-bun@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.2)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.2 pathe: 2.0.3 + picomatch: 4.0.7 rolldown: 1.2.13 tinyglobby: 0.2.17 optionalDependencies: - '@effect/platform-node': 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6) + '@effect/platform-bun': 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6) + '@effect/platform-node': 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) vite: '@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0)' transitivePeerDependencies: - '@effect/sql-libsql' @@ -12549,40 +12619,42 @@ snapshots: - proxy-agent - typescript - '@alchemy.run/docker@2.0.0-beta.84(74118100341fd69edb1510aa7b7f1bd2)': + '@alchemy.run/docker@2.0.0-beta.85(@effect/platform-bun@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6))(alchemy@2.0.0-beta.85(@effect/platform-bun@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.2)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.2)': dependencies: - alchemy: 2.0.0-beta.84(patch_hash=824006659fa28ca31e490ce1fc3611f77436005ce9fa0f638be46564133cf042)(@effect/platform-node@4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@effect/vitest@4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(effect@4.0.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.0.5 + alchemy: 2.0.0-beta.85(@effect/platform-bun@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.2)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.2 rolldown: 1.2.13 + optionalDependencies: + '@effect/platform-bun': 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6) - '@alchemy.run/drizzle@2.0.0-beta.84(621723465c0c1236eb5d87515baf6818)': + '@alchemy.run/drizzle@2.0.0-beta.85(0f2f0b2f6e85ad5bbc9df78a7c15a609)': dependencies: - '@alchemy.run/sql': 2.0.0-beta.84(1b64d144d22bc50b8239f5331dd49513) - '@effect/sql-d1': 4.0.6(effect@4.0.5) - '@effect/sql-sqlite-do': 4.0.5(effect@4.0.5) - alchemy: 2.0.0-beta.84(patch_hash=824006659fa28ca31e490ce1fc3611f77436005ce9fa0f638be46564133cf042)(@effect/platform-node@4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@effect/vitest@4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(effect@4.0.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - drizzle-orm: 1.0.0-rc.5-ab785fc(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.0.6(effect@4.0.5))(@effect/sql-pg@4.0.5(effect@4.0.5))(@effect/sql-sqlite-bun@4.0.0-rc.112(effect@4.0.5))(@effect/sql-sqlite-do@4.0.5(effect@4.0.5))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.0.5)(expo-sqlite@58.0.13(expo@58.0.14)(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.5) - effect: 4.0.5 + '@alchemy.run/sql': 2.0.0-beta.85(@effect/sql-pg@4.1.2(effect@4.1.2))(alchemy@2.0.0-beta.85(@effect/platform-bun@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.2)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.2)(pg@8.23.0) + '@effect/sql-d1': 4.1.1(effect@4.1.2) + '@effect/sql-sqlite-do': 4.1.2(effect@4.1.2) + alchemy: 2.0.0-beta.85(@effect/platform-bun@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.2)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + drizzle-orm: 1.0.0-rc.5-ab785fc(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.2))(@effect/sql-pg@4.1.2(effect@4.1.2))(@effect/sql-sqlite-do@4.1.2(effect@4.1.2))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.2)(expo-sqlite@58.0.13(expo@58.0.14)(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.5) + effect: 4.1.2 optionalDependencies: - '@alchemy.run/cloudflare': 2.0.0-beta.84(24ce6902b7189b66a257867375b8f56d) - '@effect/sql-pg': 4.0.5(effect@4.0.5) + '@alchemy.run/cloudflare': 2.0.0-beta.85(3c6bb1d0d4de1cb5d4932cf1224d79e6) + '@effect/sql-pg': 4.1.2(effect@4.1.2) drizzle-kit: 1.0.0-rc.5-ab785fc transitivePeerDependencies: - mysql2 - pg - '@alchemy.run/node-utils@2.0.0-beta.84': + '@alchemy.run/node-utils@2.0.0-beta.85': dependencies: chokidar: 5.0.0 rolldown: 1.2.13 - '@alchemy.run/planetscale@2.0.0-beta.84(1b64d144d22bc50b8239f5331dd49513)': + '@alchemy.run/planetscale@2.0.0-beta.85(@effect/sql-pg@4.1.2(effect@4.1.2))(alchemy@2.0.0-beta.85(@effect/platform-bun@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.2)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.2)(pg@8.23.0)': dependencies: - '@alchemy.run/sql': 2.0.0-beta.84(1b64d144d22bc50b8239f5331dd49513) - '@distilled.cloud/core': 1.0.0-rc.17(effect@4.0.5) - '@distilled.cloud/planetscale': 1.0.0-rc.17(effect@4.0.5) - alchemy: 2.0.0-beta.84(patch_hash=824006659fa28ca31e490ce1fc3611f77436005ce9fa0f638be46564133cf042)(@effect/platform-node@4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@effect/vitest@4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(effect@4.0.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.0.5 + '@alchemy.run/sql': 2.0.0-beta.85(@effect/sql-pg@4.1.2(effect@4.1.2))(alchemy@2.0.0-beta.85(@effect/platform-bun@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.2)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.2)(pg@8.23.0) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.2) + '@distilled.cloud/planetscale': 1.0.0-rc.18(effect@4.1.2) + alchemy: 2.0.0-beta.85(@effect/platform-bun@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.2)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.2 optionalDependencies: pg: 8.23.0 transitivePeerDependencies: @@ -12595,15 +12667,27 @@ snapshots: '@types/react': 19.3.0 react-devtools-core: 6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6) - '@alchemy.run/sql@2.0.0-beta.84(1b64d144d22bc50b8239f5331dd49513)': + '@alchemy.run/sql@2.0.0-beta.85(@effect/sql-pg@4.1.2(effect@4.1.2))(alchemy@2.0.0-beta.85(@effect/platform-bun@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.2)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.2)(pg@8.23.0)': dependencies: - alchemy: 2.0.0-beta.84(patch_hash=824006659fa28ca31e490ce1fc3611f77436005ce9fa0f638be46564133cf042)(@effect/platform-node@4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@effect/vitest@4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(effect@4.0.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.0.5 + alchemy: 2.0.0-beta.85(@effect/platform-bun@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.2)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.2 optionalDependencies: - '@effect/sql-pg': 4.0.5(effect@4.0.5) + '@effect/sql-pg': 4.1.2(effect@4.1.2) pg: 8.23.0 - '@anthropic-ai/claude-agent-sdk@0.3.276(@anthropic-ai/sdk@0.93.0(zod@4.6.5))(@modelcontextprotocol/sdk@1.29.0(supports-color@8.1.1)(zod@4.6.5))(zod@4.6.5)': + '@alchemy.run/test@2.0.0-beta.85(patch_hash=29c0539ea71d9cc372f0b16558640599beb9bc609605feb2a493da268d72713e)(071253407c4f3cb63d401833ee1dda26)': + dependencies: + '@effect/platform-bun': 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6) + effect: 4.1.2 + optionalDependencies: + '@effect/vitest': 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.1.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + alchemy: 2.0.0-beta.85(@effect/platform-bun@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.2)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + vitest: 5.0.5(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/browser-preview@5.0.5)(@vitest/ui@5.0.5)(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0) + transitivePeerDependencies: + - bufferutil + - utf-8-validate + + '@anthropic-ai/claude-agent-sdk@0.3.284(@anthropic-ai/sdk@0.93.0(zod@4.6.5))(@modelcontextprotocol/sdk@1.29.0(supports-color@8.1.1)(zod@4.6.5))(zod@4.6.5)': dependencies: '@anthropic-ai/sdk': 0.93.0(zod@4.6.5) '@modelcontextprotocol/sdk': 1.29.0(supports-color@8.1.1)(zod@4.6.5) @@ -13436,25 +13520,25 @@ snapshots: react: 19.3.0 react-dom: 19.3.0(react@19.3.0) - '@cloudflare/unenv-preset@2.16.2(unenv@2.0.0-rc.24)(workerd@1.20261012.1)': + '@cloudflare/unenv-preset@2.16.2(unenv@2.0.0-rc.24)(workerd@1.20261026.1)': dependencies: unenv: 2.0.0-rc.24 optionalDependencies: - workerd: 1.20261012.1 + workerd: 1.20261026.1 - '@cloudflare/workerd-darwin-64@1.20261012.1': + '@cloudflare/workerd-darwin-64@1.20261026.1': optional: true - '@cloudflare/workerd-darwin-arm64@1.20261012.1': + '@cloudflare/workerd-darwin-arm64@1.20261026.1': optional: true - '@cloudflare/workerd-linux-64@1.20261012.1': + '@cloudflare/workerd-linux-64@1.20261026.1': optional: true - '@cloudflare/workerd-linux-arm64@1.20261012.1': + '@cloudflare/workerd-linux-arm64@1.20261026.1': optional: true - '@cloudflare/workerd-windows-64@1.20261012.1': + '@cloudflare/workerd-windows-64@1.20261026.1': optional: true '@cloudflare/workers-types@4.20260604.1': {} @@ -13525,22 +13609,22 @@ snapshots: '@csstools/css-tokenizer@4.0.1': {} - '@cursor/sdk-darwin-arm64@1.0.38': + '@cursor/sdk-darwin-arm64@1.2.0': optional: true - '@cursor/sdk-darwin-x64@1.0.38': + '@cursor/sdk-darwin-x64@1.2.0': optional: true - '@cursor/sdk-linux-arm64@1.0.38': + '@cursor/sdk-linux-arm64@1.2.0': optional: true - '@cursor/sdk-linux-x64@1.0.38': + '@cursor/sdk-linux-x64@1.2.0': optional: true - '@cursor/sdk-win32-x64@1.0.38': + '@cursor/sdk-win32-x64@1.2.0': optional: true - '@cursor/sdk@1.0.38(zod@4.6.5)': + '@cursor/sdk@1.2.0(zod@4.6.5)': dependencies: '@bufbuild/protobuf': 1.10.0 '@connectrpc/connect': 1.7.0(@bufbuild/protobuf@1.10.0) @@ -13548,11 +13632,11 @@ snapshots: '@statsig/js-client': 3.31.0 zod: 4.6.5 optionalDependencies: - '@cursor/sdk-darwin-arm64': 1.0.38 - '@cursor/sdk-darwin-x64': 1.0.38 - '@cursor/sdk-linux-arm64': 1.0.38 - '@cursor/sdk-linux-x64': 1.0.38 - '@cursor/sdk-win32-x64': 1.0.38 + '@cursor/sdk-darwin-arm64': 1.2.0 + '@cursor/sdk-darwin-x64': 1.2.0 + '@cursor/sdk-linux-arm64': 1.2.0 + '@cursor/sdk-linux-x64': 1.2.0 + '@cursor/sdk-win32-x64': 1.2.0 '@date-fns/tz@1.5.0': {} @@ -13565,39 +13649,45 @@ snapshots: '@dimforge/rapier3d-compat@0.12.0': {} - '@distilled.cloud/acme@1.0.0-rc.17(effect@4.0.5)': + '@distilled.cloud/acme@1.0.0-rc.18(effect@4.1.2)': dependencies: - '@distilled.cloud/core': 1.0.0-rc.17(effect@4.0.5) - effect: 4.0.5 + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.2) + effect: 4.1.2 - '@distilled.cloud/aws4signer@1.0.0-rc.17(effect@4.0.5)': + '@distilled.cloud/aws4signer@1.0.0-rc.18(effect@4.1.2)': dependencies: - '@distilled.cloud/core': 1.0.0-rc.17(effect@4.0.5) - effect: 4.0.5 + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.2) + effect: 4.1.2 - '@distilled.cloud/axiom@1.0.0-rc.17(effect@4.0.5)': + '@distilled.cloud/aws@1.0.0-rc.18(effect@4.1.2)': dependencies: - '@distilled.cloud/core': 1.0.0-rc.17(effect@4.0.5) - effect: 4.0.5 + '@distilled.cloud/aws4signer': 1.0.0-rc.18(effect@4.1.2) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.2) + effect: 4.1.2 - '@distilled.cloud/cloudflare@1.0.0-rc.17(effect@4.0.5)': + '@distilled.cloud/axiom@1.0.0-rc.18(effect@4.1.2)': dependencies: - '@distilled.cloud/core': 1.0.0-rc.17(effect@4.0.5) - effect: 4.0.5 + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.2) + effect: 4.1.2 - '@distilled.cloud/core@1.0.0-rc.17(effect@4.0.5)': + '@distilled.cloud/cloudflare@1.0.0-rc.18(effect@4.1.2)': dependencies: - effect: 4.0.5 + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.2) + effect: 4.1.2 - '@distilled.cloud/iceberg@1.0.0-rc.17(effect@4.0.5)': + '@distilled.cloud/core@1.0.0-rc.18(effect@4.1.2)': dependencies: - '@distilled.cloud/core': 1.0.0-rc.17(effect@4.0.5) - effect: 4.0.5 + effect: 4.1.2 - '@distilled.cloud/planetscale@1.0.0-rc.17(effect@4.0.5)': + '@distilled.cloud/iceberg@1.0.0-rc.18(effect@4.1.2)': dependencies: - '@distilled.cloud/core': 1.0.0-rc.17(effect@4.0.5) - effect: 4.0.5 + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.2) + effect: 4.1.2 + + '@distilled.cloud/planetscale@1.0.0-rc.18(effect@4.1.2)': + dependencies: + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.2) + effect: 4.1.2 '@dnd-kit/accessibility@3.1.1(react@19.3.0)': dependencies: @@ -13633,65 +13723,68 @@ snapshots: '@drizzle-team/brocli@0.12.0': {} - '@effect/atom-react@4.0.5(effect@4.0.5)(react@19.3.0)(scheduler@0.28.0)': + '@effect/atom-react@4.1.2(effect@4.1.2)(react@19.3.0)(scheduler@0.28.0)': dependencies: - effect: 4.0.5 + effect: 4.1.2 react: 19.3.0 scheduler: 0.28.0 - '@effect/graphql-generator@4.0.5(@effect/platform-node@4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.0.5)': + '@effect/graphql-generator@4.1.2(@effect/platform-node@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.2)': dependencies: - '@effect/platform-node': 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6) - effect: 4.0.5 + '@effect/platform-node': 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) + effect: 4.1.2 - '@effect/openapi-generator@4.0.5(@effect/platform-node@4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.0.5)(encoding@0.1.13)': + '@effect/openapi-generator@4.1.2(@effect/platform-node@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.2)(encoding@0.1.13)': dependencies: - '@effect/platform-node': 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6) - effect: 4.0.5 + '@effect/platform-node': 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) + effect: 4.1.2 swagger2openapi: 7.0.8(encoding@0.1.13) transitivePeerDependencies: - encoding - '@effect/platform-node-shared@4.0.5(bufferutil@4.1.0)(effect@4.0.5)(utf-8-validate@6.0.6)': + '@effect/platform-bun@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6)': + dependencies: + '@effect/platform-node-shared': 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6) + effect: 4.1.2 + transitivePeerDependencies: + - bufferutil + - utf-8-validate + + '@effect/platform-node-shared@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6)': dependencies: '@types/ws': 8.18.2 - effect: 4.0.5 + effect: 4.1.2 ws: 8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6) transitivePeerDependencies: - bufferutil - utf-8-validate - '@effect/platform-node@4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6)': + '@effect/platform-node@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6)': dependencies: - '@effect/platform-node-shared': 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(utf-8-validate@6.0.6) - effect: 4.0.5 + '@effect/platform-node-shared': 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6) + effect: 4.1.2 redis: 6.2.1 undici: 8.11.2 transitivePeerDependencies: - bufferutil - utf-8-validate - '@effect/sql-d1@4.0.6(effect@4.0.5)': + '@effect/sql-d1@4.1.1(effect@4.1.2)': dependencies: '@cloudflare/workers-types': 5.20261026.1 - effect: 4.0.5 + effect: 4.1.2 - '@effect/sql-pg@4.0.5(effect@4.0.5)': + '@effect/sql-pg@4.1.2(effect@4.1.2)': dependencies: - effect: 4.0.5 - - '@effect/sql-sqlite-bun@4.0.0-rc.112(effect@4.0.5)': - dependencies: - effect: 4.0.5 - optional: true + effect: 4.1.2 - '@effect/sql-sqlite-do@4.0.5(effect@4.0.5)': + '@effect/sql-sqlite-do@4.1.2(effect@4.1.2)': dependencies: - effect: 4.0.5 + effect: 4.1.2 - '@effect/vitest@4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0)': + '@effect/vitest@4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.1.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0)': dependencies: - effect: 4.0.5 + effect: 4.1.2 vite-plus: 1.4.0(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) transitivePeerDependencies: - '@arethetypeswrong/core' @@ -15145,22 +15238,22 @@ snapshots: dependencies: cross-spawn: 7.0.6 - '@opencode/client@2.0.28(effect@4.0.5)': + '@opencode/client@2.0.28(effect@4.1.2)': dependencies: '@opencode/protocol': 2.0.28 '@opencode/schema': 2.0.28 optionalDependencies: - effect: 4.0.5 + effect: 4.1.2 '@opencode/protocol@2.0.28': dependencies: '@opencode/schema': 2.0.28 - effect: 4.0.5 + effect: 4.1.2 '@opencode/schema@2.0.28': dependencies: '@standard-schema/spec': 1.1.0 - effect: 4.0.5 + effect: 4.1.2 '@oslojs/asn1@1.0.0': dependencies: @@ -17164,12 +17257,12 @@ snapshots: json-schema-traverse: 1.0.0 require-from-string: 2.0.2 - alchemy@2.0.0-beta.84(patch_hash=824006659fa28ca31e490ce1fc3611f77436005ce9fa0f638be46564133cf042)(@effect/platform-node@4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@effect/vitest@4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(effect@4.0.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)): + alchemy@2.0.0-beta.85(@effect/platform-bun@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.2)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)): dependencies: - '@alchemy.run/node-utils': 2.0.0-beta.84 + '@alchemy.run/node-utils': 2.0.0-beta.85 '@alchemy.run/sigil': 0.1.0-alpha.1(@types/react@19.3.0)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6)) capnweb: 0.12.0 - effect: 4.0.5 + effect: 4.1.2 fflate: 0.8.3 pathe: 2.0.3 picomatch: 4.0.7 @@ -17177,8 +17270,8 @@ snapshots: tinyglobby: 0.2.17 yaml: 2.9.0 optionalDependencies: - '@effect/platform-node': 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6) - '@effect/vitest': 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + '@effect/platform-bun': 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6) + '@effect/platform-node': 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) vite: '@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0)' ws: 8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6) transitivePeerDependencies: @@ -18126,18 +18219,17 @@ snapshots: get-tsconfig: 4.14.3 jiti: 2.7.0 - drizzle-orm@1.0.0-rc.5-ab785fc(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.0.6(effect@4.0.5))(@effect/sql-pg@4.0.5(effect@4.0.5))(@effect/sql-sqlite-bun@4.0.0-rc.112(effect@4.0.5))(@effect/sql-sqlite-do@4.0.5(effect@4.0.5))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.0.5)(expo-sqlite@58.0.13(expo@58.0.14)(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.5): + drizzle-orm@1.0.0-rc.5-ab785fc(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.2))(@effect/sql-pg@4.1.2(effect@4.1.2))(@effect/sql-sqlite-do@4.1.2(effect@4.1.2))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.2)(expo-sqlite@58.0.13(expo@58.0.14)(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.5): optionalDependencies: '@cloudflare/workers-types': 4.20260604.1 - '@effect/sql-d1': 4.0.6(effect@4.0.5) - '@effect/sql-pg': 4.0.5(effect@4.0.5) - '@effect/sql-sqlite-bun': 4.0.0-rc.112(effect@4.0.5) - '@effect/sql-sqlite-do': 4.0.5(effect@4.0.5) + '@effect/sql-d1': 4.1.1(effect@4.1.2) + '@effect/sql-pg': 4.1.2(effect@4.1.2) + '@effect/sql-sqlite-do': 4.1.2(effect@4.1.2) '@electric-sql/pglite': 0.3.15 '@libsql/client': 0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6) '@types/sql.js': 1.4.11 bun-types: 1.3.14 - effect: 4.0.5 + effect: 4.1.2 expo-sqlite: 58.0.13(expo@58.0.14)(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) pg: 8.23.0 sql.js: 1.15.0 @@ -18159,7 +18251,7 @@ snapshots: ee-first@1.1.1: {} - effect@4.0.5: {} + effect@4.1.2: {} ejs@3.1.10: dependencies: @@ -22791,13 +22883,13 @@ snapshots: why-is-node-running@3.2.1: {} - workerd@1.20261012.1: + workerd@1.20261026.1: optionalDependencies: - '@cloudflare/workerd-darwin-64': 1.20261012.1 - '@cloudflare/workerd-darwin-arm64': 1.20261012.1 - '@cloudflare/workerd-linux-64': 1.20261012.1 - '@cloudflare/workerd-linux-arm64': 1.20261012.1 - '@cloudflare/workerd-windows-64': 1.20261012.1 + '@cloudflare/workerd-darwin-64': 1.20261026.1 + '@cloudflare/workerd-darwin-arm64': 1.20261026.1 + '@cloudflare/workerd-linux-64': 1.20261026.1 + '@cloudflare/workerd-linux-arm64': 1.20261026.1 + '@cloudflare/workerd-windows-64': 1.20261026.1 wrap-ansi@7.0.0: dependencies: diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 9283ca93f4fb3..1c3721dc2e9db 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -30,10 +30,11 @@ allowBuilds: workerd: false catalog: - "@alchemy.run/axiom": 2.0.0-beta.84 - "@alchemy.run/cloudflare": 2.0.0-beta.84 - "@alchemy.run/drizzle": 2.0.0-beta.84 - "@alchemy.run/planetscale": 2.0.0-beta.84 + "@alchemy.run/axiom": 2.0.0-beta.85 + "@alchemy.run/cloudflare": 2.0.0-beta.85 + "@alchemy.run/drizzle": 2.0.0-beta.85 + "@alchemy.run/planetscale": 2.0.0-beta.85 + "@alchemy.run/test": 2.0.0-beta.85 "@clerk/backend": 3.25.0 "@clerk/clerk-js": 6.40.0 "@clerk/electron": 0.1.3 @@ -43,15 +44,16 @@ catalog: "@clerk/shared": 4.41.0 # Must match the version alchemy depends on: the relay overrides its # Cloudflare retry policy through this package's Retry service. - "@distilled.cloud/cloudflare": 1.0.0-rc.17 - "@effect/atom-react": 4.0.5 - "@effect/graphql-generator": 4.0.5 - "@effect/openapi-generator": 4.0.5 - "@effect/platform-node": 4.0.5 - "@effect/platform-node-shared": 4.0.5 - "@effect/sql-pg": 4.0.5 - "@effect/sql-sqlite-do": 4.0.5 - "@effect/vitest": 4.0.5 + "@distilled.cloud/cloudflare": 1.0.0-rc.18 + "@effect/atom-react": 4.1.2 + "@effect/graphql-generator": 4.1.2 + "@effect/openapi-generator": 4.1.2 + "@effect/platform-bun": 4.1.2 + "@effect/platform-node": 4.1.2 + "@effect/platform-node-shared": 4.1.2 + "@effect/sql-pg": 4.1.2 + "@effect/sql-sqlite-do": 4.1.2 + "@effect/vitest": 4.1.2 "@electron-webauthn/macos": 1.3.1 "@legendapp/list": 3.3.5 "@noble/curves": 1.9.1 @@ -66,8 +68,8 @@ catalog: "@types/react": ~19.3.0 "@types/react-dom": ~19.3.0 "@types/ws": 8.18.2 - alchemy: 2.0.0-beta.84 - effect: 4.0.5 + alchemy: 2.0.0-beta.85 + effect: 4.1.2 electron-webauthn: 1.3.1 jose: 6.2.2 lightningcss: 1.33.0 @@ -98,23 +100,24 @@ catalog: unified: 11.0.5 minimumReleaseAgeExclude: - - alchemy@2.0.0-beta.84 - - "@alchemy.run/acme@2.0.0-beta.84" - - "@alchemy.run/axiom@2.0.0-beta.84" - - "@alchemy.run/cloudflare@2.0.0-beta.84" - - "@alchemy.run/cloudflare-runtime@2.0.0-beta.84" - - "@alchemy.run/docker@2.0.0-beta.84" - - "@alchemy.run/drizzle@2.0.0-beta.84" - - "@alchemy.run/node-utils@2.0.0-beta.84" - - "@alchemy.run/planetscale@2.0.0-beta.84" - - "@alchemy.run/sql@2.0.0-beta.84" - - "@distilled.cloud/acme@1.0.0-rc.17" - - "@distilled.cloud/aws4signer@1.0.0-rc.17" - - "@distilled.cloud/axiom@1.0.0-rc.17" - - "@distilled.cloud/cloudflare@1.0.0-rc.17" - - "@distilled.cloud/core@1.0.0-rc.17" - - "@distilled.cloud/iceberg@1.0.0-rc.17" - - "@distilled.cloud/planetscale@1.0.0-rc.17" + - alchemy@2.0.0-beta.85 + - "@alchemy.run/acme@2.0.0-beta.85" + - "@alchemy.run/axiom@2.0.0-beta.85" + - "@alchemy.run/cloudflare@2.0.0-beta.85" + - "@alchemy.run/cloudflare-runtime@2.0.0-beta.85" + - "@alchemy.run/docker@2.0.0-beta.85" + - "@alchemy.run/drizzle@2.0.0-beta.85" + - "@alchemy.run/node-utils@2.0.0-beta.85" + - "@alchemy.run/planetscale@2.0.0-beta.85" + - "@alchemy.run/sql@2.0.0-beta.85" + - "@alchemy.run/test@2.0.0-beta.85" + - "@distilled.cloud/acme@1.0.0-rc.18" + - "@distilled.cloud/aws4signer@1.0.0-rc.18" + - "@distilled.cloud/axiom@1.0.0-rc.18" + - "@distilled.cloud/cloudflare@1.0.0-rc.18" + - "@distilled.cloud/core@1.0.0-rc.18" + - "@distilled.cloud/iceberg@1.0.0-rc.18" + - "@distilled.cloud/planetscale@1.0.0-rc.18" - "@tsc-rs/*" - expo-glass-effect@58.0.4 - expo-blur@58.0.4 @@ -126,15 +129,16 @@ minimumReleaseAgeExclude: - "@clerk/expo@4.14.0" - "@clerk/react@6.18.0" - "@clerk/shared@4.41.0" - - "@effect/atom-react@4.0.5" - - "@effect/graphql-generator@4.0.5" - - "@effect/openapi-generator@4.0.5" - - "@effect/platform-node-shared@4.0.5" - - "@effect/platform-node@4.0.5" - - "@effect/sql-pg@4.0.5" - - "@effect/sql-sqlite-do@4.0.5" - - "@effect/vitest@4.0.5" - - effect@4.0.5 + - "@effect/atom-react@4.1.2" + - "@effect/graphql-generator@4.1.2" + - "@effect/openapi-generator@4.1.2" + - "@effect/platform-node-shared@4.1.2" + - "@effect/platform-bun@4.1.2" + - "@effect/platform-node@4.1.2" + - "@effect/sql-pg@4.1.2" + - "@effect/sql-sqlite-do@4.1.2" + - "@effect/vitest@4.1.2" + - effect@4.1.2 - "@legendapp/list@3.3.5" - "@expo/cli@58.1.1 || 58.1.9 || 58.1.11" - "@expo/env@2.5.1" @@ -171,7 +175,6 @@ minimumReleaseAgeExclude: - expo-sqlite@58.0.13 - expo-symbols@58.0.4 - electron@44.10.0 - - "@anthropic-ai/claude-agent-sdk@0.3.276" - "@shadcn/lint@0.1.5" - cn@0.3.2 - uniwind@1.13.0 @@ -227,6 +230,13 @@ minimumReleaseAgeExclude: - "@pierre/highlights@0.2.0" - "@pierre/theming@1.0.2" - agent-device@0.21.32 + - "@cursor/sdk-darwin-arm64@1.2.0" + - "@cursor/sdk-darwin-x64@1.2.0" + - "@cursor/sdk-linux-arm64@1.2.0" + - "@cursor/sdk-linux-x64@1.2.0" + - "@cursor/sdk-win32-x64@1.2.0" + - "@cursor/sdk@1.2.0" + - "@distilled.cloud/aws@1.0.0-rc.18" overrides: # Pin every patched package, including transitive dependencies, so lockfile-free @@ -297,6 +307,7 @@ overrides: "@clerk/react": "catalog:" "@clerk/shared": "catalog:" "@effect/atom-react": "catalog:" + "@effect/platform-bun": "catalog:" "@effect/platform-node": "catalog:" "@effect/platform-node-shared": "catalog:" "@effect/sql-pg": "catalog:" @@ -361,7 +372,6 @@ patchedDependencies: micromark-extension-gfm-table@2.1.1: patches/micromark-extension-gfm-table@2.1.1.patch micromark@4.0.2: patches/micromark@4.0.2.patch mdast-util-to-hast@13.2.1: patches/mdast-util-to-hast@13.2.1.patch - alchemy@2.0.0-beta.84: patches/alchemy@2.0.0-beta.84.patch expo-audio@58.0.9: patches/expo-audio@58.0.9.patch expo-video@58.0.11: patches/expo-video@58.0.11.patch expo-network@58.0.3: patches/expo-network@58.0.3.patch @@ -370,7 +380,8 @@ patchedDependencies: # Use the app's Android Gradle and Kotlin plugins for the local markdown tarball. react-native-enriched-markdown@1.2.0-t3.16: patches/react-native-enriched-markdown@1.2.0-t3.16.patch "@clerk/expo-native-components@0.4.0": patches/@clerk__expo-native-components@0.4.0.patch - "@effect/vitest@4.0.5": patches/@effect__vitest@4.0.5.patch + "@alchemy.run/test@2.0.0-beta.85": patches/@alchemy.run__test@2.0.0-beta.85.patch + "@effect/vitest@4.1.2": patches/@effect__vitest@4.1.2.patch "@expo/metro-config@58.0.14": patches/@expo__metro-config@58.0.14.patch expo-sharing@58.0.19: patches/expo-sharing@58.0.19.patch # Keep iOS activity fixes plus Android instance configuration and cold-start deep links. diff --git a/scripts/build-desktop-artifact.ts b/scripts/build-desktop-artifact.ts index a1cc822fe8e46..40fb95ef7d342 100644 --- a/scripts/build-desktop-artifact.ts +++ b/scripts/build-desktop-artifact.ts @@ -2891,6 +2891,7 @@ export const createBuildConfig = Effect.fn("createBuildConfig")(function* ( buildConfig.toolsets = { appimage: "1.0.3" }; const path = yield* Path.Path; const repoRoot = yield* RepoRoot; + buildConfig.afterPack = path.join(repoRoot, "scripts/linux-after-pack.ts"); buildConfig.linux = { target: target === "AppImage" ? [target, "deb"] : [target], executableName: "t3code", diff --git a/scripts/check-changed.test.ts b/scripts/check-changed.test.ts index eaba712f4c516..17c9b2b4bb2ee 100644 --- a/scripts/check-changed.test.ts +++ b/scripts/check-changed.test.ts @@ -397,7 +397,7 @@ it("checks changed source paths through the Windows launcher", () => { expect(result.status, result.stdout + result.stderr).toBe(0); const calls = project.calls(); expect(calls.find(({ args }) => args[0] === "lint")).toEqual({ - args: ["lint", project.source], + args: ["lint", "--no-error-on-unmatched-pattern", project.source], cwd: project.root, }); expect(calls.some(({ args }) => args[0] === "fmt" && args.includes(project.source))).toBe(true); @@ -407,6 +407,21 @@ it("checks changed source paths through the Windows launcher", () => { expect(result.stdout).toContain("fixture stderr: lint"); }); +it("lints an Astro component and runs knip when only it changed", () => { + using project = launcherFixture(); + const page = "packages/example/Page.astro"; + project.write(page, "---\nconst title = 1;\n---\n

    {title}

    \n"); + const result = project.run(); + expect(result.status, result.stdout + result.stderr).toBe(0); + const calls = project.calls(); + expect(calls.find(({ args }) => args[0] === "lint")?.args).toEqual([ + "lint", + "--no-error-on-unmatched-pattern", + page, + ]); + expect(calls.some(({ args }) => args[0] === "exec" && args[1] === "knip")).toBe(true); +}); + it.each(["install", "lint"])("reports a failing %s step with its output", (step) => { using project = launcherFixture(); project.write(project.source, "export const value = 2;\n"); diff --git a/scripts/check-changed.ts b/scripts/check-changed.ts index 0bf96fb98ca3f..274ad9dacd314 100644 --- a/scripts/check-changed.ts +++ b/scripts/check-changed.ts @@ -172,7 +172,8 @@ export const comparisonBase = Effect.fn("checkChanged.comparisonBase")(function* return closest; }); -const CODE = /\.[cm]?[jt]sx?$/; +// CI's lint and knip also read Astro components' frontmatter. +const CODE = /\.(?:[cm]?[jt]sx?|astro)$/; const TEST = /\.test\.[cm]?[jt]sx?$/; // CI runs the .github/scripts tests with `node --test`; vitest passes a failing node:test file. const NODE_TEST = /^\.github[/\\]scripts[/\\]/; @@ -469,7 +470,9 @@ const checkChanged = Effect.fn("checkChanged")(function* (input: { ...(present.length > 0 ? [command("format", ["fmt", "--check", "--no-error-on-unmatched-pattern", ...present])] : []), - ...(code.length > 0 ? [command("lint", ["lint", ...code])] : []), + ...(code.length > 0 + ? [command("lint", ["lint", "--no-error-on-unmatched-pattern", ...code])] + : []), ...(runKnip ? knipPasses.map((args, index) => command(`knip ${index + 1}/${knipPasses.length}`, args)) : []), diff --git a/scripts/install.sh b/scripts/install.sh index e445459337c65..da7e540755691 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -20,6 +20,14 @@ set -eu repo="issuelt/t3code" base_url="${T3CODE_RELEASE_BASE_URL:-https://github.com/${repo}/releases/download}" t3_home="${T3CODE_HOME:-$HOME/.t3}" +case "$t3_home" in + /*) ;; + *) + # Preserve cwd's trailing newlines; trim only pwd's newline and the sentinel. + t3_cwd="$(pwd -P && printf .)" + t3_home="${t3_cwd%??}/$t3_home" + ;; +esac bin_dir="${T3CODE_INSTALL_BIN_DIR:-$HOME/.local/bin}" fail() { diff --git a/scripts/install.test.ts b/scripts/install.test.ts index 461deb7562d14..379b127a58cf4 100644 --- a/scripts/install.test.ts +++ b/scripts/install.test.ts @@ -12,6 +12,54 @@ const nightlies = Array.from({ length: 100 }, (_, index) => ({ tag_name: `v1.2.4-nightly.20261020.${200 - index}`, })); +describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")("installer home", () => { + it("installs a relative home from a directory ending in a newline", async () => { + const temporaryRoot = await NodeFSP.realpath( + await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-install-home-")), + ); + const root = NodePath.join(temporaryRoot, "cwd\n"); + const homeName = "-custom home\\home\n"; + const home = NodePath.join(root, homeName); + const version = "1.2.3"; + const target = NodePath.join(home, "runtime/versions", version); + const launcher = NodePath.join(root, "bin/t3"); + try { + await NodeFSP.mkdir(target, { recursive: true }); + await NodeFSP.writeFile(NodePath.join(target, ".install-complete"), `${version}\n`); + await NodeFSP.writeFile(NodePath.join(target, "t3"), "#!/bin/sh\necho 't3 v1.2.3'\n", { + mode: 0o755, + }); + const { status, stdout, stderr } = NodeChildProcess.spawnSync( + "sh", + [NodePath.resolve(import.meta.dirname, "install.sh")], + { + cwd: root, + env: { + ...process.env, + HOME: root, + T3CODE_HOME: homeName, + T3CODE_VERSION: version, + T3CODE_INSTALL_BIN_DIR: NodePath.dirname(launcher), + T3CODE_RELEASE_BASE_URL: "http://127.0.0.1:1", + }, + encoding: "utf8", + }, + ); + expect(status, stdout + stderr).toBe(0); + expect(stderr).toContain(`Installed T3 Code ${version}`); + expect(await NodeFSP.readlink(launcher)).toBe(NodePath.join(target, "t3")); + expect( + NodeChildProcess.execFileSync(launcher, ["--version"], { + cwd: NodeOS.tmpdir(), + encoding: "utf8", + }).trim(), + ).toBe("t3 v1.2.3"); + } finally { + await NodeFSP.rm(temporaryRoot, { recursive: true, force: true }); + } + }); +}); + // regression: #22490 describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")("installer channel lookup", () => { it.each([ diff --git a/scripts/lib/server-compile-cache.test.ts b/scripts/lib/server-compile-cache.test.ts index bb9294c54219c..9853d4aed85fb 100644 --- a/scripts/lib/server-compile-cache.test.ts +++ b/scripts/lib/server-compile-cache.test.ts @@ -25,6 +25,67 @@ it.each(["x64", "arm64"])("skips prepared bytecode generation on Linux %s", asyn expect(result.stdout).toContain("Skipping unsupported target linux"); }); +it("prepares macOS x64 cache on an ARM64 build host", async () => { + const { spawnSync } = await import("node:child_process"); + const root = NodeFS.realpathSync( + NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-rosetta-cache-")), + ); + try { + const resources = NodePath.join(root, "Fixture.app", "Contents", "Resources"); + const archive = NodePath.join(resources, "app.asar"); + const dist = NodePath.join(archive, "apps/server/dist"); + const helper = NodePath.join(archive, "apps/desktop/dist-electron/serverCompileCache.cjs"); + NodeFS.mkdirSync(dist, { recursive: true }); + NodeFS.mkdirSync(NodePath.dirname(helper), { recursive: true }); + NodeFS.writeFileSync(NodePath.join(dist, "binCli-fixture.mjs"), "export const answer = 42;"); + NodeFS.writeFileSync( + helper, + `module.exports = require(${JSON.stringify(NodeURL.fileURLToPath(new URL("./server-compile-cache.ts", import.meta.url)))});`, + ); + const hook = NodeURL.fileURLToPath( + new URL("../prepare-server-compile-cache.cjs", import.meta.url), + ); + // The fixture uses Node for generation; the hook still sees an ARM64 macOS build host. + const result = spawnSync( + process.execPath, + [ + "-e", + ` + const childProcess = require("node:child_process"); + const spawn = childProcess.spawnSync; + childProcess.spawnSync = (executable, args, options) => { + require("node:assert/strict").equal(executable, ${JSON.stringify(NodePath.join(root, "Fixture.app", "Contents", "MacOS", "Fixture"))}); + return spawn(process.execPath, args, options); + }; + Object.defineProperty(process, "platform", { value: "darwin" }); + Object.defineProperty(process, "arch", { value: "arm64" }); + require(${JSON.stringify(hook)})({ + appOutDir: ${JSON.stringify(root)}, electronPlatformName: "darwin", arch: 1, + packager: { appInfo: { productFilename: "Fixture" } } + }).catch(error => { console.error(error); process.exitCode = 1; }); + `, + ], + { encoding: "utf8" }, + ); + expect(result.status, result.stderr).toBe(0); + const manifest = JSON.parse( + NodeFS.readFileSync(NodePath.join(resources, "server-compile-cache/manifest.json"), "utf8"), + ); + expect(manifest.entries).toEqual([ + { + module: "app.asar/apps/server/dist/binCli-fixture.mjs", + file: expect.stringMatching(/^[a-f0-9]{8}$/), + }, + ]); + expect( + NodeFS.statSync(NodePath.join(resources, "server-compile-cache", manifest.entries[0].file)) + .size, + ).toBeGreaterThan(0); + } finally { + NodeFS.rmSync(root, { recursive: true, force: true }); + } +}); + it("seeds relocated cache entries without allowing writes into shipped resources", () => { const root = NodeFS.realpathSync( NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-prepared-test-")), diff --git a/scripts/linux-after-pack.test.ts b/scripts/linux-after-pack.test.ts new file mode 100644 index 0000000000000..7171ac4b1f884 --- /dev/null +++ b/scripts/linux-after-pack.test.ts @@ -0,0 +1,43 @@ +// @effect-diagnostics nodeBuiltinImport:off - Applies real file modes in a temporary app folder. +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as NodeFSP from "node:fs/promises"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; +import { describe, expect, it } from "vite-plus/test"; + +import { removeSharedWriteAccess } from "./linux-after-pack.ts"; + +describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("removeSharedWriteAccess", () => { + it("removes group and other write access from the packed app only", async () => { + const root = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-after-pack-")); + try { + const appOutDir = NodePath.join(root, "app"); + const modes = { + "app/t3code": [0o777, 0o755], + "app/resources.pak": [0o666, 0o644], + "app/chrome-sandbox": [0o4777, 0o4755], + "app/resources/app.asar": [0o644, 0o644], + "outside/file": [0o666, 0o666], + } as const; + await NodeFSP.mkdir(NodePath.join(appOutDir, "resources"), { recursive: true }); + await NodeFSP.mkdir(NodePath.join(root, "outside")); + for (const [file, [before]] of Object.entries(modes)) { + await NodeFSP.writeFile(NodePath.join(root, file), ""); + await NodeFSP.chmod(NodePath.join(root, file), before); + } + await NodeFSP.chmod(NodePath.join(appOutDir, "resources"), 0o777); + await NodeFSP.symlink("../outside", NodePath.join(appOutDir, "linked-dir")); + + await removeSharedWriteAccess(appOutDir); + + for (const [file, [, after]] of Object.entries(modes)) { + const { mode } = await NodeFSP.stat(NodePath.join(root, file)); + expect([file, mode & 0o7777]).toEqual([file, after]); + } + const { mode: resourcesMode } = await NodeFSP.stat(NodePath.join(appOutDir, "resources")); + expect(resourcesMode & 0o7777).toBe(0o755); + } finally { + await NodeFSP.rm(root, { recursive: true, force: true }); + } + }); +}); diff --git a/scripts/linux-after-pack.ts b/scripts/linux-after-pack.ts new file mode 100644 index 0000000000000..37ccab08ede3e --- /dev/null +++ b/scripts/linux-after-pack.ts @@ -0,0 +1,29 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeFSP from "node:fs/promises"; +import * as NodeModule from "node:module"; +import * as NodePath from "node:path"; + +const prepareServerCompileCache: (context: AfterPackContext) => Promise = + NodeModule.createRequire(import.meta.url)("./prepare-server-compile-cache.cjs"); + +interface AfterPackContext { + readonly appOutDir: string; +} + +// Electron's Linux zips can ship world-writable files (44.10.0 has 0777 binaries), and +// electron-builder copies zip modes verbatim into the .deb and AppImage. +export default async function afterPack(context: AfterPackContext): Promise { + await prepareServerCompileCache(context); + await removeSharedWriteAccess(context.appOutDir); +} + +// Walks by hand: recursive readdir follows directory symlinks out of the app folder. +export async function removeSharedWriteAccess(path: string): Promise { + const stats = await NodeFSP.lstat(path); + if (stats.isSymbolicLink()) return; + if (stats.mode & 0o022) await NodeFSP.chmod(path, stats.mode & 0o7755); + if (!stats.isDirectory()) return; + for (const entry of await NodeFSP.readdir(path)) { + await removeSharedWriteAccess(NodePath.join(path, entry)); + } +} diff --git a/scripts/mobile-behavior/device.ts b/scripts/mobile-behavior/device.ts index 916e3adb21245..e29cb0734463a 100644 --- a/scripts/mobile-behavior/device.ts +++ b/scripts/mobile-behavior/device.ts @@ -7,7 +7,7 @@ import * as NodeChildProcess from "node:child_process"; import * as NodeOS from "node:os"; import * as NodePath from "node:path"; -import * as NodeSocket from "@effect/platform-node/NodeSocket"; +import * as NodeWS from "@effect/platform-node/NodeWS"; import * as Clock from "effect/Clock"; import * as Effect from "effect/Effect"; import * as Schedule from "effect/Schedule"; @@ -183,7 +183,7 @@ export function makeDevice(options: DeviceOptions) { } }, Effect.scoped, - Effect.provide(NodeSocket.layerWebSocketConstructorWS), + Effect.provide(NodeWS.layerWebSocketConstructor), Effect.timeoutOrElse({ duration: "20 seconds", orElse: () => Effect.fail(new DeviceError({ message: "The inspector did not answer." })), diff --git a/scripts/mobile-behavior/environment.ts b/scripts/mobile-behavior/environment.ts index aa526a1d943e0..000e8d2f030bb 100644 --- a/scripts/mobile-behavior/environment.ts +++ b/scripts/mobile-behavior/environment.ts @@ -7,7 +7,7 @@ import * as NodeChildProcess from "node:child_process"; import * as NodeFS from "node:fs"; import * as NodeNet from "node:net"; import * as NodePath from "node:path"; -import * as NodeSocket from "@effect/platform-node/NodeSocket"; +import * as NodeWS from "@effect/platform-node/NodeWS"; import { CommandId, EnvironmentId, @@ -22,7 +22,7 @@ import { WsRpcGroup, type OrchestrationV2ThreadProjection, } from "@t3tools/contracts"; -import * as Crypto from "effect/Crypto"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; @@ -34,7 +34,7 @@ const REPO_ROOT = NodePath.resolve(import.meta.dirname, "../.."); export const EVAL_INSTANCE = ProviderInstanceId.make("evalbot"); export const EVAL_MODEL = "eval/scripted"; -export const uuid = Effect.flatMap(Crypto.Crypto, (crypto) => crypto.randomUUIDv4()); +export const uuid = Effect.flatMap(SecureRandom.SecureRandom, (random) => random.uuidV4()); export class EnvironmentError extends Schema.TaggedError()("EnvironmentError", { message: Schema.String, @@ -226,7 +226,7 @@ export const startEnvironment = Effect.fn("environment.start")(function* (input: ), ), Layer.provide(RpcSerialization.layerJson), - Layer.provide(NodeSocket.layerWebSocketConstructorWS), + Layer.provide(NodeWS.layerWebSocketConstructor), ), ); const client = yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol)); diff --git a/scripts/mobile-behavior/run.ts b/scripts/mobile-behavior/run.ts index 3a75d243113c5..516a145c7f920 100644 --- a/scripts/mobile-behavior/run.ts +++ b/scripts/mobile-behavior/run.ts @@ -9,6 +9,7 @@ import * as NodeFS from "node:fs"; import * as NodeOS from "node:os"; import * as NodePath from "node:path"; import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import * as Clock from "effect/Clock"; import * as Console from "effect/Console"; @@ -293,6 +294,6 @@ const command = Command.make( ); Command.run(command, { version: "0.0.0" }).pipe( - Effect.provide(NodeServices.layer), + Effect.provide([NodeServices.layer, NodeCrypto.layer]), NodeRuntime.runMain, ); diff --git a/scripts/mobile-behavior/scenarios.ts b/scripts/mobile-behavior/scenarios.ts index 7222086413f80..4d971d4e87f76 100644 --- a/scripts/mobile-behavior/scenarios.ts +++ b/scripts/mobile-behavior/scenarios.ts @@ -4,7 +4,7 @@ * scenario and check its metrics, so one flow can serve several issues. */ import type { ThreadId } from "@t3tools/contracts"; -import type * as Crypto from "effect/Crypto"; +import type * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; @@ -157,7 +157,9 @@ const failure = (effect: Effect.Effect) => new ScenarioFailure({ message: error instanceof Error ? error.message : String(error) }), ); -type Scenario = (ctx: ScenarioContext) => Effect.Effect; +type Scenario = ( + ctx: ScenarioContext, +) => Effect.Effect; export const SCENARIOS = { /** Six upward flings in the long settled thread. */ diff --git a/scripts/mobile-native-client.ts b/scripts/mobile-native-client.ts index 74e914312b618..ca859c259fb38 100644 --- a/scripts/mobile-native-client.ts +++ b/scripts/mobile-native-client.ts @@ -1,4 +1,5 @@ import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { isCommandAvailable, resolveSpawnCommand } from "@t3tools/shared/shell"; @@ -6,7 +7,7 @@ import * as Clock from "effect/Clock"; import * as Console from "effect/Console"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; -import * as Crypto from "effect/Crypto"; +import * as Digest from "effect/crypto/Digest"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; @@ -83,9 +84,9 @@ export const ensureClient = Effect.fn("ensureClient")(function* (o }); const digest = Effect.fn("nativeClient.digest")(function* (value: string | Uint8Array) { - const crypto = yield* Crypto.Crypto; + const crypto = yield* Digest.Digest; const bytes = yield* crypto.digest( - "SHA-256", + Digest.sha256, typeof value === "string" ? new TextEncoder().encode(value) : value, ); return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join(""); @@ -98,7 +99,7 @@ export const hashBundle = Effect.fn("hashBundle")(function* (root: string) { const entries: string[] = []; const visit = Effect.fn("mobile-native-client.visit")(function* ( relative: string, - ): Effect.fn.Return { + ): Effect.fn.Return { const names = (yield* fs.readDirectory(path.join(root, relative))).sort((a, b) => a.localeCompare(b, "en"), ); @@ -1207,7 +1208,7 @@ if (import.meta.main) { ), }), Effect.scoped, - Effect.provide([NodeServices.layer, FetchHttpClient.layer]), + Effect.provide([NodeServices.layer, NodeCrypto.layer, FetchHttpClient.layer]), NodeRuntime.runMain, ); } diff --git a/scripts/prepare-server-compile-cache.cjs b/scripts/prepare-server-compile-cache.cjs index 1c4b886d115ac..e2918c852bf7c 100644 --- a/scripts/prepare-server-compile-cache.cjs +++ b/scripts/prepare-server-compile-cache.cjs @@ -12,7 +12,15 @@ module.exports = async ({ appOutDir, electronPlatformName, arch, packager }) => return; } const targetArch = ["ia32", "x64", "armv7l", "arm64", "universal"][arch]; - if (electronPlatformName !== process.platform || targetArch !== process.arch) { + const runsWithRosetta = + electronPlatformName === "darwin" && + process.platform === "darwin" && + process.arch === "arm64" && + targetArch === "x64"; + if ( + electronPlatformName !== process.platform || + (targetArch !== process.arch && !runsWithRosetta) + ) { console.log( `[server-compile-cache] Skipping unexecutable target ${electronPlatformName}/${targetArch}`, ); @@ -43,14 +51,14 @@ module.exports = async ({ appOutDir, electronPlatformName, arch, packager }) => env.T3CODE_HOME = state; let result; try { - result = spawnSync( - executable, - [ - "-e", - `require(${JSON.stringify(helper)}).generatePreparedServerCache(${JSON.stringify(resources)}).then(()=>process.exit(0),e=>{console.error(e);process.exit(1)})`, - ], - { env, encoding: "utf8", timeout: 120000 }, + // Run a script file, not -e: -e defines a global __filename of "[eval]", which + // @effect/platform-node passes to createRequire and fails on. + const runner = path.join(state, "prepare-server-compile-cache-runner.cjs"); + fs.writeFileSync( + runner, + `require(${JSON.stringify(helper)}).generatePreparedServerCache(${JSON.stringify(resources)}).then(()=>process.exit(0),e=>{console.error(e);process.exit(1)})`, ); + result = spawnSync(executable, [runner], { env, encoding: "utf8", timeout: 120000 }); } finally { fs.rmSync(state, { recursive: true, force: true }); } diff --git a/scripts/release-smoke.ts b/scripts/release-smoke.ts index 8f300533523ae..a586d67ef6035 100644 --- a/scripts/release-smoke.ts +++ b/scripts/release-smoke.ts @@ -37,6 +37,7 @@ const workspaceFiles = [ "packages/provider-cursor/package.json", "packages/provider-fx/package.json", "packages/provider-grok/package.json", + "packages/provider-kiro/package.json", "packages/provider-muse/package.json", "packages/provider-opencode/package.json", "packages/secret-provider-core/package.json",